Exemplo n.º 1
0
    def update(self, pops=None):
        """Master update function for the UI - redraw the visuals each update.
           """
        plt.clf()
        bg = np.max(self.terrain.heightmap) - self.terrain.heightmap
        plt.imshow(bg, cmap='Blues', interpolation='nearest')

        vmap = util.mask(self.terrain.vegetation, 1e-8)

        plt.imshow(self.norm(vmap), cmap='Greens', alpha=0.8)
        plt.imshow(util.mask(self.terrain.climates, 0.1),
                   cmap='Oranges',
                   interpolation='none',
                   alpha=0.3)

        # render Terran populations
        if pops is not None:
            for i in range(len(pops)):
                if len(pops[i].terrans) > 0:
                    pmap = pops[i].get_positions()[0]
                    pmap = util.mask(pmap, 0.1)
                    plt.imshow(pmap, cmap='Spectral', interpolation='none')

        # render storms
        if np.max(self.weather.weathermap) > 0:
            plt.imshow(util.mask(self.weather.weathermap, 0.1),
                       cmap='Purples',
                       interpolation='none',
                       alpha=0.6)

        plt.draw()
        plt.pause(0.0001)
Exemplo n.º 2
0
    def inst():
        yield delay(200 * nsec)

        addr = Signal(intbv(0x10)[len(bus.A):])

        while 1:
            yield system.CLK.posedge

            bus.CS_B.next = 0
            bus.RAS_B.next = 0
            bus.A.next = 0x4
            bus.BA.next = 0x2

            yield system.CLK.posedge

            bus.CS_B.next = 1
            bus.RAS_B.next = 1
            bus.A.next = ~0 & mask(bus.A)
            bus.BA.next = ~0 & mask(bus.BA)

            yield system.CLK.posedge

            bus.CS_B.next = 0
            bus.CAS_B.next = 0
            bus.A.next = addr
            bus.BA.next = 0

            yield system.CLK.posedge

            bus.CS_B.next = 1
            bus.CAS_B.next = 1
            bus.A.next = ~0 & mask(bus.A)
            bus.BA.next = ~0 & mask(bus.BA)

            addr.next = 0
            if addr != n - 1:
                addr.next = addr + 4

            yield system.CLK.posedge

            bus.CS_B.next = 0
            bus.CAS_B.next = 0
            bus.A.next = addr

            yield system.CLK.posedge

            bus.CS_B.next = 1
            bus.CAS_B.next = 1
            bus.A.next = ~0 & mask(bus.A)

            addr.next = 0
            if addr != n - 1:
                addr.next = addr + 4

            yield delay(interval - 1)
Exemplo n.º 3
0
 def __init__(self, width, data = None):
   self.width = width
   self.buf = []
   if data:
     mask = util.mask(self.width)
     self.buf = [x & mask for x in data]
   self.wr_idx = len(self.buf)
   self.rd_idx = 0
Exemplo n.º 4
0
Arquivo: iobuf.py Projeto: deadsy/pycs
 def __init__(self, width, data = None):
   self.width = width
   self.buf = []
   if data:
     mask = util.mask(self.width)
     self.buf = [x & mask for x in data]
   self.wr_idx = len(self.buf)
   self.rd_idx = 0
Exemplo n.º 5
0
def masks(n_ite, ifrun):
    '''对utils里的mask 的集成
    '''
    #n_ite=1
    path = 'D:\\result\\train_result\\' + str(n_ite) + 'ite'
    name_from = [
        'predict_' + str(n_ite) + '_sub1_merge',
        'predict_' + str(n_ite) + '_sub2_merge',
        'predict_' + str(n_ite) + '_sub3_merge'
    ]
    name_to = [
        'predict_' + str(n_ite) + '_sub1_mask_correct',
        'predict_' + str(n_ite) + '_sub2_mask_correct',
        'predict_' + str(n_ite) + '_sub3_mask_correct'
    ]

    if ifrun[0]:
        '''sub1'''
        if not os.path.exists(path + '\\' + name_to[0]):
            os.makedirs(path + '\\' + name_to[0])
        util.mask(path + '\\' + name_from[0], path + '\\' + name_to[0])

    if ifrun[1]:
        '''sub2'''
        if not os.path.exists(path + '\\' + name_to[1]):
            os.makedirs(path + '\\' + name_to[1])
        util.mask(path + '\\' + name_from[1], path + '\\' + name_to[1])

    if ifrun[2]:
        '''sub3'''
        if not os.path.exists(path + '\\' + name_to[2]):
            os.makedirs(path + '\\' + name_to[2])
        util.mask(path + '\\' + name_from[2], path + '\\' + name_to[2])
Exemplo n.º 6
0
    def __init__(self, game):
        """
        Constructor for the Dragon
        """
        grid = util.str_to_array(graphics.DRAGON)
        grid_col = util.tup_to_array(grid.shape,
                                     (col.Back.RED, col.Fore.BLACK))
        grid_col = util.mask(grid, grid_col)
        self.game = game

        super().__init__(grid, \
                    np.array([config.WIDTH - 50, 0], dtype="float64"), \
                    0, grid_col, config.DRAGONBOSS_LIVES, self.game)
Exemplo n.º 7
0
    def __init__(self, position, orientation=None):
        """
        Constructor for FireBeam

        Args:
            position [px, py] : Initial position of the FireBeam
            orientation (int) : 0 -> config.FIREBEAM_MAX, type of FireBeam
        """
        if orientation is None or orientation < 0 or orientation > config.FIREBEAM_MAX:
            orientation = util.randint(0, config.FIREBEAM_MAX - 1)

        rep = util.str_to_array(graphics.FIREBEAM[orientation])
        color = util.tup_to_array(rep.shape, (col.Back.RED, col.Fore.YELLOW))

        super().__init__(rep, position, np.array([-2., 0.]),
                         util.mask(rep, color))
Exemplo n.º 8
0
    def update(self):
        """Master update function for the weather map."""
        self.weathermap = np.zeros((self.size, self.size))

        # update storms & add them to map
        if (len(self.storms) > 0):
            new_storms = []
            for i in range(len(self.storms)):
                self.storms[i][0][0] += self.storms[i][1][0]
                self.storms[i][0][1] += self.storms[i][1][1]

                # wrap storms around map
                if self.storms[i][0][0] >= self.size:
                    self.storms[i][0][0] = 0
                if self.storms[i][0][1] >= self.size:
                    self.storms[i][0][1] = 0

                if self.storms[i][0][0] < 0:
                    self.storms[i][0][0] = self.size - 1
                if self.storms[i][0][1] < 0:
                    self.storms[i][0][1] = self.size - 1

                self.storms[i][2] *= (1 - self.storm_decay)
                if self.storms[i][2] > 0.1:
                    new_storms.append(self.storms[i])
                self.weathermap[int(self.storms[i][0][0]),
                                int(self.storms[i][0][1])] = self.storms[i][2]

            self.storms = new_storms
            self.weathermap = proc_smooth(self.weathermap, self.sigma)
            self.weathermap = util.mask(self.weathermap,
                                        np.average(self.weathermap) * 1.2)

        if random.random() < self.storm_chance:
            # generate random position vector for storm
            coords = [
                random.randint(0, self.size - 1),
                random.randint(0, self.size - 1)
            ]
            # generate random movement vector for storm
            direction = [
                random.uniform(-self.storm_speed, self.storm_speed),
                random.uniform(-self.storm_speed, self.storm_speed)
            ]
            self.storms.append([coords, direction, 1.0])
Exemplo n.º 9
0
    def get_rep(self, phase_offset=0):
        """
        Returns the live representation of dragon
        """
        rep = np.full((self.height, self.width), " ")
        color = util.tup_to_array(rep.shape, (col.Back.BLACK, col.Fore.GREEN))

        dragon_head = util.str_to_array(graphics.DRAGON_HEAD)
        head_h, head_w = dragon_head.shape

        # phase_offset = 4 * (phase_offset // 4)

        _h, _w = self.get_shape()

        body_width = _w - head_w

        _y = np.sin(np.linspace(-np.pi, np.pi, body_width) + phase_offset)
        _y *= (_h / 2)
        _y += (_h / 2)

        _y = _y.astype(int)

        for i in range(body_width):
            rep[_y[i]][i] = "~"

            if _y[i] > self.height - 2:
                rep[_y[i] - 2][i] = "~"
            else:
                rep[_y[i] + 1][i] = "~"

            if _y[i] == 0:
                rep[2][i] = "~"
            else:
                rep[_y[i] - 1][i] = "~"

        beg_h = int(min(_y[-1], self.height - head_h))

        rep[beg_h:beg_h + head_h, -head_w:] = dragon_head

        self.head = self.get_position() + beg_h

        color = util.mask(rep, color)

        return rep, color
Exemplo n.º 10
0
    def from_string(rep,
                    position=np.array([0., 0.]),
                    velocity=np.array([0., 0.]),
                    accel=np.array([0., 0.]),
                    gravity=0,
                    color=("", "")):
        """
        Creates a GameObject from string

        Args:
            rep (2D np.array)   : The object representation (How does it look?)
            position ([x, y])   : Initial position of the object
            velocity ([vx, vy]) : Speed with which the object moves to left
            accel ([fx, fy])    : accel in both dir
            gravity (float)     : Gravitational accel on that object
            color (str, str)    : Color of each character (bg, fg)

        Returns:
            GameObject with all the parameters
        """
        grid = util.str_to_array(rep)
        color = util.mask(grid, util.tup_to_array(grid.shape, color))

        return GameObject(grid, position, velocity, accel, gravity, color)
Exemplo n.º 11
0
    def post_process(self):
        self.init_metrics()

        self.mean_times = util.mask(self.times).cumsum(axis=0).mean(axis=1)

        # self.mean_times = np.mean(np.array([np.cumsum(self.times[i]) for i in \
        #         range(self.k)]),axis=0)

        def metrics(A, b, X):
            d = X.shape[1]
            diff = A.dot(X) - np.tile(b, (d, 1)).T
            error = 0.5 * np.diag(diff.T.dot(diff))
            RMSE = np.sqrt(error / b.size)
            den = np.sum(b) / np.sqrt(b.size)
            pRMSE = RMSE / den
            plus = A.dot(X) + np.tile(b, (d, 1)).T

            # GEH metric [See https://en.wikipedia.org/wiki/GEH_statistic]
            GEH = np.sqrt(2 * diff**2 / plus)
            meanGEH = np.mean(GEH, axis=0)
            maxGEH = np.max(GEH, axis=0)
            GEHunder5 = np.mean(GEH < 5, axis=0)
            GEHunder1 = np.mean(GEH < 1, axis=0)
            GEHunder05 = np.mean(GEH < 0.5, axis=0)
            GEHunder005 = np.mean(GEH < 0.05, axis=0)
            return {
                'error': error,
                'RMSE': RMSE,
                'pRMSE': pRMSE,
                'mean_GEH': meanGEH,
                'max_GEH': maxGEH,
                'GEH_under_5': GEHunder5,
                'GEH_under_1': GEHunder1,
                'GEH_under_0.5': GEHunder05,
                'GEH_under_0.05': GEHunder005,
            }

        def populate(d, m):
            for (k, v) in m.iteritems():
                if k not in d:
                    d[k] = []
                d[k].append(v)
            return d

        for i, (train, test) in enumerate(self.kf):
            d = len(self.states[i])
            b_train, A_train = self.b[train], self.A[train, :]
            b_test, A_test = self.b[test], self.A[test, :]
            self.x_hat = self.N.dot(np.array(self.states[i]).T) + \
                    np.tile(self.x0,(d,1)).T

            # Aggregate error
            m = metrics(A_train, b_train, self.x_hat)
            self.train = populate(self.train, m)
            logging.debug(
                'Train: %8.5e to %8.5e (%8.5e)' %
                (m['RMSE'][0], m['RMSE'][-1], m['RMSE'][0] - m['RMSE'][-1]))

            m = metrics(A_test, b_test, self.x_hat)
            self.test = populate(self.test, m)
            logging.debug(
                'Test: %8.5e to %8.5e (%8.5e)' %
                (m['RMSE'][0], m['RMSE'][-1], m['RMSE'][0] - m['RMSE'][-1]))

            # TODO deprecate
            x_last = self.x_hat[:, -1]
            dist_from_true = np.max(np.abs(x_last - self.x_true))
            start_dist_from_true = np.max(np.abs(self.x_true - self.x0))
            logging.debug('max|x-x_true|: %.2f\nmax|x_init-x_true|: %.2f' \
                    % (dist_from_true, start_dist_from_true))

            # Error metric by link class
            inds = np.digitize(b_train, self.bins)
            indts = np.digitize(b_test, self.bins)
            train_bin, test_bin = {}, {}
            for j in range(1, self.nbins + 2):
                ind = inds == j
                indt = indts == j
                if np.all(indt == False) or np.all(ind == False):
                    for k in KEYS:
                        if k not in train_bin:
                            train_bin[k] = []
                        train_bin[k].append(None)
                    for k in KEYS:
                        if k not in test_bin:
                            test_bin[k] = []
                        test_bin[k].append(None)
                    continue

                b_bin, A_bin = b_train[ind], A_train[ind, :]
                b_bint, A_bint = b_test[indt], A_test[indt, :]

                m = metrics(A_bin, b_bin, self.x_hat)
                train_bin = populate(train_bin, m)

                m = metrics(A_bint, b_bint, self.x_hat)
                test_bin = populate(test_bin, m)

            self.train_bin = populate(self.train_bin, train_bin)
            self.test_bin = populate(self.test_bin, test_bin)

        # Summary metrics
        self.mean_time = np.mean([np.cumsum(self.times[i])[-1] for i in \
                range(self.k)])
        self.mean_error = np.mean([self.test['error'][i][-1] for i in \
                range(self.k)])
        self.mean_RMSE = np.mean([self.test['RMSE'][i][-1] for i in \
                range(self.k)])
        logging.debug('mean time: %8.5e, mean error: %8.5e' %
                      (self.mean_time, self.mean_error))
        print '\n\n'
Exemplo n.º 12
0
 def __call__(self, sample):
     gene = np.array(list(sample['gene'].sequence))
     next_gene = np.array(list(sample['next_gene'].sequence))
     gene_seq = mutate(gene, self.mutate_prob, self.vocab)
     gene_seq = mask(gene_seq, prob=self.mask_prob, mask_chr=self.mask_chr)
     return {'gene_seq': gene_seq, 'next_seq': next_gene}
Exemplo n.º 13
0
 def seq():
     if self.RD:
         self.DAT.next = self.ADR & mask(self.DAT)