Exemple #1
0
  def __init__(self,ip,port):
#    global flyermmap
    print(posix_ipc.MESSAGE_QUEUES_SUPPORTED)
    print(posix_ipc.QUEUE_MESSAGES_MAX_DEFAULT)
    print(posix_ipc.QUEUE_MESSAGE_SIZE_MAX_DEFAULT)
    self.model_pub = rospy.Publisher("/gazebo/set_model_state",ModelState,queue_size=1)
    self.bridge = CvBridge()
    #self.image_sub = rospy.Subscriber("/mycam/image_raw",Image,self.callback)
    self.image_sub = rospy.Subscriber("/multisense/camera/left/image_raw",Image,self.callback)
    self.imageflag = 0
    self.imagecnt = 0
    self.key = 0
    firstFoot = Foot([0,-0.1,0],Foot.RIGHT)
    standingFoot = Foot([0,0.1,0],Foot.LEFT)
    self.list = Steplist(firstFoot,standingFoot)
    self.height = 1.6
    self.tilt = 0.0
    memory = posix_ipc.SharedMemory("flyermmap", posix_ipc.O_CREAT, size=8*Mib)
    self.sem = posix_ipc.Semaphore("flyersem", posix_ipc.O_CREAT)
    self.memmap = mmap.mmap(memory.fd, memory.size)
#    flyermmap = self.memmap
    memory.close_fd()
    self.queue = posix_ipc.MessageQueue("/flyerqueue", posix_ipc.O_CREAT)
    #self.wsproc = prc.Popen('python flyerws.py', shell=True )
    self.wsproc = prc.Popen('python -u flyerws.py --ip %s --port %s' % (ip,port), shell=True )
    self.writecnt = 0
    self.loc = (0,0,0)
    self.walker = Walker()
    self.walker.init()
Exemple #2
0
class APlayer(threading.Thread):

    mpd = None
    mainloop = None

    def __init__(self):
        self.volume = 0
        self.isPlaying = False
        self.isRandom = False
        self.walker = Walker()
        self.currentlyPlaying = {}
        self.nextId = []
        self.currentPlaylist = ""
        self.watchCurrentSubscriber = []
        self.timer = None

        try:
            self.mpd = MPDClient()
            self.mpd.timeout = 10;
            self.mpd.idletimeout = None
            self.walker.setMPD(self)
        except Exception, e:
            print "Problem with setting up the mpd stuff"
            print "Error: {0}".format(str(e))

        threading.Thread.__init__(self)
Exemple #3
0
    def __init__(self, model_dir, config, node_feat_dim, edge_feat_dim, out_dim, loss, node_feat_enc=None, edge_feat_enc=None):
        """
        :param model_dir: Directory to store model in
        :param config: Python Dict that specifies the configuration of the model
        :param node_feat_dim: Dimension of the node features
        :param edge_feat_dim: Dimension of the edge features
        :param out_dim: Output dimension
        :param loss: torch.nn Loss object used for training
        :param node_feat_enc: Optional initial embedding of node features
        :param edge_feat_enc: Optional initial embedding of edge features
        """
        super(CRaWl, self).__init__()
        self.model_dir = model_dir
        self.config = config
        self.out_dim = out_dim
        self.node_feat_enc = node_feat_enc
        self.edge_feat_enc = edge_feat_enc

        self.layers = config['layers']
        self.hidden = config['hidden_dim']
        self.kernel_size = config['kernel_size']
        self.dropout = config['dropout']

        self.pool = config['pool'] if 'pool' in config.keys() else 'mean'
        self.vn = config['vn'] if 'vn' in config.keys() else False

        self.walker = Walker(config)

        self.walk_dim = self.walker.struc_feat_dim
        self.conv_dim = config['conv_dim'] if 'conv_dim' in config.keys() else self.hidden

        modules = []
        for i in range(self.layers):
            modules.append(ConvModule(conv_dim=self.conv_dim,
                                      node_dim_in=node_feat_dim if i == 0 else self.hidden,
                                      edge_dim_in=edge_feat_dim,
                                      w_feat_dim=self.walk_dim,
                                      dim_out=self.hidden,
                                      kernel_size=self.kernel_size))

            if self.vn and i < self.layers - 1:
                modules.append(VNUpdate(self.hidden, config))

        self.convs = Sequential(*modules)

        self.node_out = Sequential(BatchNorm1d(self.hidden), ReLU())

        if config['graph_out'] == 'linear':
            self.graph_out = Sequential(Dropout(self.dropout),
                                        Linear(self.hidden, out_dim))
        else:
            self.graph_out = Sequential(Dropout(self.dropout),
                                        Linear(self.hidden, self.hidden),
                                        ReLU(),
                                        Linear(self.hidden, out_dim))

        self.criterion = loss

        pytorch_total_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
        print(f'Number of paramters: {pytorch_total_params}')
Exemple #4
0
def main(argv):

    # set up argument parsing
    parser = argparse.ArgumentParser()
    parser.add_argument('input_graph', help='Original graph input file, in\
                                             edge list format')
    parser.add_argument('seed', help='Seed file, to pull start nodes from')
    parser.add_argument('-e', '--restart_prob', type=float, default=0.7,
                        help='Restart probability for random walk')
    parser.add_argument('-l', '--low_list', nargs='?', default=None,
                        help='<Optional> List of genes expressed and\
                              unexpressed in the current tissue, if applicable')
    parser.add_argument('-n', '--node_list', nargs='?', default=None,
                        help='<Optional> Order of output probs')
    parser.add_argument('-o', '--original_graph_prob', type=float, default=0.1,
                        help='Probability of walking on the original (non-\
                              tissue specific) graph, if applicable')
    parser.add_argument('-r', '--remove', nargs='+',
                        help='<Optional> Nodes to remove from the graph, if any')
    opts = parser.parse_args()

    seed_list = generate_seed_list(opts.seed)
    node_list = get_node_list(opts.node_list) if opts.node_list else []

    # filter nodes we want to remove out of the starting seed, if any
    remove_list = opts.remove if opts.remove else []
    if remove_list:
        seed_list = [s for s in seed_list if s not in remove_list]

    # run the experiments, and write a rank list to stdout
    wk = Walker(opts.input_graph, opts.low_list, remove_list)
    wk.run_exp(seed_list, opts.restart_prob,
               opts.original_graph_prob, node_list)
Exemple #5
0
 def makeMeasurements(self):
   w = Walker(r.randint(350,450),2)
   path = w.startWalking()
   ts = datetime(2015,02,13,6)
   for x in path:
     ts = ts - timedelta(days=1)
     self.measurements.append(Measurement(ts,x,r.random()*5))
Exemple #6
0
def translate(ast, output_header, namespace=None):
    """
    Walk concord message format(CMF) AST and generate C++ code.

    Return C++ code as a string.
    """
    with open(os.path.join(os.path.dirname(__file__), "serialize.hpp")) as f:
        cmf_base_header = f.read()
    with open(os.path.join(os.path.dirname(__file__), "serialize.cpp")) as f:
        cmf_base_serialization = f.read()
    visitor = CppVisitor()
    walker = Walker(ast, visitor)
    walker.walk()

    impl = copyright() \
           + include_header(output_header) + '\n' \
           + cmf_base_serialization + '\n' \
           + file_namespace(namespace) + '\n' \
           + visitor.output \
           + file_trailer(namespace)

    header = copyright() \
             + header_guard(output_header) \
             + header_includes() + '\n' \
             + cmf_base_header + '\n' \
             + file_namespace(namespace) \
             + visitor.output_declaration + '\n' \
             + file_trailer(namespace) \
             + header_guard_trailer(output_header)

    return header, impl
Exemple #7
0
    def __init__ (self, start_dir, sqlitefile):

        if 0 and os.path.exists (sqlitefile):
            raise AlreadyExistsError, '\nERROR: sqlite_file already exists at {}\n'.format(sqlitefile)

        Walker.__init__(self, start_dir)

        self.db_table = CommsDBTable(sqlitefile)
Exemple #8
0
	def __init__(self, objectLogicPath, object):
		Live.__init__(self,objectLogicPath, object)
		Walker.__init__(self, objectLogicPath, object)
		logicFileName = object.GetLogicFileName()
		configFile=ini.IniFile(objectLogicPath)
		configFile.ReadString("npc", "group")
		self.SetHealth(configFile.ReadInt("npc", "health"))
		self._clock = sf.Clock()
		self._alarm = False
Exemple #9
0
def test_walker():
    """Test that Walker class can be used as required."""

    start, home = 10, 20
    w = Walker(start, home)
    assert not w.is_at_home()
    move()
    assert w.get_position() != start
    move()
    assert w.get_steps() == 2
Exemple #10
0
def generate_walks(network_data, num_walks, walk_length, schema, file_name):
    if schema is not None:
        node_type = load_node_type(file_name + '/node_type.txt')
    else:
        node_type = None
    from walker import Walker
    walker = Walker(network_data, num_walks, walk_length, schema, node_type)
    all_walks = walker.walk()
    print('Finish generating the walks')
    return all_walks
class RandomWalker(Sketch):
    width = 800
    height = 200

    def setup(self):
        self.walker = Walker(self)
        self.background(255)

    def draw(self):
        self.walker.step()
        self.walker.render()
Exemple #12
0
    def __init__(self):
        ''' connect to midi device and set up ros
        '''
        self.sp = SmartPAD('SmartPAD')
        self.axis = Axis()
        self.axis.init()
        self.walker = Walker()
        self.walker.init()
        self.web = pages.Pages()

        rospy.loginfo("Using input device %s" % self.sp.device)
        os.environ['PORT'] = '8081'
Exemple #13
0
def translate(ast, namespace=None):
    """
    Walk concord message format(CMF) AST and generate Python code.

    Return Python code as a string.
    """
    with open(os.path.join(os.path.dirname(__file__), "serialize.py")) as f:
        base_serializers = f.read() + '\n'
    visitor = PyVisitor()
    walker = Walker(ast, visitor)
    walker.walk()
    return header + base_serializers + visitor.output
Exemple #14
0
def translate(ast, namespace=None):
    """
    Walk concord message format(CMF) AST and generate C++ code.

    Return C++ code as a string.
    """
    with open(os.path.join(os.path.dirname(__file__), "serialize.h")) as f:
        cmf_base_serialization = f.read()
    s = cmf_base_serialization + '\n' + file_header(namespace)
    visitor = CppVisitor()
    walker = Walker(ast, visitor)
    walker.walk()
    return s + visitor.output + file_trailer(namespace)
Exemple #15
0
    def run(self, niter=50000):

        self.p0 = np.identity(26, dtype=bool)
        self.chain = np.zeros((niter+1, 26, 26), dtype=bool)
        self.probchain = np.zeros((niter+1))
        self.chain[0] = self.p0
        self.probchain[0] = self.lnprob(self.p0)
        w1 = Walker(p0=self.p0, k=30, lnprobfunc=self.lnprob)

        for i in range(niter):
            w1.iterate()
            self.chain[i+1] = w1.p
            self.probchain[i+1] = w1.lnprob
        return
Exemple #16
0
    def __init__(self):
        self.n_features = 366
        self.n_actions = 8
        self.max_epoch = 1000
        self.max_steps = 40

        # define sound source information
        self.src_pos_x = -2.0
        self.src_pos_y = 1.6
        self.src_pos_z = -4.0

        # sample as a grid map with 0.5m unit
        # change step length to 1m
        self.unit = 1.0
        self.room_grids_x = [i for i in np.arange(-3.0, 3.0 + self.unit, self.unit)]
        self.room_grids_z = [i for i in np.arange(-4.0, 4.0 + self.unit, self.unit)]

        # define wall and obstacles
        self.wall_axis_z = {-4: [i for i in np.arange(-5.0, 6.0, 1.0)],
                            4: [i for i in np.arange(-5.0, 6.0, 1.0)],
                            0: [i for i in np.arange(-5.0, 6.0, 1.0) if i != 0]}
        self.wall_axis_x = {5: [i for i in np.arange(-4.0, 5.0, 1.0)],
                            1: [i for i in np.arange(-4.0, 5.0, 1.0) if i != -2 and i != 2],
                            -1: [i for i in np.arange(-4.0, 5.0, 1.0) if i != -2 and i != 2],
                            -5: [i for i in np.arange(-4.0, 5.0, 1.0)]}

        # define checkpoints: room gates, hall center
        self.room_gates = [[-2.0, 1, -1.0], [2.0, 1, -1.0], [-2.0, 1, 1.0], [2.0, 1, 1.0]]
        self.hall_center = [[0, 0, 0]]

        # define room zone
        self.room1_x = [i for i in np.arange(-3.5, 0, 0.5)]
        self.room1_z = [i for i in np.arange(-4.5, -1, 0.5)]

        self.room2_x = [i for i in np.arange(0.5, 4.0, 0.5)]
        self.room2_z = [i for i in np.arange(-4.5, -1, 0.5)]

        self.room3_x = [i for i in np.arange(-3.5, 0, 0.5)]
        self.room3_z = [i for i in np.arange(1.5, 5.0, 0.5)]

        self.room4_x = [i for i in np.arange(0.5, 4.0, 0.5)]
        self.room4_z = [i for i in np.arange(1.5, 5.0, 0.5)]

        self.hall_x = [i for i in np.arange(-3.5, 4.0, 0.5)]
        self.hall_z = [i for i in np.arange(-0.5, 1.0, 0.5)]

        self.walker = Walker(self.n_features, self.n_actions)

        self.BayeProb = {1: 0.25, 2: 0.25, 3: 0.25, 4: 0.25}
        self.Pzx = {1: 1, 2: 1, 3: 1, 4: 1}
Exemple #17
0
def main(argv):

    # set up argument parsing
    parser = argparse.ArgumentParser()
    parser.add_argument('input_graph',
                        help='Original graph input file, in\
                                             edge list format')
    parser.add_argument('seed', help='Seed file, to pull start nodes from')
    parser.add_argument('-e',
                        '--restart_prob',
                        type=float,
                        default=0.7,
                        help='Restart probability for random walk')
    parser.add_argument('-l',
                        '--low_list',
                        nargs='?',
                        default=None,
                        help='<Optional> List of genes expressed and\
                              unexpressed in the current tissue, if applicable'
                        )
    parser.add_argument('-n',
                        '--node_list',
                        nargs='?',
                        default=None,
                        help='<Optional> Order of output probs')
    parser.add_argument('-o',
                        '--original_graph_prob',
                        type=float,
                        default=0.1,
                        help='Probability of walking on the original (non-\
                              tissue specific) graph, if applicable')
    parser.add_argument(
        '-r',
        '--remove',
        nargs='+',
        help='<Optional> Nodes to remove from the graph, if any')
    opts = parser.parse_args()

    seed_list = generate_seed_list(opts.seed)
    node_list = get_node_list(opts.node_list) if opts.node_list else []

    # filter nodes we want to remove out of the starting seed, if any
    remove_list = opts.remove if opts.remove else []
    if remove_list:
        seed_list = [s for s in seed_list if s not in remove_list]

    # run the experiments, and write a rank list to stdout
    wk = Walker(opts.input_graph, opts.low_list, remove_list)
    wk.run_exp(seed_list, opts.restart_prob, opts.original_graph_prob,
               node_list)
Exemple #18
0
 def __init__(self):
     events.AddListener(self)
     Walker.__init__(self)
     self.health = 10
     self.energy = 1
     self.xMax = 4
     self.xMin = -4
     self.yMax = 2
     self.yMin = -2
     self.state = State.fastWalking
     self.knownAvatars = []
     self.xFightingReach = 10
     self.yFightingReach = 4
     self.attack = attacks.Hug()
     self.stunCounter = 0
Exemple #19
0
 def __init__(self):
     events.AddListener(self)
     Walker.__init__(self)
     self.health = 10
     self.energy = 1
     self.xMax = 4
     self.xMin = -4
     self.yMax = 2
     self.yMin = -2
     self.state = State.fastWalking
     self.knownAvatars = []
     self.xFightingReach = 10
     self.yFightingReach = 4
     self.attack = attacks.Hug()
     self.stunCounter = 0
Exemple #20
0
    def __init__(self, ip, port):

        self.bridge = CvBridge()
        self.imageflags = [0, 0, 0, 0,
                           0]  #I 1gray 2small 3fc 4seg (zero not used)
        self.imagecnt = 0
        self.key = 0
        self.height = 1.6
        self.tilt = 0.0
        self.torso = 0.0
        self.headtilt = 0.0
        self.headrot = 0.0
        self.stepspending = 0
        self.totalsteps = 0
        self.nextposetime = 0
        self.nextfsstime = 0
        memory = posix_ipc.SharedMemory("flyermmap",
                                        posix_ipc.O_CREAT,
                                        size=8 * IPComm.Mib)
        self.sem = posix_ipc.Semaphore("flyersem", posix_ipc.O_CREAT)
        self.memmap = mmap.mmap(memory.fd, memory.size)
        memory.close_fd()
        self.image_sub = rospy.Subscriber("/olrun/image/gray", Image,
                                          self.callback)
        self.fcimage_sub = rospy.Subscriber("/olrun/image/fc", Image,
                                            self.callbackfc)
        self.segimage_sub = rospy.Subscriber("/olrun/image/seg", Image,
                                             self.callbackseg)
        self.smallimage_sub = rospy.Subscriber("/olrun/image/small", Image,
                                               self.callbacksmall)
        ROBOT_NAME = rospy.get_param('/ihmc_ros/robot_name')
        fss_name = "/ihmc_ros/{0}/output/footstep_status".format(ROBOT_NAME)
        pose_name = "/ihmc_ros/{0}/output/robot_pose".format(ROBOT_NAME)
        self.fssSubscriber = rospy.Subscriber(fss_name,
                                              FootstepStatusRosMessage,
                                              self.rcvdfss)
        self.poseSubscriber = rospy.Subscriber(pose_name, Odometry,
                                               self.rcvdpose)
        self.queue = posix_ipc.MessageQueue("/flyerqueue", posix_ipc.O_CREAT)
        self.wsproc = prc.Popen('python -u flyerws.py --ip %s --port %s' %
                                (ip, port),
                                shell=True)
        self.writecnt = 0
        self.loc = [0.0, 0.0, 0.0]
        self.walker = Walker()
        self.walker.init()
        self.neck_joint = [0.0, 0.0, 0.0]
        self.torso_joint = 0.0
Exemple #21
0
 def __init__(self, path):
     self.path = path
     self.queue = Queue.PriorityQueue()
     self.watcher = Watcher(path, self.queue)
     self.walker = Walker(path, self.queue, Settings.is_rescan_forced())
     self.reader = Reader(self.queue)
     self.validator = Validator(self.queue)
Exemple #22
0
    def Setup(self):
        #Create the ground
        self.world.CreateStaticBody(position=(0, -10),
                                    shapes=b2PolygonShape(box=(10000, 10)))

        #Make some walkers
        self.walkerList = []
        for i in range(learningSettings.groupSize):
            self.walkerList.append(
                Walker(self.world, (i * 10, 0),
                       learningSettings.useSimpleWalkers))

        #Make a population of agents
        if (learningSettings.loadPopulation):
            self.population = Population.loadFromFile(
                learningSettings.populationFile)
            #Reduce the number of agents to the best performing ones
            self.population.pruneToTopAgents(learningSettings.groupSize)
        else:
            jointCount = len(self.walkerList[0].jointList)
            sampleNetwork = Network(jointCount + 2, jointCount, [jointCount])
            self.population = Population(learningSettings.walkerCount,
                                         sampleNetwork)

        #If we need it, setup an environment for speciation
        if (learningSettings.selectionCriteria == selection.SPECIATION):
            self.environment = speciation.Environment()
            self.environment.generateAllFood(self.walkerList[0],
                                             learningSettings.foodCount,
                                             learningSettings.foodUses,
                                             learningSettings.foodEnergy)
Exemple #23
0
    def __init__(self):
        self.n_features = 366
        self.n_actions = 8
        self.max_epoch = 100
        self.max_steps = 100

        # define sound source information
        self.src_pos_x = -3.0
        self.src_pos_y = 1.6
        self.src_pos_z = -3.0

        # sample as a grid map with 0.5m unit
        self.unit = 0.5
        self.room_grids = [i for i in np.arange(-3.5, 3.5 + self.unit, self.unit)]

        self.walker = Walker(self.n_features, self.n_actions)
Exemple #24
0
def main():

    # Initialize pygame
    pygame.init()
    clock = pygame.time.Clock()
    globals.window = pygame.display.set_mode((globals.WIDTH, globals.HEIGHT), False)
    globals.window.fill(BACKGROUND_COLOR)

    loop = True

    # Create the walkers
    walkers = []
    for i in range(NUM_WALKERS):
        if RANDOM_COLORS:
            color = (random.randint(0, 255), random.randint(0, 150), random.randint(100, 255))
        else:
            color = (0, 0, 0) # Default to black if no random colors
        walkers.append(Walker(globals.WIDTH / 2, globals.HEIGHT / 2, color))

    while(loop):

        clock.tick(60)

        for i in range(len(walkers)):
            walkers[i].update()
            walkers[i].draw()

        # Check if the escape key has been pressed
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()

        pygame.display.flip()
Exemple #25
0
    def make_graph(self):

        for h_line in self.horizon_lines:
            coeff_x, coeff_y, bias = h_line.eq
            for v_line in self.vertical_lines:
                cx, cy, b = v_line.eq
                A = np.array([[coeff_x, coeff_y], [cx, cy]])
                B = np.array([bias, b])
                root = Corner(np.linalg.solve(A, B).astype(int))
                h_line.corners.append(root)
                v_line.corners.append(root)
                self.corners.append(root)

        for line in self.lines:
            line.line_link()

        self.walker = Walker(self.corners)
Exemple #26
0
 def AddSpike(self):
     # Release/spawn some number of ions at Post Synaptic Density
     amp = random.randint(
         1, 15)  #should be drawn from Gaussian and have some meaning
     print "Spike of size ", amp
     for i in xrange(amp):
         #draw a random position in proximity of PSD
         self.Ions.append(
             Walker([random.random(), 1 - 0.1 * random.random()]))
def generate_code_and_tests(ast):
    """ Walk concord message format(CMF) AST and generate C++ code and C++ tests"""
    namespace = "cmf::test"
    print("Generating C++ Message structs and serialization code")
    code = cppgen.translate(ast, namespace)
    test_code = file_header(namespace)
    print("Generating C++ message instances and serialization tests")
    visitor = InstanceVisitor()
    # We generate `max_size` msg instances for tests
    for i in range(0, MAX_SIZE):
        visitor.size = i
        walker = Walker(ast, visitor)
        walker.walk()
    for msg_name, instances in visitor.existing_instances.items():
        for instance in instances:
            test_code += instance + "\n\n"
        test_code += testSerializationStr(msg_name)
    return code, test_code + file_trailer(namespace, ast)
 def initialize_walkers_(self, population):
     if self.memory_safe:
         self.__dict__['population'] = population
     for i in range(self.chain.no_of_nodes):
         trans_prob = self.chain.get_node_transition_probability(self.chain.node_ids[i])
         next_step_processor = Markov(trans_prob)
         for j in range(population[i]):
             wlk = Walker(next_step_processor = next_step_processor,\
                             initial_id = self.chain.node_ids[i])
             self.walkers.append(wlk)
Exemple #29
0
 def simulate(self):
     s = Simulation()
     robot = Walker(s.space, [self.chromosome[0], self.chromosome[1]], self.chromosome[2], self.chromosome[3],\
     self.chromosome[4], self.chromosome[5], self.chromosome[6], self.chromosome[7], self.chromosome[8])
     print "Simulating best Individual with score: ", self.score
     currentPosition = s.step(0.02)
     energy = s.get_ke()
     while (currentPosition > 0 and energy > 1):
         energy = s.get_ke()
         #print "currentPosition: ", currentPosition
         currentPosition = s.step(0.02)
def load_map(file, move_keys, player_number):
    # Load map

    # Load background color
    f = open(path.join("levels", file + ".txt"), "r")
    data = f.read()
    f.close()
    data = data.split("\n")
    data[0] = data[0].split(",")
    color = data[0]
    tile_chars = {}
    data.pop(0)

    # Load tiles
    while "=" in data[0]:
        tile_chars[data[0][0]] = data[0].split("=")[1].split(",")
        data.pop(0)

    # Initialize objects
    tiles = []
    net = []
    walkers = []
    climbers = []
    stones = []
    players = []

    # Load objects
    y = 1
    for row in range(len(data)):
        x = -1
        for tile in range(len(data[row])):
            if data[row][tile] in tile_chars:
                tiles.append(
                    Tile(x, y, TILE_WIDTH, TILE_HEIGHT,
                         tile_chars[data[row][tile]]))
            elif data[row][tile] == "p" and len(players) < player_number:
                players.append(
                    Player(x, y, CHAR_WIDTH, CHAR_HEIGHT, 0,
                           move_keys[len(players)]))
            elif data[row][tile] == "w":
                walkers.append(Walker(x, y, CHAR_WIDTH, CHAR_HEIGHT, 0))
            elif data[row][tile] == "n":
                net.append(Net(x, y, TILE_WIDTH, TILE_HEIGHT, 6))
            elif data[row][tile] == "c":
                net.append(Net(x, y, TILE_WIDTH, TILE_HEIGHT, 6))
                climbers.append(Climber(x, y, CHAR_WIDTH, CHAR_HEIGHT, 0))
            elif data[row][tile] == "s":
                stones.append(Stone(x, y, TILE_WIDTH, TILE_HEIGHT, 7))
            x += TILE_WIDTH
        y -= TILE_HEIGHT

    # Return objects
    return tiles, net, stones, players, walkers, climbers, color
Exemple #31
0
 def __init__(self):
     Walker.__init__(self)
     events.AddListener(self)
     self.health = 3
     self.state = State.normal
     self.upPressed = False
     self.rightPressed = False
     self.downPressed = False
     self.leftPressed = False
     self.xFriction = 1
     self.yFriction = 2
     self.xAccel = 1
     self.yAccel = 1 
     self.xMax = 6
     self.xMin = -6
     self.yMax = 2
     self.yMin = -2
     self.stunCounter = 0
     self.yoyo = LogicalYoyo()
     self.attacks = attacks.makeYoyoAttacks(self.yoyo)
     self.strings = []
     self.selectedAttack = None
def send():
    send.butt.setEnabled(False)
    robot = Robot("192.168.0.14", "5469")
    walk = Walker(robot)
    robot.locomotion.gait(stance, step, zmp, hack, sensor, stiff, odo, arm)
    walk.linear_go_to(300.0, 0.0, 100.0)
    time.sleep(1.0)
    while not walk.is_done():
        time.sleep(1.0)
    walk.stop()
    send.butt.setEnabled(True)
def main(argv):

    # set up argument parsing
    # parser = argparse.ArgumentParser()
    # parser.add_argument('input_graph', help='Original graph input file, in\
    #                                          edge list format')
    # parser.add_argument('seed', help='Seed file, to pull start nodes from')
    # parser.add_argument('-e', '--restart_prob', type=float, default=0.7,
    #                     help='Restart probability for random walk')
    # parser.add_argument('-l', '--low_list', nargs='?', default=None,
    #                     help='<Optional> List of genes expressed and\
    #                           unexpressed in the current tissue, if applicable')
    # parser.add_argument('-n', '--node_list', nargs='?', default=None,
    #                     help='<Optional> Order of output probs')
    # parser.add_argument('-o', '--original_graph_prob', type=float, default=0.1,
    #                     help='Probability of walking on the original (non-\
    #                           tissue specific) graph, if applicable')
    # parser.add_argument('-r', '--remove', nargs='+',
    #                     help='<Optional> Nodes to remove from the graph, if any')
    # opts = parser.parse_args()
    #*************************************************************************
    seed = 'testdata/seeds.tsv'
    node_list = None
    seed_list = generate_seed_list(seed)
    node_list = get_node_list(node_list) if node_list else []
    remove = None
    # filter nodes we want to remove out of the starting seed, if any
    remove_list = remove if remove else []
    if remove_list:
        seed_list = [s for s in seed_list if s not in remove_list]

    # run the experiments, and write a rank list to stdout
    input_graph = 'testdata/observed_network.txt'
    restart_prob = 0.7
    original_graph_prob = 0.1
    low_list = None
    wk = Walker(input_graph, low_list, remove_list)
    wk.run_exp(seed_list, restart_prob, original_graph_prob, node_list)
Exemple #34
0
 def interactive(self):
     # Interactive mode
     running = True
     robot = None
     while running:
         # Deal with clicks and other events
         for event in pygame.event.get():
             if event.type == QUIT:
                 running = False
             if event.type == MOUSEBUTTONDOWN:
                 robot = Walker(self.space, \
                         self._invy(event.pos), \
                         80, 60, 10, pi/16, 0, 0, 0)
         self.step(0.02)
Exemple #35
0
class Scanner:
    def __init__(self, path):
        self.path = path
        self.queue = Queue.PriorityQueue()
        self.watcher = Watcher(path, self.queue)
        self.walker = Walker(path, self.queue, Settings.is_rescan_forced())
        self.reader = Reader(self.queue)
        self.validator = Validator(self.queue)

    def start(self):
        self.validator.start()
        self.watcher.start()
        self.walker.start()
        self.reader.start()

    def stop(self):
        self.watcher.stop()
        self.reader.stop()

        self.validator.join()
        self.walker.join()
        self.watcher.join()
        self.reader.join()
Exemple #36
0
def main(file_path=None, all_sync=False):
    inifile = cp.SafeConfigParser()
    inifile.read(os.getcwd() + "/confing.ini")

    """ load config file """
    host = inifile.get("receiver", "host")
    port = inifile.get("receiver", "port")
    user = inifile.get("receiver", "user")
    passwd = inifile.get("receiver", "passwd")
    header_path = inifile.get("file", "header_path")

    transfer = Transfer("ftp")
    transfer.inst.connect(host, port, user, passwd)

    if all_sync:
        syncdir = inifile.get("all_sync", "syncdir")
        walker = Walker(syncdir)
        w = walker.start()
        while True:
            try:
                file_path = w.next()
                remote_path = file_path.replace(header_path, "")
                dirname = os.path.dirname(remote_path)
                filename = os.path.basename(remote_path)
                send(transfer.inst, dirname, filename, file_path)
            except StopIteration:
                return

    if file_path:
        remote_path = file_path.replace(header_path, "")
        if remote_path[0] != "/":
            remote_path = "/" + remote_path
        dirname = os.path.dirname(remote_path)
        filename = os.path.basename(remote_path)

        """ Connection with remote server """
        send(transfer.inst, dirname, filename, file_path)
Exemple #37
0
class Smartie(object):
    ''' Class to connect to and publish the Korg NanoKontrol midi device
        as a ros joystick
    '''
    def __init__(self):
        ''' connect to midi device and set up ros
        '''
        self.sp = SmartPAD('SmartPAD')
        self.axis = Axis()
        self.axis.init()
        self.walker = Walker()
        self.walker.init()
        self.web = pages.Pages()

        rospy.loginfo("Using input device %s" % self.sp.device)
        os.environ['PORT'] = '8081'

    def finish(self):
        self.sp.finish()
        self.axis.fini()
        self.web.finish()
        #del self.sp
        #del self.axis

    def run(self):
        try:
            thread.start_new_thread(self.web.run, ())
            while not rospy.is_shutdown():
                done, data, steps = self.sp.readin()
                if done:
                    rospy.signal_shutdown("Smartie Done")
                self.axis.process_keys(data)
                self.walker.process_keys(steps)
        finally:
            rospy.loginfo("Smartie Died")
            self.finish()
def send():
    send.butt.setEnabled(False)
    robot = Robot("192.168.0.14", "5469")
    walk = Walker(robot)
    robot.locomotion.gait(stance, step, zmp, hack, sensor, stiff, odo, arm)
    walk.linear_go_to(300.0, 0.0, 100.0)
    time.sleep(1.0)
    while not walk.is_done():
        time.sleep(1.0)
    walk.stop()
    send.butt.setEnabled(True)
    def make_graph(self):

        for h_line in self.horizon_lines:
            coeff_x, coeff_y, bias = h_line.eq
            for v_line in self.vertical_lines:
                cx, cy, b = v_line.eq
                A = np.array([[coeff_x, coeff_y], [cx, cy]])
                B = np.array([bias, b])
                root = Corner(np.linalg.solve(A, B).astype(int))
                h_line.corners.append(root)
                v_line.corners.append(root)
                self.corners.append(root)

        for line in self.lines:
            line.line_link()

        self.walker = Walker(self.corners)
    def run_memory_safe_(self, time, display_progress = False):
        population_changes = {key: np.zeros(self.times.shape[0]) for key in self.chain.node_ids}
        prg = np.arange(0, np.sum(self.population), 1)
        prg_count = 0
        for p in range(len(self.population)):
            trans_prob = self.chain.get_node_transition_probability(self.chain.node_ids[p])
            next_step_processor = Markov(trans_prob)
            for i in range(self.population[p]):
                iteration = 0
                walker = Walker(next_step_processor = next_step_processor,\
                                initial_id = self.chain.node_ids[p])
                for tt in self.times[1:]:
                    curr = walker.current_position()
                    walker.next_step_processor.transition_probability = \
                                                            self.chain.nodes[curr].transition_probability
                    next_pos = self.chain.next(curr)
                    if len(next_pos) == 0:
                        walker.empty_step()
                        continue
                    pmf = self.chain.get_node_probability_mass_function(curr)
                    pmf = [pmf[pos] for pos in next_pos]
                    walker.walk(possible_states = next_pos, \
                                current_state = curr, \
                                probability_mass_function = pmf)

                    nxt = walker.current_position()

                    population_changes[curr][iteration] -= 1
                    population_changes[nxt][iteration] += 1

                    iteration += 1
                    
                if display_progress:
                    self._display_progress(prg_count, prg)
                    prg_count += 1

        return population_changes
class Graph():

    def __init__(self, lines):
        self.lines = lines
        self.corners = []
        self.horizon_lines = []
        self.vertical_lines = []
        self.walker = None

        self.set_directed_lines()
        self.make_graph()

    def set_directed_lines(self):
        for line in self.lines:
            if line.direction is 'h':
                self.horizon_lines.append(line)
            else:
                self.vertical_lines.append(line)

    def make_graph(self):

        for h_line in self.horizon_lines:
            coeff_x, coeff_y, bias = h_line.eq
            for v_line in self.vertical_lines:
                cx, cy, b = v_line.eq
                A = np.array([[coeff_x, coeff_y], [cx, cy]])
                B = np.array([bias, b])
                root = Corner(np.linalg.solve(A, B).astype(int))
                h_line.corners.append(root)
                v_line.corners.append(root)
                self.corners.append(root)

        for line in self.lines:
            line.line_link()

        self.walker = Walker(self.corners)

    def get_quad_list(self):
        return self.walker.get_quad_list()
 def setup(self):
     self.walker = Walker(self)
     self.background(255)
Exemple #43
0
 def visitFunction(self, node):
   print "[fn]", node.name
   Walker.visitFunction(self, node)
Exemple #44
0
WIDTH = 400
HEIGHT = 400
BACKGROUND = (0, 170, 0)

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Random walk with coloured trail")
screen.fill(BACKGROUND)
pygame.display.update()

clock = pygame.time.Clock()

def move():
    return (random.choice([-2,0,2]),
                            random.choice([-2,0,2]))
pos = [WIDTH//2, HEIGHT//2]
walker = Walker(screen, pos, get_move=move, size=2)

it = 0
while True:
    clock.tick(120)

    for ev in pygame.event.get():
        if ev.type == QUIT:
            pygame.quit()
            sys.exit()

    walker.walk()
    walker.c = (55,0,it)
    walker.pos[0] %= WIDTH
    walker.pos[1] %= HEIGHT
    walker.draw()