Example #1
1
    def computeArea(self, A, B, C, D, E, F, G, H):
        result = (C - A) * (D - B) + (G - E) * (H - F)
        if C < E or D < F or A > G or B > H:
            return result

        top, bottom, left, right = min(D, H), max(B, F), max(A, E), min(C, G)
        return result - (right - left) * (top - bottom)
Example #2
1
def four_point_transform(image, pts):  # original_points):
    """Take a rotate patch from an image and straightens it. 
    """
    # obtain a consistent order of the points and unpack them
    # individually
    # pts = np.copy(original_points)
    rect = order_points(pts)
    (tl, tr, br, bl) = rect
    # compute the width of the new image, which will be the
    # maximum distance between bottom-right and bottom-left
    # x-coordiates or the top-right and top-left x-coordinates
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
    maxWidth = max(int(widthA), int(widthB))

    # compute the height of the new image, which will be the
    # maximum distance between the top-right and bottom-right
    # y-coordinates or the top-left and bottom-left y-coordinates
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
    maxHeight = max(int(heightA), int(heightB))

    # now that we have the dimensions of the new image, construct
    # the set of destination points to obtain a "birds eye view",
    # (i.e. top-down view) of the image, again specifying points
    # in the top-left, top-right, bottom-right, and bottom-left
    # order
    dst = np.array([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32")

    # compute the perspective transform matrix and then apply it
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))

    # return the warped image
    return warped
Example #3
1
    def resizeColumnsToContents(self):
        """Reimplemented to support proportional column width specifications."""

        editor = self._editor
        available_space = self.viewport().width()
        hheader = self.horizontalHeader()

        # Compute sizes for columns with absolute or no size requests
        proportional = []
        for column_index in xrange(len(editor.columns)):
            requested_width = editor.columns[column_index].get_width()
            if 0 < requested_width < 1:
                proportional.append((column_index, requested_width))
            else:
                base_width = hheader.sectionSizeHint(column_index)
                width = max(base_width, self.sizeHintForColumn(column_index))
                hheader.resizeSection(column_index, width)
                available_space -= width

        # Now use the remaining space for columns with proportional width
        # requests
        for column_index, percent in proportional:
            base_width = hheader.sectionSizeHint(column_index)
            width = max(base_width, int(percent * available_space))
            hheader.resizeSection(column_index, width)
Example #4
1
    def buildCache(self):
        """ merges corpora and computes probabilities
        """
        self.cache = {}
        for pname, pool in self.pools.items():
            # skip our special pool
            if pname == "__Corpus__":
                continue

            poolCount = pool.tokenCount
            themCount = max(self.corpus.tokenCount - poolCount, 1)
            cacheDict = self.cache.setdefault(pname, self.dataClass(pname))

            for word, totCount in self.corpus.items():
                # for every word in the copus
                # check to see if this pool contains this word
                thisCount = float(pool.get(word, 0.0))
                if thisCount == 0.0:
                    continue
                otherCount = float(totCount) - thisCount

                if not poolCount:
                    goodMetric = 1.0
                else:
                    goodMetric = min(1.0, otherCount / poolCount)
                badMetric = min(1.0, thisCount / themCount)
                f = badMetric / (goodMetric + badMetric)

                # PROBABILITY_THRESHOLD
                if abs(f - 0.5) >= 0.1:
                    # GOOD_PROB, BAD_PROB
                    cacheDict[word] = max(0.0001, min(0.9999, f))
Example #5
1
def perform_scaling(data, electrode_indices):
    """This function, suprisingly, performs scaling on a given set of data.

    The data is returned as a dictionary of 8 differently scaled data sets. The
    8 data sets represents all combinations of the following scaling
    methodologies:
        'Vector' of 'MinMax' scaling
        'Within'- or 'Across'-subject scaling
        'All' or 'Few' electrodes included in scaling

    The data can be accessed in the following way:
    
    data_scaled = perform_scaling(data, electrode_indices)
    print(data_scaled['Vector']['Across']['All']
    
    """
    # TODO: Should the scaled for selected electrodes data retain all the
    # unscaled values? I.e. for compatibility with other scripts - i.e. the
    # electrode numbers will be all screwed up...
    data_scaled = {
        "Vector": {"Across": {"All": None, "Few": None}, "Within": {"All": None, "Few": None}},
        "MaxMin": {"Across": {"All": None, "Few": None}, "Within": {"All": None, "Few": None}},
    }

    mean_all = mean(data, 0)
    mean_few = mean(data[:, electrode_indices], 0)

    data_scaled["Vector"]["Across"]["All"] = copy(data) / sqrt(vdot(mean_all, mean_all))
    data_scaled["Vector"]["Across"]["Few"] = copy(data) / sqrt(vdot(mean_few, mean_few))

    min_point = min(mean_all)
    max_point = max(mean_all)
    diff = max_point - min_point
    data_scaled["MaxMin"]["Across"]["All"] = (copy(data) - min_point) / diff
    min_point = min(mean_few)
    max_point = max(mean_few)
    diff = max_point - min_point
    data_scaled["MaxMin"]["Across"]["Few"] = (copy(data) - min_point) / diff

    data_scaled["Vector"]["Within"]["All"] = zeros(data.shape)
    data_scaled["Vector"]["Within"]["Few"] = zeros(data.shape)
    data_scaled["MaxMin"]["Within"]["All"] = zeros(data.shape)
    data_scaled["MaxMin"]["Within"]["Few"] = zeros(data.shape)
    for i in range(data.shape[0]):
        data_scaled["Vector"]["Within"]["All"][i, :] = copy(data[i, :]) / sqrt(vdot(data[i, :], data[i, :]))
        data_scaled["Vector"]["Within"]["Few"][i, :] = copy(data[i, :]) / sqrt(
            vdot(data[i, electrode_indices], data[i, electrode_indices])
        )

        min_point = min(data[i, :])
        max_point = max(data[i, :])
        diff = max_point - min_point
        data_scaled["MaxMin"]["Within"]["All"][i, :] = (copy(data[i, :]) - min_point) / diff

        min_point = min(data[i, electrode_indices])
        max_point = max(data[i, electrode_indices])
        diff = max_point - min_point
        data_scaled["MaxMin"]["Within"]["Few"][i, :] = (copy(data[i, :]) - min_point) / diff

    return data_scaled
    def maxsr_distance_between_codingblocks(self, other, organism=None):
        """
        Distance in AA between two CodingBlockGraphs measured on their maxsr

        @type  organism: *
        @param organism: Organism identifier (or None)

        @rtype:  dictionary (or integer if organism or node is specified)
        @return: dictionary with organisms (keys) and AA-distance between CBGs (values),
                 or only a distance if an Organism identifier was specified
        @attention: other (CBG) is supposed to be 3p/rigth of 'self' (current CBG)
        """

        # get maximal spanning ranges
        maxsrSelf = self.maximal_spanning_range()
        maxsrOther = other.maximal_spanning_range()
        distances = {}
        for org in self.organism_set().intersection(other.organism_set()):
            if organism and org != organism:
                continue
            nodeA = self.node_by_organism(org)
            nodeB = other.node_by_organism(org)
            # although other is supposed to be 3p of self, take both
            # orientations into account.
            distA = min(maxsrSelf[nodeA]) - max(maxsrOther[nodeB]) - 1
            distB = min(maxsrOther[nodeB]) - max(maxsrSelf[nodeA]) - 1
            distances[org] = max([0, distA, distB])

        # return distance only of a specific organism is requested for
        if organism:
            return distances[organism]
        else:
            return distances
 def changeColor(self):
     colorVector = self.getColor()
     colorDec = 0.03
     colorVector = breve.vector(
         max(colorVector[0] - colorDec, 0), max(colorVector[1] - colorDec, 0), max(colorVector[2] - colorDec, 0)
     )
     self.setColor(colorVector)
Example #8
1
def panimage(ima, columns=5):
    "panimage(ima) - display ima in a scrolled window"
    top = Tkinter.Toplevel()
    top.title("panimage ")
    Pmw.initialise()
    sf = Pmw.ScrolledFrame(top, labelpos=N, label_text="Image Array", usehullsize=1, hull_width=700, hull_height=420)
    sf.pack(fill="both", expand=1)
    frame = []
    image = []
    numb = []
    vminl = []
    vmaxl = []
    nd = len(ima)
    h = len(ima[0])
    w = len(ima[0][0])
    pal = readPalette()
    for i in range(nd):
        im = array(ima[i])
        vmin, vmax = max(max(im)), min(min(im))
        da = preprocess(im)
        frame.append(Tkinter.Frame(sf.interior()))
        image.append(PNGImage2(frame[i], da, pal=pal, tmpNm="tmp.ppm"))
        image[i].pack(side="top")
        dn = "Image Array : Seq # " + str(i) + ": "
        numb.append(Tkinter.Label(frame[i], text=dn))
        numb[i].pack(side="top")
        vminl.append(Tkinter.Label(frame[i], text="min:" + str(vmin)))
        vminl[i].pack(side="top")
        vmaxl.append(Tkinter.Label(frame[i], text="max:" + str(vmax)))
        vmaxl[i].pack(side="top")
        frame[i].grid(row=i / columns, column=i % columns, padx=0, pady=5)
Example #9
1
 def set_cursor(self, param):
     x, sep, y = param.partition(";")
     x = to_int(x, 1) - 1
     y = to_int(y, 1) - 1
     sbinfo = self.screen_buffer_info()
     new_pos = COORD(min(max(0, x), sbinfo.Size.X), min(max(0, y), sbinfo.Size.Y))
     windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)
Example #10
0
    def on_touch_move(self, touch):
        if touch.grab_current == self:
            if touch.ud["page"] == "previous":
                self.children[-self.page - 1].x = max(
                    min(self.x + self.border + (touch.x - touch.ox), self.right - self.border), self.x + self.border
                )

                if self.page > 1:
                    self.children[-self.page].x = min(
                        self.x + self.border * (touch.sx - touch.osx), self.x + self.border
                    )

                if self.page < len(self.children) - 1:
                    self.children[-self.page + 1].x = min(
                        self.right - self.border * (1 - (touch.sx - touch.osx)), self.right
                    )

            elif touch.ud["page"] == "next":
                self.children[-self.page + 1].x = min(
                    max(self.right - self.border + (touch.x - touch.ox), self.x + self.border), self.right - self.border
                )

                if self.page >= 1:
                    self.children[-self.page - 1].x = max(self.x + self.border * (1 - (touch.osx - touch.sx)), self.x)

                if self.page < len(self.children) - 2:
                    self.children[-self.page].x = max(
                        self.right + self.border * (touch.sx - touch.osx), self.right - self.border
                    )

        return self.children[-self.page - 1].on_touch_move(touch)
Example #11
0
 def reinit(self, A0, A1, B0, B1, C0, C1, D0, D1):
     self.box[:, :] = 0.0
     self.A0 = A0
     self.A1 = A1
     self.B0 = B0
     self.B1 = B1
     self.C0 = C0
     self.C1 = C1
     self.D0 = D0
     self.D1 = D1
     self.offset0 = int(floor(min(self.A0, self.B0, self.C0, self.D0)))
     self.offset1 = int(floor(min(self.A1, self.B1, self.C1, self.D1)))
     self.box_size0 = int(ceil(max(self.A0, self.B0, self.C0, self.D0))) - self.offset0
     self.box_size1 = int(ceil(max(self.A1, self.B1, self.C1, self.D1))) - self.offset1
     self.A0 -= self.offset0
     self.A1 -= self.offset1
     self.B0 -= self.offset0
     self.B1 -= self.offset1
     self.C0 -= self.offset0
     self.C1 -= self.offset1
     self.D0 -= self.offset0
     self.D1 -= self.offset1
     self.pAB = self.pBC = self.pCD = self.pDA = None
     self.cAB = self.cBC = self.cCD = self.cDA = None
     self.area = None
Example #12
0
def team_glicko():
    team_glicko = {}
    for game in Game.select(
        sqlbuilder.IN(Game.q.id, sqlbuilder.Select(GameTeam.q.gameID, where=GameTeam.q.score > 0)), orderBy="date"
    ):

        pre_game = []
        for gameTeam in game.gameTeams:
            r, rd, t0 = team_glicko.get(gameTeam.team.id, (glicko.start_r, glicko.start_rd, datetime.datetime.now()))
            t = max((game.date - t0).days, 1)
            pre_game.append((gameTeam.team, r, rd, t, gameTeam.score))
        assert len(pre_game) == 2, "Should have exactly two teams in game"

        (teama, ra, rda, ta, scorea), (teamb, rb, rdb, tb, scoreb) = pre_game
        if scorea > scoreb:
            sa = 1
            sb = 0
        elif scorea == scoreb:
            sa = 0.5
            sb = 0.5
        else:
            sa = 0
            sb = 1

        xa, ya = compute_glicko(ta, ra, rda, [(rb, rdb, sa)])
        xb, yb = compute_glicko(tb, rb, rdb, [(ra, rda, sb)])
        team_glicko[teama.id] = (xa, ya, game.date)
        team_glicko[teamb.id] = (xb, yb, game.date)

    for key, (r, rd, t0) in team_glicko.iteritems():
        t = max((datetime.datetime.now() - t0).days, 1)
        rd = compute_glicko_pre_rd(rd, t)
        team_glicko[key] = (r, rd, t0)

    return team_glicko
Example #13
0
File: tabgroup.py Project: Reve/eve
    def LoadTabs(self, tabs, autoselecttab = 1, settingsID = None, iconOnly = False, silently = False):
        self._iconOnly = iconOnly
        self.sr.tabs = []
        self.sr.mytabs = []
        self.sr.tabsmenu = None
        self.Flush()
        self.Prepare_LeftSide_()
        maxTextHeight = 0
        for data in tabs:
            newtab = self.GetTabClass()(parent=self)
            self.sr.mytabs.append(newtab)
            newtab.Startup(self, data)
            newtab.align = uiconst.TOLEFT
            self.sr.Set('%s_tab' % data.label, newtab)
            self.sr.tabs.append(newtab)
            maxTextHeight = max(maxTextHeight, newtab.sr.label.textheight)
            if newtab.sr.icon:
                maxTextHeight = max(maxTextHeight, newtab.sr.icon.height)

        self.Prepare_RightSide_()
        self.height = max(MINTABGROUPHEIGHT, int(maxTextHeight * 1.7))
        self._inited = 1
        self._settingsID = settingsID
        self.UpdateSizes()
        if autoselecttab:
            self.AutoSelect(silently)
Example #14
0
def intensity_props(data, blob, min_rad=4):
    """
    Return the mean and std for the elliptical region in the given data.

    Parameters
    ----------
    data : LowerDimensionalObject or SpectralCube
        Data to estimate the background from.
    blob : numpy.array
        Contains the properties of the region.

    """

    y, x, major, minor, pa = blob[:5]

    inner_ellipse = Ellipse2D(True, x, y, max(min_rad, 0.75 * major), max(min_rad, 0.75 * minor), pa)

    yy, xx = np.mgrid[: data.shape[-2], : data.shape[-1]]

    ellip_mask = inner_ellipse(xx, yy).astype(bool)

    vals = data[ellip_mask]

    mean, sig = robust_skewed_std(vals)

    return mean, sig
Example #15
0
def str_aligned(results, header=None):
    """
    Given a tuple, generate a nicely aligned string form.
    >>> results = [["a","b","cz"],["d","ez","f"],[1,2,3]]
    >>> print(str_aligned(results))
    a    b   cz
    d   ez    f
    1    2    3

    Args:
        result: 2d sequence of arbitrary types.
        header: optional header

    Returns:
        Aligned string output in a table-like format.
    """
    k = list(zip(*results))
    stringlengths = list()
    count = 0
    for i in k:
        col_max_len = max([len(str(m)) for m in i])
        if header is not None:
            col_max_len = max([len(str(header[count])), col_max_len])
        stringlengths.append(col_max_len)
        count += 1
    format_string = "   ".join(["%" + str(d) + "s" for d in stringlengths])
    returnstr = ""
    if header is not None:
        header_str = format_string % tuple(header)
        returnstr += header_str + "\n"
        returnstr += "-" * len(header_str) + "\n"
    return returnstr + "\n".join([format_string % tuple(result) for result in results])
def plotErrorBars(dict_to_plot, x_lim, y_lim, xlabel, y_label, title, out_file, margin=[0.05, 0.05], loc=2):

    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(y_label)

    if y_lim is None:
        y_lim = [1 * float("Inf"), -1 * float("Inf")]

    max_val_seen_y = y_lim[1] - margin[1]
    min_val_seen_y = y_lim[0] + margin[1]
    print min_val_seen_y, max_val_seen_y
    max_val_seen_x = x_lim[1] - margin[0]
    min_val_seen_x = x_lim[0] + margin[0]
    handles = []
    for k in dict_to_plot:
        means, stds, x_vals = dict_to_plot[k]

        min_val_seen_y = min(min(np.array(means) - np.array(stds)), min_val_seen_y)
        max_val_seen_y = max(max(np.array(means) + np.array(stds)), max_val_seen_y)

        min_val_seen_x = min(min(x_vals), min_val_seen_x)
        max_val_seen_x = max(max(x_vals), max_val_seen_x)

        handle = plt.errorbar(x_vals, means, yerr=stds)
        handles.append(handle)
        print max_val_seen_y
    plt.xlim([min_val_seen_x - margin[0], max_val_seen_x + margin[0]])
    plt.ylim([min_val_seen_y - margin[1], max_val_seen_y + margin[1]])
    plt.legend(handles, dict_to_plot.keys(), loc=loc)
    plt.savefig(out_file)
Example #17
0
    def __layout(self):
        w = self.width() - 20
        items = self.__item_area.children()

        num_x = max(math.ceil(w / (self.__item_sizeX + self.__space)), 1)  # Can do -1
        num_y = math.ceil(len(items) / num_x)
        self.__item_area.resize(w, num_y * (self.__item_sizeY + self.__space) + 50)

        main_w = self.__item_area.width()
        main_h = self.__item_area.height()
        num_x = max(math.ceil(main_w / (self.__item_sizeX + self.__space)), 1)  # Can do -1

        x = 0
        y = 0
        for i in range(len(items)):
            space_x = 0
            if self.__auto_space:
                space_x = (main_w - self.__space * 2 - num_x * (self.__item_sizeX + self.__space)) / num_x
            items[i].move(
                self.__space * 2 + x * (self.__item_sizeX + self.__space + space_x),
                self.__space * 2 + y * (self.__item_sizeY + self.__space),
            )
            x += 1
            if x >= num_x:
                x = 0
                y += 1

        return True
Example #18
0
 def repr_int(self, x, level):
     s = builtins.repr(x)  # XXX Hope this isn't too slow...
     if len(s) > self.maxlong:
         i = max(0, (self.maxlong - 3) // 2)
         j = max(0, self.maxlong - 3 - i)
         s = s[:i] + "..." + s[len(s) - j :]
     return s
Example #19
0
    def get_prob(self, neighbours):
        """
        Calculates the probabilities of the labels, based on the neighboring
        instances.
     
        :param neighbours: a list of nearest neighboring instances.
        :type neighbours: list of :class:`Orange.data.Instance`
        
        :rtype: the prob of the labels
        
        """
        total = 0
        label_count = len(self.instances.domain.class_vars)
        confidences = [1.0 / max(1, len(self.instances))] * label_count

        total = float(label_count) / max(1, len(self.instances))

        for neigh in neighbours:
            vals = neigh.get_classes()
            for j, value in enumerate(vals):
                if value == "1":
                    confidences[j] += 1
            total += 1

        # Normalize distribution
        if total > 0:
            confidences = [con / total for con in confidences]

        return confidences
Example #20
0
    def check(self):
        """
        Determine how long until the next scheduled time for a Task.
        Returns the number of seconds until the next scheduled time or zero
        if the task needs to be run immediately.
        If it's an hourly task and it's never been run, run it now.
        If it's a daily task and it's never been run and the hour is right, run it now.
        """
        boto.log.info("checking Task[%s]-now=%s, last=%s" % (self.name, self.now, self.last_executed))

        if self.hourly and not self.last_executed:
            return 0

        if self.daily and not self.last_executed:
            if int(self.hour) == self.now.hour:
                return 0
            else:
                return max((int(self.hour) - self.now.hour), (self.now.hour - int(self.hour))) * 60 * 60

        delta = self.now - self.last_executed
        if self.hourly:
            if delta.seconds >= 60 * 60:
                return 0
            else:
                return 60 * 60 - delta.seconds
        else:
            if int(self.hour) == self.now.hour:
                if delta.days >= 1:
                    return 0
                else:
                    return 82800  # 23 hours, just to be safe
            else:
                return max((int(self.hour) - self.now.hour), (self.now.hour - int(self.hour))) * 60 * 60
Example #21
0
 def move_cursor(self, x_offset=0, y_offset=0):
     sbinfo = self.screen_buffer_info()
     new_pos = COORD(
         min(max(0, sbinfo.CursorPosition.X + x_offset), sbinfo.Size.X),
         min(max(0, sbinfo.CursorPosition.Y + y_offset), sbinfo.Size.Y),
     )
     windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)
Example #22
0
def contrast(in_low, in_hi, out_low, out_hi, minimum, maximum, inc=1):
    """ create a contrast stretch lookup table
        in_low - input low image value
        in_hi  - input high image value
        out_low - output low image value
        out_hi  - output high image value
        minimum - minimum data value
        maximum - maximum data value
        inc     - increment
    """

    smallFloat = 0.00000000000001

    if in_hi == in_low:
        slope = 0
    else:
        slope = float(out_hi - out_low) / float(in_hi - in_low)

    lookup = []
    for input_value in xrange(minimum, maximum + 1, inc):
        out_value = out_low + int(round((input_value - in_low) * slope + smallFloat))
        if slope < 0:
            out_value = max(min(out_value, out_low), out_hi)
        else:
            out_value = min(max(out_value, out_low), out_hi)

        indx = input_value - minimum

        for i in xrange(inc):
            lookup.insert(indx, out_value)
            indx = indx + 1

    return lookup
Example #23
0
    def _redraw(self):
        self.figure.clear()
        self.figure.add_axes([0.1, 0.1, 0.8, 0.8])
        figure = self.figure
        axes = figure.axes[0]
        axes.clear()

        if self.sorted_on == True:
            scalar_arr = self.scalar_arr_sorted
        else:
            scalar_arr = self.scalar_arr

        xi = linspace(min(self.data.cut_x), max(self.data.cut_x), 100)

        x = (ones_like(scalar_arr) * self.data.cut_x).flatten()
        ny_row = scalar_arr.shape[0]
        dy = max(diff(self.data.cut_x))
        yi = linspace(0, ny_row * dy, ny_row)
        y = (ones_like(scalar_arr).T * linspace(0, ny_row * dy, ny_row)).T.flatten()
        z = scalar_arr.flatten()
        zi = griddata(x, y, z, xi, yi, interp="nn")

        # contour the gridded data, plotting dots at the nonuniform data points
        # axes.contour( xi, yi, zi, 20, linewidths = .5, colors = 'k' )
        # plotting filled contour
        axes.contourf(xi, yi, zi, 200, cmap=my_cmap_lin)  # my_cmap_lin
        scat = axes.scatter(x, y, marker="o", c=z, s=20, linewidths=0, cmap=my_cmap_lin)
        figure.colorbar(scat)

        self.data_changed = True
Example #24
0
def highPass2DFilter(sdataset, user_stretchval="Contrast", user_britlo=0, user_brithi=255):
    """ 2 dimensional high pass filter from McIDAS-X
        equation for each sdataset element = (sdataset - (sample average) + (sample midpoint))
        user_britlo    - minimum brightness value for the calibration
        user_brithi    - maximum brightness value for the calibration
    """

    newData = sdataset.clone()
    stretch = user_stretchval
    britlo = int(user_britlo)
    brithi = int(user_brithi)

    for t in xrange(newData.getDomainSet().getLength()):
        rangeObject = newData.getSample(t)
        vals = rangeObject.getFloats(0)
        in_hi = max(vals[0])
        in_low = min(vals[0])
        domain = GridUtil.getSpatialDomain(rangeObject)
        [element_size, line_size] = domain.getLengths()

        """ first and last 2 lines of the image do not change """
        firstLine = vals[0][0:element_size]
        last2Lines = vals[0][(line_size - 2) * element_size : line_size * element_size]

        """ do the filter using 3 lines at a time """
        for i in range(line_size)[:-3]:
            for j in range(element_size)[1:-1]:
                midValue = vals[0][(i + 1) * element_size + j]

                val = (
                    vals[0][(i + 2) * element_size + j]
                    + vals[0][i * element_size + j]
                    + vals[0][(i + 1) * element_size + j + 1]
                    + vals[0][(i + 1) * element_size + j - 1]
                ) - 4 * midValue

                if val < midValue:
                    vals[0][i * element_size + j] = scaleOutsideVal(midValue - val, britlo, brithi)
                else:
                    vals[0][i * element_size + j] = 0

        vals[0][0 : line_size * element_size] = firstLine + vals[0][0 : (line_size - 3) * element_size] + last2Lines

        for i in range(line_size):
            for j in range(element_size):
                vals[0][i * element_size + j] = scaleOutsideVal(vals[0][i * element_size + j], britlo, brithi)

        filt_low = int(min(vals[0]))
        filt_hi = int(max(vals[0]))

        if stretch == "Contrast":
            lookup = contrast(filt_low, filt_hi, britlo, brithi, filt_low, filt_hi)
        elif stretch == "Histogram":
            h = makeHistogram(vals, element_size, line_size, filt_low, brithi - britlo)
            lookup = histoStretch(filt_low, filt_hi, in_low, in_hi, h)

        vals = modify(vals, element_size, line_size, filt_low, lookup)
        rangeObject.setSamples(vals)

    return newData
Example #25
0
    def argmax(self, segment=None, known_first=False):
        """Get most frequent label


        Parameters
        ----------
        segment : Segment, optional
            Section of annotation where to look for the most frequent label.
            Defaults to whole annotation extent.
        known_first: bool, optional
            If True, artificially reduces the duration of intersection of
            `Unknown` labels so that 'known' labels are returned first.

        Returns
        -------
        label : any existing label or None
            Label with longest intersection

        Examples
        --------

            >>> annotation = Annotation(modality='speaker')
            >>> annotation[Segment(0, 10), 'speaker1'] = 'Alice'
            >>> annotation[Segment(8, 20), 'speaker1'] = 'Bob'
            >>> print "%s is such a talker!" % annotation.argmax()
            Bob is such a talker!
            >>> segment = Segment(22, 23)
            >>> if not annotation.argmax(segment):
            ...    print "No label intersecting %s" % segment
            No label intersection [22 --> 23]

        """

        # if annotation is empty, obviously there is no most frequent label
        if not self:
            return None

        # if segment is not provided, just look for the overall most frequent
        # label (ie. set segment to the extent of the annotation)
        if segment is None:
            segment = self.get_timeline().extent()

        # compute intersection duration for each label
        durations = {
            lbl: self.label_timeline(lbl).crop(segment, mode="intersection").duration() for lbl in self.labels()
        }

        # artifically reduce intersection duration of Unknown labels
        # so that 'known' labels are returned first
        if known_first:
            maxduration = max(durations.values())
            for lbl in durations.keys():
                if isinstance(lbl, Unknown):
                    durations[lbl] = durations[lbl] - maxduration

        # find the most frequent label
        label = max(durations.iteritems(), key=operator.itemgetter(1))[0]

        # in case all durations were zero, there is no most frequent label
        return label if durations[label] > 0 else None
Example #26
0
def GetValidTypeInfos(typename, items=[]):
    if typename in internal_types:
        return internal_types[typename]
    else:
        result = type_model.match(typename)
        if result:
            values = result.groups()
            if values[0] == "UNSIGNED" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
                typeinfos = ("UNS%s" % values[1], None, "uint%s" % values[1], True)
            elif values[0] == "INTEGER" and int(values[1]) in [i * 8 for i in xrange(1, 9)]:
                typeinfos = ("INTEGER%s" % values[1], None, "int%s" % values[1], False)
            elif values[0] == "REAL" and int(values[1]) in (32, 64):
                typeinfos = ("%s%s" % (values[0], values[1]), None, "real%s" % values[1], False)
            elif values[0] in ["VISIBLE_STRING", "OCTET_STRING"]:
                size = default_string_size
                for item in items:
                    size = max(size, len(item))
                if values[1] != "":
                    size = max(size, int(values[1]))
                typeinfos = ("UNS8", size, "visible_string", False)
            elif values[0] == "DOMAIN":
                size = 0
                for item in items:
                    size = max(size, len(item))
                typeinfos = ("UNS8", size, "domain", False)
            elif values[0] == "BOOLEAN":
                typeinfos = ("UNS8", None, "boolean", False)
            else:
                raise ValueError, _("""!!! %s isn't a valid type for CanFestival.""") % typename
            if typeinfos[2] not in ["visible_string", "domain"]:
                internal_types[typename] = typeinfos
        else:
            raise ValueError, _("""!!! %s isn't a valid type for CanFestival.""") % typename
    return typeinfos
    def distance_between_codingblocks(self, other, organism=None, node=None):
        """
        Distance in AA between two CodingBlockGraphs

        @type  organism: *
        @param organism: Organism identifier (or None)

        @type  node: *
        @param node: Node identifier (or None)

        @rtype:  dictionary (or integer if organism or node is specified)
        @return: dictionary with organisms (keys) and AA-distance between CBGs (values),
                 or only a distance if an Organism or Node identifier was specified

        @attention: other (CBG) is supposed to be 3p/rigth of 'self' (current CBG)
        """

        # get overall minimal spanning ranges
        omsrSelf = self.overall_minimal_spanning_range()
        omsrOther = other.overall_minimal_spanning_range()
        distances = {}
        for org in self.organism_set().intersection(other.organism_set()):
            if organism and org != organism:
                continue
            nodeA = self.node_by_organism(org)
            nodeB = other.node_by_organism(org)
            distA = min(omsrSelf[nodeA]) - max(omsrOther[nodeB])
            distB = min(omsrOther[nodeB]) - max(omsrSelf[nodeA])
            distances[org] = max([distA, distB]) - 1

        # return distance only of a specific organism is requested for
        if organism:
            return distances[organism]
        else:
            return distances
Example #28
0
 def __handle_select_button_ccs(self, cc_no, cc_value):
     if cc_no == FX_SELECT_FIRST_BUTTON_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             self.__parent.toggle_lock()
     elif cc_no == FX_SELECT_ENCODER_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             new_index = min(
                 len(self.song().scenes) - 1,
                 max(0, list(self.song().scenes).index(self.song().view.selected_scene) - 1),
             )
             self.song().view.selected_scene = self.song().scenes[new_index]
     elif cc_no == FX_SELECT_SECOND_BUTTON_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             new_index = min(
                 len(self.song().scenes) - 1,
                 max(0, list(self.song().scenes).index(self.song().view.selected_scene) + 1),
             )
             self.song().view.selected_scene = self.song().scenes[new_index]
     elif cc_no == FX_SELECT_POTIE_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             self.song().view.selected_scene.fire_as_selected()
     elif cc_no == FX_SELECT_DRUM_PAD_ROW:
         if cc_value == CC_VAL_BUTTON_PRESSED:
             self.song().stop_all_clips()
     else:
         raise False or AssertionError, "unknown select row midi message"
Example #29
0
def plot_value_function(agent_class, run, i):
    """ Plot the value functions for run i. """
    plt.clf()
    agent = load(agent_class, run)
    state0 = simulator.Simulator().get_state()
    values, qval1, qval2 = [], [], []
    min_range = -SHIFT_VECTOR[i]
    max_range = SCALE_VECTOR[i]
    variables = []
    for j in range(VALUE_STEPS):
        var = max_range * (1.0 * j / VALUE_STEPS) + min_range
        state0[i] = var
        values.append(agent.value_function(state0))
        feat = agent.action_features[0](state0)
        qval1.append(agent.action_weights[0].dot(feat))
        qval2.append(agent.action_weights[1].dot(feat))
        variables.append(var)
    max_val = max(max(qval1), max(qval2), min(values))
    min_val = min(min(qval1), min(qval2), min(values))
    plt.plot(variables, values, "-b", label="$V(s)$")
    plt.plot(variables, qval1, "-r", label="$Q(s, a_1)$")
    plt.plot(variables, qval2, "-g", label="$Q(s, a_2)$")
    plt.axis([min_range, max_range, min_val, max_val])
    plt.legend(loc="lower right")
    plt.xlabel(str(i))
    plt.ylabel("$V$")
    plt.savefig("./runs/" + agent.name + "/value_functions/s" + str(i), bbox_inches="tight")
Example #30
0
def scan_log_limited(taskid, start, end):
    """
    Retrieve a subset of log messages
    """
    global db
    global tasks
    json_log_messages = list()

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    if not start.isdigit() or not end.isdigit() or end < start:
        abort(500, "Invalid start or end value, must be digits")

    start = max(1, int(start))
    end = max(1, int(end))

    # Read a subset of log messages from the IPC database
    for time_, level, message in db.execute(
        "SELECT time, level, message FROM logs WHERE taskid = ? AND id >= ? AND id <= ? ORDER BY id ASC",
        (taskid, start, end),
    ):
        json_log_messages.append({"time": time_, "level": level, "message": message})

    logger.debug("Retrieved subset of log messages for scan for task ID %s" % taskid)
    return jsonize({"log": json_log_messages})