示例#1
0
def get_kernel(z, k, x_range, nlayers=1000, hashing_mem=None):
    indices = []
    ntiles = []
    hashing = None
    all_cat = np.unique(z)
    if hashing_mem:
        hashing = [rp.UNH(hashing_mem) for _ in xrange(len(all_cat))]
    for a in all_cat:
        inds = helper.find(z == a)
        indices.append(inds)
        ntiles.append(k[inds])
    phi = TileCoding(
        input_indices=indices,
        # ntiles = input dim x number of layers x tilings
        ntiles=ntiles,
        ntilings=[nlayers] * len(indices),
        hashing=hashing,
        state_range=x_range,
        rnd_stream=np.random,
        bias_term=False)
    #start = time.time()
    # sparsephi = IndexToBinarySparse(phi, normalize=True)
    # gp = SparseKernelGP(self.X, self.y, sigma = 0.1, phi = sparsephi)
    # gp = SparseFeatureGP(self.X, self.y, sigma = 0.1, phi = sparsephi) too slow
    densekern = DenseKernel(phi, normalize=True)
    return densekern
示例#2
0
    def filter_norm_room(self, data):
        """Filters the normals based on the 3 room coordinates

        Args:
            data: dict containing input, depth, normal

        """
        normals = data['normal']
        normals = np.squeeze(normals, axis=0).transpose((1, 2, 0))
        normals = normals.reshape((-1, 3))
        norms = LA.norm(normals, axis=1)
        normals = (normals.T / norms).T
        room = np.asarray(get_room_directions(normals))
        idx = set()
        for direction in room:
            dist = abs(np.matmul(direction, normals.T))
            idx.update(find(dist, lambda x: x > 0.99))
        tot = set(range(normals.shape[0]))
        idx = tot - idx
        idx = list(sorted(idx))
        # pdb.set_trace()
        for index in idx:
            row = index // 64
            col = index % 64
            # data['image'][0, :, row, col] = [255, 255, 255]
            data['normal'][0, :, row, col] = [0, 0, 0]

        return data
    def get_tilegp(self):
        nlayers = self.options['nlayers']
        indices = []
        ntiles = []
        hashing = None
        all_cat = np.unique(self.z)
        if self.tilecap:
            hashing_mem = self.tilecap / len(all_cat) / nlayers
            hashing = [rp.UNH(hashing_mem) for _ in xrange(len(all_cat))]
        for a in all_cat:
            inds = helper.find(self.z == a)
            indices.append(inds)
            ntiles.append(self.k[inds])

        phi = TileCoding(
            input_indices=indices,
            # ntiles = input dim x number of layers x tilings
            ntiles=ntiles,
            ntilings=[nlayers] * len(indices),
            hashing=hashing,
            state_range=self.x_range,
            rnd_stream=np.random,
            bias_term=False)

        if self.gp_type == 'sk':
            # densekern > sparsekern \approx sparserp
            sparsekern = SparseKernel(phi, normalize=True)
            gp = SparseKernelGP(self.X, self.y, sigma=0.1, kern=sparsekern)
        elif self.gp_type == 'sf':
            # too slow
            sparsephi = IndexToBinarySparse(phi, normalize=True)
            gp = SparseFeatureGP(self.X, self.y, sigma=0.1, phi=sparsephi)

        elif self.gp_type == 'dk':
            densekern = DenseKernel(phi, normalize=True)
            gp = DenseKernelGP(self.X,
                               self.y,
                               sigma=self.sigma,
                               kern=densekern)
        else:
            random_proj = rp.sparse_random_matrix(300,
                                                  phi.size,
                                                  random_state=np.random)
            densephi = SparseRPTilecoding(phi,
                                          random_proj=random_proj,
                                          normalize=True,
                                          output_dense=True)
            gp = DenseFeatureGP(self.X, self.y, sigma=self.sigma, phi=densephi)

        gp.fit()
        return gp
    def check_update(self, forced=False):
        ''' Check for objects build version and compare.
            This pulls a dict that contains all the information for the build needed.
        '''
        LOG.info("--[ check updates/%s ]", objects.version)
        kodi = "DEV" if settings('devMode.bool') else xbmc.getInfoLabel(
            'System.BuildVersion')

        try:
            versions = requests.get(
                'http://kodi.emby.media/Public%20testing/Dependencies/databases.json'
            ).json()
            build = find(versions, kodi)

            if not build:
                raise Exception("build %s incompatible?!" % kodi)

            label, zipfile = build.split('-', 1)

            if label == 'DEV' and forced:
                LOG.info("--[ force/objects/%s ]", label)

            elif label == objects.version:
                LOG.info("--[ objects/%s ]", objects.version)

                return False

            get_objects(zipfile, label + '.zip')
            self.reload_objects()

            dialog("notification",
                   heading="{emby}",
                   message=_(33156),
                   icon="{emby}")
            LOG.info("--[ new objects/%s ]", objects.version)

            try:
                if compare_version(self.settings['addon_version'],
                                   objects.embyversion) < 0:
                    dialog("ok",
                           heading="{emby}",
                           line1="%s %s" % (_(33160), objects.embyversion))
            except Exception:
                pass

        except Exception as error:
            LOG.exception(error)

        return True
示例#5
0
def mean_shift(data, num_trails, h, epsilon, dist2):
    """find modes in the data
    Args:
        data: data dxN
        num_trails: number of trails
        h: Gaussian window
        epsilon: threshold
        dist2: distance metrics

    Returns:
        mode: modes
        score: scores of each mode

    """

    # PRINT.info('num_trails: {}, h: {}, epsilon: {}, dist2: {}'.format(
    #           num_trails, h, epsilon, dist2))

    d, N = data.shape
    num_trails = min(num_trails, N)
    rsp = np.random.permutation(N)
    rsp = rsp[0:num_trails]
    eps2 = epsilon * epsilon

    mode = np.zeros((d, num_trails))
    score = np.zeros((1, num_trails))

    for i in range(num_trails):
        x = data[:, rsp[i] - 1]
        mode[:, i], score[:, i] = __mean_shift_iteration(x, data, h, eps2, dist2)

    idxs = np.argsort(score)
    score = score[0][idxs[0]]
    mode = mode[:, idxs[0]]

    keep = np.ones((num_trails), dtype=bool)
    for i in range(0, num_trails - 1):
        x1 = np.repeat(mode[:, i][np.newaxis].T, num_trails - i - 1, axis=1)
        x2 = mode[:, i + 1:]
        d = dist2(x1, x2)
        idx = find(d, lambda x: x < (h * h))
        if len(idx):
            keep[i] = False

    score = score[keep]
    mode = mode[:, keep]

    return mode, score
示例#6
0
    def __compute_local_planes(self, X, Y, Z):
        """compute the local planes, normals, normals confidence

        Args:
            X: x coordinates
            Y: y coordinates
            Z: z coordinates

        Returns:
            imgPlanes: image planes
            imgNormals: normals for each 3d-point
            imgConfs: confidence maps
        """

        H = 192
        W = 256

        N = H * W

        # store 3d points and convert to homogeneous coordinates
        pts = np.zeros((N, 4))
        pts[:, 0] = X.ravel()
        pts[:, 1] = Y.ravel()
        pts[:, 2] = Z.ravel()
        pts[:, 3] = np.ones(N)

        u, v = np.meshgrid(np.arange(0, W), np.arange(0, H))
        u, v = u.flatten('F'), v.flatten('F')
        blockWidths = [-1, -3, -6, -9, 0, 1, 3, 6, 9]
        nu, nv = np.meshgrid(blockWidths, blockWidths)

        nx = np.zeros((H, W)).flatten()
        ny = np.zeros((H, W)).flatten()
        nz = np.zeros((H, W)).flatten()
        nd = np.zeros((H, W)).flatten()
        imgConfs = np.zeros((H, W)).flatten()

        ind_all = find(Z, lambda x: x != 0)
        for k in ind_all:
            u2 = u[k] + nu
            v2 = v[k] + nv

            # check that u2 and v2 are in the image
            valid = (u2 >= 0) & (v2 >= 0) & (u2 < W) & (v2 < H)
            u2 = u2[valid]
            v2 = v2[valid]
            ind2 = u2 * H + v2
            ind2 = sorted(ind2)

            # check that depth difference is not too large
            valid = abs(Z[ind2] - Z[k]) < Z[k] * relDepthThresh
            u2 = u2[valid]
            v2 = v2[valid]
            ind2 = u2 * H + v2
            ind2 = sorted(ind2)

            if len(u2) < 3:
                continue

            A = pts[ind2]
            [eigvalues,
             eigvectors] = np.linalg.eig(np.matmul(A.transpose(), A))
            idx = eigvalues.argsort()
            eigvalues = eigvalues[idx]
            eigvectors = eigvectors[:, idx]

            nx[k] = eigvectors[0, 0]
            ny[k] = eigvectors[1, 0]
            nz[k] = eigvectors[2, 0]
            nd[k] = eigvectors[3, 0]
            imgConfs[k] = 1 - (np.sqrt(eigvalues[0] / eigvalues[1]))

        nx = -1 * np.reshape(nx, (H, W, 1), order='F')
        ny = -1 * np.reshape(ny, (H, W, 1), order='F')
        nz = -1 * np.reshape(nz, (H, W, 1), order='F')
        nd = -1 * np.reshape(nd, (H, W, 1), order='F')
        imgConfs = -1 * np.reshape(imgConfs, (H, W), order='F')

        imgPlanes = np.concatenate((nx, ny, nz, nd), axis=2)
        length = np.sqrt(np.square(nx) + np.square(ny) + np.square(nz))
        eps = 2.2204e-16

        imgPlanes = np.divide(imgPlanes, np.repeat(length + eps, 4, axis=2))
        imgNormals = imgPlanes[:, :, 0:3]
        return imgPlanes, imgNormals, imgConfs
示例#7
0
    def check_update(self, forced=False, versions=None):
        ''' Check for objects build version and compare.
            This pulls a dict that contains all the information for the build needed.
        '''
        LOG.info("--[ check updates/%s ]", objects.version)

        if settings('devMode.bool'):
            kodi = "DEV"
        elif not self.addon_version.replace(".", "").isdigit():

            LOG.info("[ objects/beta check ]")
            kodi = "beta-%s" % xbmc.getInfoLabel('System.BuildVersion')
        else:
            kodi = xbmc.getInfoLabel('System.BuildVersion')

        try:
            versions = versions or requests.get(OBJ).json()
            build, key = find(versions, kodi)

            if not build:
                raise Exception("build %s incompatible?!" % kodi)

            label, min_version, zipfile = build['objects'][0].split('-', 2)

            if label == 'DEV' and forced:
                LOG.info("--[ force/objects/%s ]", label)

            elif compare_version(self.addon_version, min_version) < 0:
                try:
                    build['objects'].pop(0)
                    versions[key]['objects'] = build['objects']
                    LOG.info("<[ patch min not met: %s ]", min_version)

                    return self.check_update(versions=versions)

                except Exception as error:
                    LOG.info("--<[ min add-on version not met: %s ]",
                             min_version)

                    return False

            elif label == objects.version:
                LOG.info("--<[ objects/%s ]", objects.version)

                return False

            self.get_objects(zipfile, label + '.zip')
            self.reload_objects()

            dialog("notification",
                   heading="{emby}",
                   message=_(33156),
                   icon="{emby}")
            LOG.info("--<[ new objects/%s ]", objects.version)

            try:
                if compare_version(self.addon_version,
                                   objects.embyversion) < 0:
                    dialog("ok",
                           heading="{emby}",
                           line1="%s %s" % (_(33160), objects.embyversion))
            except Exception:
                pass

        except Exception as error:
            LOG.exception(error)

        return True
示例#8
0
文件: main.py 项目: iCode18/HangMan
helper.clear()
status(2)
while (wrongs > 0):
    helper.newLine(2)
    char = input("Guess a charachter: ")
    if char in choosed:
        helper.clear()
        status(1)
        print("You had this char before")
        for item in hangedPortion:
            if (len(item) > 0):
                print(item)
    else:
        choosed.append(char)
        if (char in word):
            indexList = helper.find(word, char)
            for i in indexList:
                tempGuess[i] = char
            helper.newLine()
            if ('_' not in tempGuess):
                helper.clear('You won!!!')
                print('The word was ' + word)
                helper.newLine()
                helper.draw(notHanged)
                helper.newLine()
                break
            else:
                helper.clear()
                status(2)
                for item in hangedPortion:
                    if (len(item) > 0):