Пример #1
0
 def update_weights(self, reward, state, new_state, action, new_action):
   """ Update the agents weights after a non-terminal step. """
   x = tiles.tiles(self.iht, self.no_of_tiles, np.append(state, action)*self.normalise)
   new_x = tiles.tiles(self.iht, self.no_of_tiles, np.append(new_state, new_action)*self.normalise)
   q = sum([self.weights[x[i]][i] for i in range(self.no_of_tiles)])
   new_q = sum([self.weights[new_x[i]][i] for i in range(self.no_of_tiles)])
   for i in range(self.no_of_tiles):
     self.weights[x[i]][i] += self.training_rate*(reward + new_q - q)
Пример #2
0
def runTest(seed=65597):

    import tiles

    i = 5
    j = 6
    print 'seed: ' + str(seed)
    tiles.setseed(seed)
    print tiles.tiles(10, 2048, [i * 0.5, j * 0.5])
Пример #3
0
def runTest(seed = 65597):

    import tiles

    i=5
    j=6
    print 'seed: '+str(seed)
    tiles.setseed(seed)
    print tiles.tiles(10, 2048, [i*0.5, j*0.5])
Пример #4
0
 def calcTiledata(self, numtilings, memct, floats, ints=[]):
     samet = []
     sametd = []
     sametbd = []
     sametdm = []
     sametl = []
     samete = []
     samets = []
     t = tiles.tiles(numtilings, memct, floats, ints)
     tsx = fancytiles.stripetiles(numtilings, memct, [floats[0]], None,
                                  ints)
     tsy = fancytiles.stripetiles(numtilings, memct, [floats[1]], None,
                                  ints)
     td = fancytiles.diagonaltiles(numtilings, memct, floats, None, ints)
     tbd = fancytiles.backdiagonaltiles(numtilings, memct, floats, None,
                                        ints)
     tdm = fancytiles.diamondtiles(numtilings, memct, floats, None, ints)
     tl = fancytiles.logtiles(numtilings, memct, floats, ints)
     te = fancytiles.exptiles(numtilings, memct, floats, ints)
     total = int((self.end - self.start) * self.intervals)
     for i in range(total):
         for j in range(total):
             x = float(i) / self.intervals + self.start
             y = float(j) / self.intervals + self.start
             newfloats = [x, y]
             if tiles.tiles(numtilings, memct, newfloats, ints) == t:
                 samet.append(newfloats)
             if fancytiles.stripetiles(numtilings, memct, [x], None,
                                       ints) == tsx or \
                             fancytiles.stripetiles(numtilings, memct, [y],
                                                    None, ints) == tsy:
                 samets.append(newfloats)
             if fancytiles.diagonaltiles(numtilings, memct, newfloats, None,
                                         ints) == td:
                 sametd.append(newfloats)
             if fancytiles.backdiagonaltiles(numtilings, memct, newfloats,
                                             None, ints) == tbd:
                 sametbd.append(newfloats)
             if fancytiles.diamondtiles(numtilings, memct, newfloats, None,
                                        ints) == tdm:
                 sametdm.append(newfloats)
             if fancytiles.logtiles(numtilings, memct, newfloats,
                                    ints) == tl:
                 sametl.append(newfloats)
             if fancytiles.exptiles(numtilings, memct, newfloats,
                                    ints) == te:
                 samete.append(newfloats)
     data = [samet, samets, sametd, sametbd, sametdm, sametl, samete]
     return data
Пример #5
0
def stripetiles(numtilings, memctable, floats, widths=None, ints=[]):
    "returns tiles in the shape of stripes (scaled by widths), a set for each dimension in floats"
    floats = scalefloats(floats, widths)
    # should another int be added here for each dimension if there is more than one?
    return reduce(operator.add,
                  [tiles.tiles(numtilings, memctable, [f], ints) for f in
                   floats])
Пример #6
0
 def act(self, state, reward):
   """ Epsilon-greedy policy. """
   x0 = tiles.tiles(self.iht, self.no_of_tiles, np.append(state, 0)*self.normalise)
   x1 = tiles.tiles(self.iht, self.no_of_tiles, np.append(state, 1)*self.normalise)
   a0 = sum([self.weights[x0[i]][i] for i in range(self.no_of_tiles)])
   a1 = sum([self.weights[x1[i]][i] for i in range(self.no_of_tiles)])
   if np.random.rand() < 0.9:
     if a0 > a1:
       action = 0
     else:
       action = 1
   else:
     if a1 > a0:
       action = 0
     else:
       action = 1
   return action
Пример #7
0
def runit2(num=10, ct=2048, numt=1):
    for i in xrange(num):
        for j in xrange(num):
            t = tiles.tiles(
                numt, ct,
                [i * 0.5, j * 0.5,
                 float(i + j) / 2,
                 float(i - j) / 2], [i, j])
Пример #8
0
def fancytiles(numtilings, floats, tileshape="square", tilesize="uniform", \
               tilewidths=None, memctable=2048, ints=[]):
    """Does appropriate manipulations to get special shaped or sized tiles.
       Tileshapes are 'square' - square or rectangular tiles (the default),
                      'stripe' - stripes for each dimension, and
                      'diagonal' - diagonal stripes for each pair of dimensions
                      'backdiagonal' diagonal stripes the other way
                      'alldiagonal' - diagonal stripes for all dimensions at once
                      'allbackdiagonal' - diagonal stripes the other way for all dimensions at once
                      'diamond' - diagonal stripes and back diagonal stripes are applied
       Tilesizes are 'uniform' - all tiles are the same size (the default), 
                     'log' - tile sizes vary logarithmically from small to large, and
                     'exp' - tile sizes vary exponentially from large to small
       Scaling is handled first if tilewidths is set - there should be a width for every
       element of the float vector. If you don't wish to apply scaling to the floats,
       tilewidths may be set to None, or to a vector of 1's the same length as floats.
       memctable, numtilings and ints are the same as for the regular tiles routine.
       Note that you may get back more tiles than numtilings - for stripes or diagonal stripes
       you may get a larger number of tiles back.
    """
    if tilewidths != None:                  # apply scaling, if desired
            floats = scalefloats(floats, tilewidths)
    if tilesize == "log":                   # logarithmic sized tiles
        floats = logfloats(floats)
    elif tilesize == "exp":                 # exponential sized tiles
        floats = expfloats(floats)
        
    if tileshape == "stripe":               # stripes - do one set for each variable in floats
        return reduce(operator.add, [tiles.tiles(numtilings, memctable, [f], ints) for f in floats])
    elif tileshape == "diagonal":           # diagonal stripes for every pair of dimensions
        flist = floats[:]
        tlist = []
        while len(flist) > 1:
            current = flist[0]
            for next in flist[1:]:
                tlist.extend(tiles.tiles(numtilings, memctable, diagonalstripe([current, next]), ints))
            flist = flist[1:]
        return tlist
    elif tileshape == "backdiagonal":       # diagonal stripes for every pair of dimensions
        flist = floats[:]
        tlist = []
        while len(flist) > 1:
            current = flist[0]
            for next in flist[1:]:
                tlist.extend(tiles.tiles(numtilings, memctable, backdiagonalstripe([current, next]), ints))
            flist = flist[1:]
        return tlist
    elif tileshape == "alldiagonal":        # diagonal stripe through all dimensions at once - no different than diag?
        return tiles.tiles(numtilings, memctable, diagonalfloats(floats), ints)
    elif tileshape == "allbackdiagonal":    # diagonal stripe through all dimensions at once
        return tiles.tiles(numtilings, memctable, backdiagonalfloats(floats), ints)
    elif tileshape == "diamond":            # diamond shaped tiles 
        floats1 = diagonalfloats(floats)
        floats2 = backdiagonalfloats(floats)
        return tiles.tiles(numtilings, memctable, floats1+floats2, ints)
    else:                                   # square/rectangular - do the regular tiles
        return tiles.tiles(numtilings, memctable, floats, ints)
def getfeatvec(res, normS):

    ## pure pythong tilecoding
    # activetiles = [-1]*numTilings
    # tilesOut = tilecode(numTilings, res, activetiles, normS)

    ## cython tilecoder is faster
    scalednormS = [x * res for x in normS]
    tilesOut = tiles.tiles(numTilings, np.power(res, numFeatures)*numTilings, scalednormS)

    return tilesOut
Пример #10
0
 def transform(self, state):
     # Normalize values to range from [0, 1] for use in transformations
     position, velocity = state
     position = (position + 1.2) / 1.8
     velocity = (velocity + 0.07) / 0.14
     assert 0 <= position <= 1
     assert 0 <= velocity <= 1
     position *= 2
     velocity *= 2
     if self.mode == "tile":
         if self.iht is None:
             self.iht = IHT(self.state_space)
         tiling = tiles(self.iht, 64, [position, velocity], [0]) + \
                 tiles(self.iht, 64, [position], [1]) + \
                 tiles(self.iht, 64, [velocity], [2])
         return {index: 1 for index in tiling}
     elif self.mode == "raw":
         return dict(enumerate(state))
     else:
         raise Error("Invalid environment mode. Must be tile or raw")
 def calcTiledata(self, numtilings, memct, floats, ints=[]):
     samet = []
     sametd = []
     sametbd = []
     sametdm = []
     sametl = []
     samete = []
     samets = []
     t = tiles.tiles(numtilings, memct, floats, ints)
     tsx = fancytiles.stripetiles(numtilings, memct, [floats[0]], None, ints)
     tsy = fancytiles.stripetiles(numtilings, memct, [floats[1]], None, ints)
     td = fancytiles.diagonaltiles(numtilings, memct, floats, None, ints)
     tbd = fancytiles.backdiagonaltiles(numtilings, memct, floats, None, ints)
     tdm = fancytiles.diamondtiles(numtilings, memct, floats, None, ints)
     tl = fancytiles.logtiles(numtilings, memct, floats, ints)
     te = fancytiles.exptiles(numtilings, memct, floats, ints)
     total = int((self.end - self.start) * self.intervals)
     for i in xrange(total):
         for j in xrange(total):
             x = float(i)/self.intervals + self.start
             y = float(j)/self.intervals + self.start
             newfloats = [x, y]
             if tiles.tiles(numtilings, memct, newfloats, ints) == t:
                 samet.append(newfloats)
             if fancytiles.stripetiles(numtilings, memct, [x], None, ints) == tsx or \
                fancytiles.stripetiles(numtilings, memct, [y], None, ints) == tsy:
                 samets.append(newfloats)
             if fancytiles.diagonaltiles(numtilings, memct, newfloats, None, ints) == td:
                 sametd.append(newfloats)
             if fancytiles.backdiagonaltiles(numtilings, memct, newfloats, None, ints) == tbd:
                 sametbd.append(newfloats)
             if fancytiles.diamondtiles(numtilings, memct, newfloats, None, ints) == tdm:
                 sametdm.append(newfloats)
             if fancytiles.logtiles(numtilings, memct, newfloats, ints) == tl:
                 sametl.append(newfloats)
             if fancytiles.exptiles(numtilings, memct, newfloats, ints) == te:
                 samete.append(newfloats)
     data = [samet, samets, sametd, sametbd, sametdm, sametl, samete]
     return data
    def loadFeatures(self, stateVars, featureVector):
#         loadtiles(featureVector, 0, self.numTilings, self.num_bins, stateVars)
#         active_tiles = loadtiles([0], 0, self.numTilings*self.num_bins, 1024, stateVars)
#         buffer = [0] # array of length numtilings
#         tiles(1,512,stateVars)
#         active_tiles = loadtiles([0], 0, self.numTilings, self.num_bins, stateVars)
        self.F = active_tiles = tiles(self.numTilings,self.mem_size,stateVars)
#         print 'tiles = ' + str(active_tiles)
#         active_tiles = simple_tiles(self.numTilings, self.numTilings*self.num_bins, stateVars)
#         simple_tiles(self.numTilings, self.numTilings*self.num_bins, stateVars)
#         print "featureVector " + str(len(self.theta))
#         print 'active tiles = ' + str(active_tiles)
#         print 'numTilings = ' + str(self.numTilings)
#         print 'stateVars = ' + str(stateVars)
        """ 
def featurize(s):

    normS = normalize(s)

    featvecs = Parallel(n_jobs=num_cores)(delayed(getfeatvec)(resolutions[res], normS) for res in range(len(resolutions)))

    # Concatenate the feature vectors and add
    # Single active baseline unit
    catfeat = np.hstack(featvecs)
    catfeat = np.hstack((0, catfeat))

    print catfeat[0]

    print len(catfeat)

    print sum(np.power(np.array(resolutions), numFeatures)*numTilings)+1

    # For each resolution the features are needed 
    for res in np.nditer(resolutions):

        # Tilecoding hash table
        # ctu = tiles.CollisionTable(32, 'super safe')
        # ctu = tiles.CollisionTable(4096, 'unsafe')
        # cts = tiles.CollisionTable(4096, 'safe')
        # ctss = tiles.CollisionTable(4096, 'super safe')

        resVec = np.zeros(np.power(res, numFeatures)*numTilings)
        # resVecHash = np.zeros(4096)
 
        # Get the indexes of the tiles
        tilesOut = tiles.tiles(numTilings, res, normS*res)
        print tilesOut

#         print tilesOut 
        
        # tilesOutHash = tiles.tiles(numTilings, ctu, normS*res)
#         print tilesOutHash
        
        # resVecHash[tilesOutHash] = 1
        # print resVecHash
        
        # For each tile index flip a feature in the feature vector
        # for tileIndex in range(len(tilesOut)):
        #     resVec[tilesOut[tileIndex] + (res**2 * tileIndex)] = 1
            
        # x = np.append(x, resVec)

    return catfeat
Пример #14
0
    def __init__(self, concealed, exposed=None, initial_update=True):
        if isinstance(concealed, str):
            concealed = tiles.tiles(concealed)

        if isinstance(concealed, Counter):
            self._concealed = concealed
        else:
            self._concealed = Counter(concealed)
        self._exposed = exposed or []

        self.claimable_chow = {}
        self.claimable_pung = {}
        self.claimable_kong = {}
        self.claimable_win = {}

        self.shanten_std, self.shanten_7, self.shanten_13 = None, None, None
        if initial_update:
            self.update()
def getfeatvec(res, normS):

    scalednormS = [x * res for x in normS]

    # x is the active tiles in this featurization
    # This featurization should return a single binary feature vector
    # with exactly m features in x(s) active at any time
    # Binary feature vector has a length of 4636426 or
    # sum(np.power(np.array([5,8,12,20]),4)*25)+1
    x = np.zeros(np.power(res, numFeatures)*numTilings)

    tilesOut = tiles.tiles(numTilings, res, scalednormS)

    for idx, val in enumerate(tilesOut):
        # for each tile index put out by the tile coder
        # we need to flip a bit in the feature vector
        # this bit index is given by the value of the tile from the tile coder
        # the index this value was at, the resolution of the tile
        x[val + (res**2 * idx)] = 1

    return x
Пример #16
0
    def __init__(self, level, controls):
        super().__init__()

        self.set_background_color(33/255, 46/255, 56/255)

        # set up timing system
        self.timeline = Timeline()
        self.last_time = 0.0

        def extract_tile_id(filename, flags, tileset):
            def inner(rect, flags):
                x, y, w, h = rect
                return x // w + y // h * tileset.columns
            return inner

        tile_list = tiles(self)
        tiled_map = TiledMap(level, image_loader=extract_tile_id)
        level = self.render.attach_new_node("level")
        width = tiled_map.width
        height = tiled_map.height * 3**0.5 / 2
        level.set_pos(width / 2, -height / 2, 0)

        def get_track(x, y):
            for i, layer in enumerate(tiled_map):
                tile = tile_list.get(tiled_map.get_tile_image(x, y, i))
                if isinstance(tile, Track):
                    return tile
            return None

        z = {}
        for layer in tiled_map:
            for x, y, tile_id in layer.tiles():
                if (tile_type := tile_list.get(tile_id)) is not None:
                    tile = level.attach_new_node("tile")
                    tile.set_pos(*from_hex(x, y), z.get((x, y), 0))
                    z[(x, y)] = z.get((x, y), 0) + tile_type.height
                    tile_type.instance_to(tile)
                    tile_type.register(tile, self.timeline, x, y, get_track)
Пример #17
0
	def loadXml(self,node):
		self.getText(node.childNodes)
		if node.nodeType!=Node.ELEMENT_NODE:
			for n in node.childNodes:
				if n.nodeType==Node.ELEMENT_NODE and n.localName == 'xdl_resource_report':
					self.loadXml(n)
		else:
			for n in node.childNodes:
				if n.nodeType==Node.ELEMENT_NODE and n.localName == 'tiles':
					el=tiles()
					el.loadXml(n)
					self.set_tiles(el)
		
			for n in node.childNodes:
				if n.nodeType==Node.ELEMENT_NODE and n.localName == 'primitive_defs':
					el=primitive_defs()
					el.loadXml(n)
					self.set_primitive_defs(el)
		
			for n in node.childNodes:
				if n.nodeType==Node.ELEMENT_NODE and n.localName == 'summary':
					el=summary()
					el.loadXml(n)
					self.set_summary(el)
		
			if node.hasAttributes():
				attrs=node.attributes
				attrId='a1'
				if attrId in attrs.keys():
					self.a1=str(attrs[attrId].value)
		
				attrId='a0'
				if attrId in attrs.keys():
					self.a0=str(attrs[attrId].value)
		
				attrId='a2'
				if attrId in attrs.keys():
					self.a2=str(attrs[attrId].value)
Пример #18
0
def run(args):
    """main entry point"""

    player_hand = tiles.tiles(args.hand)

    func = {
        '13': count_shanten_13_orphans,
        '7': count_shanten_seven_pairs,
        'std': count_shanten_std,
    }.get(args.algorithm, None)

    if func:
        shanten = func(player_hand)
    else:
        shanten, func = count_shanten_naive(player_hand)

    shanten_type = {
        count_shanten_13_orphans: ShantenType.THIRTEEN_ORPHANS,
        count_shanten_seven_pairs: ShantenType.SEVEN_PAIRS,
        count_shanten_std: ShantenType.STANDARD
    }[func]

    print(f'{shanten} {shanten_type}')
Пример #19
0
def diamondtiles(numtilings, memctable, floats, widths=None, ints=[]):
    "returns tiles in the shape of diamonds"
    floats = scalefloats(floats, widths)
    floats1 = diagonalfloats(floats)
    floats2 = backdiagonalfloats(floats)
    return tiles.tiles(numtilings, memctable, floats1 + floats2, ints)
Пример #20
0
    def __init__(self, level, controls):
        super().__init__()

        self.set_background_color(33 / 255, 46 / 255, 56 / 255)

        # set up timing system
        self.timeline = Timeline()
        self.timeline.speed = 0
        self.last_time = 0.0

        self.tile_list = tiles(self)

        def extract_tile(filename, flags, tileset):
            filename = Path(filename).name
            tiles = self.tile_list[filename]

            def inner(rect, flags):
                x, y, w, h = rect
                return tiles[x // w + y // h * tileset.columns]

            return inner

        tiled_map = TiledMap(level, image_loader=extract_tile)
        self.level = self.render.attach_new_node("level")
        self.tile_nodes = self.level.attach_new_node("tiles")
        width = tiled_map.width
        height = tiled_map.height * 3**0.5 / 2
        self.level.set_pos(width / 2, -height / 2, 0)

        self.z = defaultdict(int)
        self.track = {}
        self.clear = {}
        self.trains = []
        for layer in tiled_map:
            for x, y, tile_type in layer.tiles():
                if tile_type is not None:
                    if isinstance(tile_type, Train):
                        train_node = tile_type.train.copyTo(self.level)
                        train_node.set_pos(*from_hex(x, y), self.z[x, y])
                        self.trains.append(
                            TrainInstance(tile_type, train_node, x, y))
                    if isinstance(tile_type, Track):
                        self.track[x, y] = tile_type
                    else:
                        tile = self.tile_nodes.attach_new_node("tile")
                        tile.set_pos(*from_hex(x, y), self.z[x, y])
                        self.z[x, y] += tile_type.height
                        self.clear[x, y] = self.clear.get(
                            (x, y), True) and tile_type.clear
                        tile_type.node.instanceTo(tile)

        self.track_nodes = None
        self.update_track()

        self.timeline.subscribe(self.update_trains)

        # use antialiasing
        self.render.set_antialias(AntialiasAttrib.MMultisample)

        # position camera
        self.camera.set_pos(0, 8, 8)
        self.camera.look_at(0, 0, 0)
        self.disable_mouse()

        # create a light
        ambient = ambient_light(colour=(.3, .3, .3, 1))
        self.ambient = self.render.attach_new_node(ambient)
        self.render.set_light(self.ambient)

        # create another light
        directional = directional_light(colour=(1, 1, 1, 1),
                                        direction=(-1, -2, -3))
        self.directional = self.render.attach_new_node(directional)
        self.render.set_light(self.directional)

        # load control scheme from file
        self.load_controls(controls)
        self.task_mgr.add(self.loop, 'loop')

        # create a ui
        aspect_ratio = self.get_aspect_ratio()

        self.tile_tray = self.aspect2d.attach_new_node("tile_tray")
        tile_tray_bg = OnscreenImage(image='data/black.png',
                                     pos=(0, 0, -1.66),
                                     scale=(aspect_ratio, 0, 1),
                                     color=(0, 0, 0, .3),
                                     parent=self.tile_tray)
        self.tile_tray.setTransparency(TransparencyAttrib.MAlpha)

        self.play = OnscreenImage(image='data/play.png',
                                  pos=(-0.9 * aspect_ratio, 0, 0.85),
                                  scale=0.08,
                                  parent=self.aspect2d)
        self.play.setTransparency(TransparencyAttrib.MAlpha)
        self.stop = OnscreenImage(image='data/stop.png',
                                  pos=(-0.9 * aspect_ratio, 0, 0.85),
                                  scale=0.08,
                                  parent=self.aspect2d)
        self.stop.setTransparency(TransparencyAttrib.MAlpha)
        self.stop.hide()

        self.playing = False

        track_id_to_thumb = {
            1: 'straight_1-2-3-4.png',
            2: 'curved_1-2-3-4.png',
            3: 'straight_1-_-3-4.png',
            4: 'straight_1-2-_-4.png',
            5: 'straight_1-2-3-_.png',
            6: 'curved_1-_-3-4.png',
            7: 'curved_1-2-_-4.png',
            8: 'curved_1-2-3-_.png',
        }
        self.thumbs = random.choices(list(track_id_to_thumb), k=3)
        self.selected_thumb = None

        for n, thumb in enumerate(self.thumbs):
            _thumb = OnscreenImage(image='thumbs/' + track_id_to_thumb[thumb],
                                   pos=((n + 1) * 2 / (len(self.thumbs) + 1) -
                                        1, 0, -.82),
                                   scale=.15,
                                   parent=self.tile_tray)
            _thumb.setTransparency(TransparencyAttrib.MAlpha)

        self.preview = self.level.attach_new_node("preview")
        self.preview.setTransparency(TransparencyAttrib.MAlpha)
        self.preview.setColorScale(2, 2, 2, 0.65)
        self.preview.hide()

        self.rotating_cw = False
        self.rotating_ccw = False

        self.mouse_handler = MouseHandler(self.camera, self.tile_nodes)
Пример #21
0
def exptiles(numtilings, memctable, floats, ints=[]):
    "returns tiles which vary in size exponentially from large to small"
    floats = expfloats(floats)
    return tiles.tiles(numtilings, memctable, floats, ints)
Пример #22
0
def logtiles(numtilings, memctable, floats, ints=[]):
    "returns tiles which vary in size logarithmically from small to large"
    floats = logfloats(floats)
    return tiles.tiles(numtilings, memctable, floats, ints)
Пример #23
0
def scaletiles(numtilings, memctable, floats, widths=None, ints=[]):
    "returns tiles scaled by widths"
    floats = scalefloats(floats, widths)
    return tiles.tiles(numtilings, memctable, floats, ints)
Пример #24
0
 def terminal_update(self, reward, state, action):
   """ Update the weights after a terminal step. """
   x = tiles.tiles(self.iht, self.no_of_tiles, np.append(state, action)*self.normalise)
   q = sum([self.weights[x[i]][i] for i in range(self.no_of_tiles)])
   for i in range(self.no_of_tiles):
     self.weights[x[i]][i] += self.training_rate*(reward - q)
Пример #25
0
def runit (num=10, ct=2048, numt=1):
    for i in xrange(num):
        for j in xrange(num):
            t = tiles.tiles(numt, ct, [i*0.5, j*0.5])
Пример #26
0
def logtiles (numtilings, memctable, floats, ints=[]):
    "returns tiles which vary in size logarithmically from small to large"
    floats = logfloats(floats)
    return tiles.tiles(numtilings, memctable, floats, ints)
Пример #27
0
def scaletiles (numtilings, memctable, floats, widths=None, ints=[]):
    "returns tiles scaled by widths"
    floats = scalefloats(floats, widths)
    return tiles.tiles(numtilings, memctable, floats, ints)
Пример #28
0
def runit2 (num=10, ct=2048, numt=1):
    for i in xrange(num):
        for j in xrange(num):
            t = tiles.tiles(numt, ct, [i*0.5, j*0.5, float(i+j)/2, float(i-j)/2], [i, j])
Пример #29
0
 def get_features(self, pos, vel):
     return np.array(tiles(self.iht, self.num_tiles, [self.num_tilings * pos / (0.5 + 1.2), self.num_tilings * vel / (0.07 + 0.07)]))
Пример #30
0
            pcaT_all_cen, pcaT_info_cen, fastT_info_cen = [], [], []
            print 'Processing '+ infile+'\n'
            #k = m = 1
            for s in range(k*m):
                s += 1; print 'Complete:'+str(s)+' of '+ str(k*m) + ';'      
                train_table = uxvaltables[s]['train']['0']; test_table = uxvaltables[s]['test']['0']               
                
                discrete_table = discrete.discrete(train_table, bins)  #discrete_table[0]: original; discrete_table['d']: discrete table
                attrlst, inforgain = attrselect.attrselect(discrete_table['d'], pattr)     #select attributes    
                # tables after feature selection                
                attrtable_train = attrselect.attrtable(train_table, attrlst)                
                attrtable_test = attrselect.attrtable(test_table, attrlst)
                
                
                #test_table = projections.projections(uxvaltables[s]['test'])
                pcaT_all,tmp1 = tiles.tiles(table, numdim, outfile0)  #pca projection and clustering
                pcaT_info, tmp2 = tiles.tiles(attrtable_train, numdim, outfile0)
                #fastT_all = tiles.tilesv2(table, numdim, outfile0)
                fastT_info, tmp3 = tiles.tilesv2(attrtable_train, numdim, outfile0)     
                
                pcaT_all_cen += [tmp1]; pcaT_info_cen += [tmp2]; fastT_info_cen += [tmp3]

                #tablestr.tableprint(centroid_attr)
                tables = reader.klasses(table)
                kt = 1; mt = 2
                acc1, f1, prec1, pd1 = nb.nb(xvaltables[s]['test'], xvaltables[s]['train'], tables['names'], kt, mt)
                acc2, f2, prec2, pd2 = knn.knn(uxvaltables[s]['test'], uxvaltables[s]['train'], kn)
                # PCA Infer Methods
                acc3, f3, prec3, pd3 = newknn.knn(test_table, pcaT_all[0], kn, threshold)
                acc4, f4, prec4, pd4 = newknn.knn(attrtable_test, pcaT_info[0], kn, threshold)
Пример #31
0
import reader
import tablestr
import tiles
import math
if __name__ == "__main__":      
    filename = 'data/nasa93dem.csv'   
    table = tablestr.Table()
    reader.readcsv(filename, table) 
    tables = tiles.tiles(table)
    ntable = tables['project']
    print '# $_XX'.ljust(8), '$_YY'.ljust(8), 'log(-effort)'.ljust(8)
    for i in range(len(ntable.data[0])):
       print ntable.data[27][i].ljust(8), ntable.data[28][i].ljust(8), str(math.log(float(ntable.data[24][i]))).ljust(8)        
    print '# $_XX'.ljust(8), '$_YY'.ljust(8), 'log($_ZZ)'.ljust(8)
    for i in range(len(tables[0].data[0])):
        print tables[0].data[27][i].ljust(8), tables[0].data[28][i].ljust(8), str(math.log(float(tables[0].data[30][i]))).ljust(8)
    for k, v in tables.items():
        print '*'*20
        print 'CLASS LABEL: ', k
        tablestr.tableprint(v)
        
Пример #32
0
def main():
    t = tiles()
    while True:
        t.display_hands()
        input("Please input something")
        t.display_answer()
Пример #33
0
if __name__ == '__main__':
    loadPrcFileData("", """
        window-type none
        show-frame-rate-meter 0
        sync-video 0
    """ )

    aspect = 1.5

    width = 128
    height = int(128 * aspect)

    base = ShowBase()

    tile_lists = tiles(base)

    base.set_background_color(33/255, 46/255, 56/255)

    # use antialiasing
    base.render.setAntialias(AntialiasAttrib.MMultisample)

    # move camera
    lens = OrthographicLens()

    # TODO: How do the default camera controls work?
    base.disable_mouse()

    # create a light
    ambient = ambient_light((.3, .3, .3, 1))
    ambient = base.render.attach_new_node(ambient)
Пример #34
0
def exptiles (numtilings, memctable, floats, ints=[]):
    "returns tiles which vary in size exponentially from large to small"
    floats = expfloats(floats)
    return tiles.tiles(numtilings, memctable, floats, ints)
Пример #35
0
def diamondtiles(numtilings, memctable, floats, widths=None, ints=[]):
    "returns tiles in the shape of diamonds"
    floats = scalefloats(floats, widths)
    floats1 = diagonalfloats(floats)
    floats2 = backdiagonalfloats(floats)
    return tiles.tiles(numtilings, memctable, floats1+floats2, ints)
Пример #36
0
def runit(num=10, ct=2048, numt=1):
    for i in xrange(num):
        for j in xrange(num):
            t = tiles.tiles(numt, ct, [i * 0.5, j * 0.5])
Пример #37
0
def stripetiles(numtilings, memctable, floats, widths=None, ints=[]):
    "returns tiles in the shape of stripes (scaled by widths), a set for each dimension in floats"
    floats = scalefloats(floats, widths)
    # should another int be added here for each dimension if there is more than one?
    return reduce(operator.add, [tiles.tiles(numtilings, memctable, [f], ints) for f in floats])