Example #1
0
	def slider_dialog(self, title, minimum = 0, maximum = 100, step = 1, big_step = 10, align = 'left', value = 0, char = "*", fill_char = "-", style = 'slider', onchange = None, onchange_args = (), onchange_kwargs = {}):
		assert value >= minimum
		assert value <= maximum
		done = False
		while not done:
			title = self._align(title, align)
			slider_row = self.format_slider(minimum, maximum, value, align = align, char = char, fill_char = fill_char, style = style)
			self.update((title, slider_row))
			self.redraw()
			key = None
			while key is None:
				key = self.input.read_key()
			if key == self.KEY_LEFT:
				value = max(value - step, minimum)
			elif key == self.KEY_RIGHT:
				value = min(value + step, maximum)
			elif key == self.KEY_UP:
				value = min(value + big_step, maximum)
			elif key == self.KEY_DOWN:
				value = max(value - big_step, minimum)
			elif key == self.KEY_ENTER:
				done = True
			if onchange:
				try:
					onchange(value, *onchange_args, **onchange_kwargs)
				except:
					warnings.warn("On-Change function of slider element failed", RuntimeWarning)
		return value
Example #2
0
    def updateValue(self, delta_x, delta_y):
        newTs = self.tsStart + Zoomable.pixelToNs(delta_x)
        newValue = self.valueStart - (delta_y / EXPANDED_SIZE)

        # Don't overlap first and last keyframes.
        newTs = min(max(newTs, self.inpoint + 1),
                    self.duration + self.inpoint - 1)

        newValue = min(max(newValue, 0.0), 1.0)

        if not self.has_changeable_time:
            newTs = self.lastTs

        updating = self.timelineElement.updating_keyframes
        self.timelineElement.updating_keyframes = True
        self.timelineElement.source.unset(self.lastTs)
        if (self.timelineElement.source.set(newTs, newValue)):
            self.value = Gst.TimedValue()
            self.value.timestamp = newTs
            self.value.value = newValue
            self.lastTs = newTs

            self.timelineElement.setKeyframePosition(self, self.value)
            # Resort the keyframes list each time. Should be cheap as there should never be too much keyframes,
            # if optimization is needed, check if resorting is needed, should
            # not be in 99 % of the cases.
            self.timelineElement.keyframes = sorted(
                self.timelineElement.keyframes, key=lambda keyframe: keyframe.value.timestamp)
            self.timelineElement.drawLines(self.line)
            # This will update the viewer. nifty.
            if not self.line:
                self.timelineElement.timeline._container.seekInPosition(
                    newTs + self.start)

        self.timelineElement.updating_keyframes = updating
Example #3
0
def offset_slice(pixels1, pixels2, i, j):
    '''Return two sliced arrays where the first slice is offset by i,j
    relative to the second slice.
    
    '''
    if i < 0:
        height = min(pixels1.shape[0] + i, pixels2.shape[0])
        p1_imin = -i
        p2_imin = 0
    else:
        height = min(pixels1.shape[0], pixels2.shape[0] - i)
        p1_imin = 0
        p2_imin = i
    p1_imax = p1_imin + height
    p2_imax = p2_imin + height
    if j < 0:
        width = min(pixels1.shape[1] + j, pixels2.shape[1])
        p1_jmin = -j
        p2_jmin = 0
    else:
        width = min(pixels1.shape[1], pixels2.shape[1] - j)
        p1_jmin = 0
        p2_jmin = j
    p1_jmax = p1_jmin + width
    p2_jmax = p2_jmin + width
    
    p1 = pixels1[p1_imin:p1_imax,p1_jmin:p1_jmax]
    p2 = pixels2[p2_imin:p2_imax,p2_jmin:p2_jmax]
    return (p1,p2)
def get_probability(xyz1s,xyz2s,sigma1s,sigma2s,psis,length,slope):
    onemprob = 1.0

    for n in range(len(xyz1s)):
        xyz1=xyz1s[n]
        xyz2=xyz2s[n]
        sigma1=sigma1s[n]
        sigma2=sigma2s[n]
        psi = psis[n]
        psi = psi.get_scale()
        dist=IMP.core.get_distance(xyz1, xyz2)

        sigmai = sigma1.get_scale()
        sigmaj = sigma2.get_scale()
        voli = 4.0 / 3.0 * pi * sigmai * sigmai * sigmai
        volj = 4.0 / 3.0 * pi * sigmaj * sigmaj * sigmaj
        fi = 0
        fj = 0
        if dist < sigmai + sigmaj :
            xlvol = 4.0 / 3.0 * pi * (length / 2) * (length / 2) * \
                           (length / 2)
            fi = min(voli, xlvol)
            fj = min(volj, xlvol)
        else:
            di = dist - sigmaj - length / 2
            dj = dist - sigmai - length / 2
            fi = sphere_cap(sigmai, length / 2, abs(di))
            fj = sphere_cap(sigmaj, length / 2, abs(dj))
        pofr = fi * fj / voli / volj

        factor = (1.0 - (psi * (1.0 - pofr) + pofr * (1 - psi))*exp(-slope*dist))
        onemprob = onemprob * factor
    prob = 1.0 - onemprob
    return prob
Example #5
0
def save_level_costs(level, costs, filename='distance_map.csv'):
    """ Displays cell costs from an origin point over the given level.

    Args:
        level: The level to be displayed.
        costs: A dictionary containing a mapping of cells to costs from an origin point.
        filename: The name of the csv file to be created.

    """
    xs, ys = zip(*(list(level['spaces'].keys()) + list(level['walls'])))
    x_lo, x_hi = min(xs), max(xs)
    y_lo, y_hi = min(ys), max(ys)

    rows = []
    for j in range(y_lo, y_hi + 1):
        row = []

        for i in range(x_lo, x_hi + 1):
            cell = (i, j)
            if cell not in costs:
                row.append(inf)
            else:
                row.append(costs[cell])

        rows.append(row)

    assert '.csv' in filename, 'Error: filename does not contain file type.'
    with open(filename, 'w', newline='') as f:
        csv_writer = writer(f)
        for row in rows:
            csv_writer.writerow(row)
            
    
    print("Saved file:", filename)
    def plotResult(self, nn):
        cmask = np.where(self.y==1);
        plot(self.X[cmask,0], self.X[cmask,1], 'or', markersize=4)
        cmask = np.where(self.y==2);
        plot(self.X[cmask,0], self.X[cmask,1], 'ob', markersize=4)
        cmask = np.where(self.y==3);
        plot(self.X[cmask,0], self.X[cmask,1], 'og', markersize=4)

        minX = min(self.X[:,0])
        minY = min(self.X[:,1])
        maxX = max(self.X[:,0])
        maxY = max(self.X[:,1])

        grid_range = [minX, maxX, minY, maxY];
        delta = 0.05; levels = 100
        a = arange(grid_range[0],grid_range[1],delta)
        b = arange(grid_range[2],grid_range[3],delta)
        A, B = meshgrid(a, b)
        values = np.zeros(A.shape)

        for i in range(len(a)):
            for j in range(len(b)):
                values[j,i] = nn.getNetworkOutput( [ a[i], b[j] ] )
        contour(A, B, values, levels=[1], colors=['k'], linestyles='dashed')
        contourf(A, B, values, levels=linspace(values.min(),values.max(),levels), cmap=cm.RdBu)
Example #7
0
def cost_config(pos_,Qnet,Pnet,counts):
    p_wind=pos_[0]*WINDS_PRICE_DEVICE
    p_pv=pos_[1]*PV_PRICE_BAT1
    counts.append(int(max(Pnet)))
    counts.append(abs(int(min(Pnet))))
    Qmin=min(Qnet)
    print 'Qmin:%f   '%Qmin
    Qmax=max(max(Qnet),abs(min(Qnet)))
    Pmax=max(max(Pnet),abs(min(Pnet)))
    maxVol=recyclemodule.tank_svgas(recyclemodule.ele_mkgas(Qmax))
    max_tank_Volumn.append(abs(maxVol)) 
    print 'maxVol :%f'%maxVol
    counts.append(abs(maxVol/100.0))
    q=(Qmax/BAT_POWER)*BAT_PRICE_DEVICE
    if abs(q)>ELE_PRICE_DEVICE+TANK_PRICE_DEVICE+FC_PRICE_DEVICE:
        p_cycle=ELE_PRICE_DEVICE*counts[0]+TANK_PRICE_DEVICE*counts[2]+FC_PRICE_DEVICE*counts[1]
        counts.append(round(Pmax))            
        p_bat=(Pmax)/BAT_POWER*BAT_PRICE_DEVICE
        #print 'cycle price :%f'%p_cycle
        #print 'bat   price :%f'%p_bat
           
    else:
        counts.append(0.0)
        p_bat=q
        p_cycle=0
        #print 'cycle not use'
        #print q

    print 'ele: %d fc : %d tank : %d bat : %d'%(counts[0],counts[1],counts[2],counts[3])       
    return p_wind+p_pv+p_bat+p_cycle
def cornersHeuristic(state, problem):
    """
    A heuristic for the CornersProblem that you defined.

      state:   The current search state
               (a data structure you chose in your search problem)

      problem: The CornersProblem instance for this layout.

    This function should always return a number that is a lower bound
    on the shortest path from the state to a goal of the problem; i.e.
    it should be admissible (as well as consistent).
    """
    corners = problem.corners # These are the corner coordinates
    walls = problem.walls # These are the walls of the maze, as a Grid (game.py)
    "*** YOUR CODE HERE ***"
    
    currentPosition = state[0]
    unvisitedCorners = []
    distance = 0

    for corner in corners:
        if corner not in state[1]:
            unvisitedCorners.append(corner)

    while unvisitedCorners:
        unvisitedCornersDistance = {}
        for corner in unvisitedCorners:
            subdistance = util.manhattanDistance(currentPosition, corner)
            unvisitedCornersDistance[corner] = subdistance
        distance += min(unvisitedCornersDistance.values())
        currentPosition = min(unvisitedCornersDistance)
        unvisitedCorners.remove( min(unvisitedCornersDistance) )

    return distance
Example #9
0
    def run_periodic_tasks(self, context, raise_on_error=False):
        """Tasks to be run at a periodic interval."""
        idle_for = DEFAULT_INTERVAL
        for task_name, task in self._periodic_tasks:
            full_task_name = '.'.join([self.__class__.__name__, task_name])

            spacing = self._periodic_spacing[task_name]
            last_run = self._periodic_last_run[task_name]

            # Check if due, if not skip
            idle_for = min(idle_for, spacing)
            if last_run is not None:
                delta = last_run + spacing - time.time()
                if delta > 0:
                    idle_for = min(idle_for, delta)
                    continue

            LOG.debug("Running periodic task %(full_task_name)s",
                      {"full_task_name": full_task_name})
            self._periodic_last_run[task_name] = _nearest_boundary(
                last_run, spacing)

            try:
                task(self, context)
            except Exception as e:
                if raise_on_error:
                    raise
                LOG.exception(_LE("Error during %(full_task_name)s: %(e)s"),
                              {"full_task_name": full_task_name, "e": e})
            time.sleep(0)

        return idle_for
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 #11
0
    def perform(self, node, inputs, output_storage):
        a = inputs[0].copy()
        val = inputs[1]
        offset = inputs[2]
        height, width = a.shape

        """
        Notes
        -----
        The fill_diagonal only support rectangular matrix. The output
        of tall matrix is "wrapped", which is an option in numpy 1.9.0
        but was regarded as a bug in numpy 1.6.2. Here I implement the
        fill_diagonal_offset with unwrapped output, so fill_diagonal_offset
        supports tall matrix.(This make a little difference between the output
        of fill_diagonal and fill_diagonal_offset only in the case of tall
        matrix)

        """
        if offset >= 0:
            start = offset
            num_of_step = min(min(width, height), width - offset)
        else:
            start = - offset * a.shape[1]
            num_of_step = min(min(width, height), height + offset)
        step = a.shape[1] + 1
        end = start + step * num_of_step
        # Write the value out into the diagonal.
        a.flat[start:end:step] = val

        output_storage[0][0] = a
Example #12
0
def query_fits_map(header, data, x_deg, y_deg, doStrip=True, doApp=False,
                   r_deg=10.0/60.0):
    """Query the value in a 2D FITS map at a given coordinate in deg"""

    dataValue = None
    
    # Strip unused dimensions from the array
    if doStrip:
        data, header = strip_fits_dims(data, header, 2, 5)
    
    # Extract the data
    try:
        w = mkWCSDict(header)
        wcs = pw.WCS(w['header2D'])
        [[x_pix, y_pix]] =  wcs.wcs_world2pix([(x_deg, y_deg)], 0)
        dataValue = data[int(round(y_pix)), int(round(x_pix))]
        r_pix = r_deg / w['pixscale']
        if doApp:
            xMax_pix = min(int(round(x_pix + r_pix)), w['xnaxis'])
            xMin_pix = max(int(round(x_pix - r_pix)), 0)
            yMax_pix = min(int(round(y_pix + r_pix)), w['ynaxis'])
            yMin_pix = max(int(round(y_pix - r_pix)), 0)        
            dataSub = data[yMin_pix:yMax_pix, xMin_pix:xMax_pix ]
            ms = calc_stats(dataSub)
        
    except Exception:
        print "Fail query FITS pixel."

    if doApp:
        return dataValue, ms
    else:        
        return dataValue
Example #13
0
 def visit(v):
     "Mark a state as visited"
     call_stack = [(1, v, graph.getrow(v).nonzero()[1], None)]
     while call_stack:
         tovisit, v, iterator, w = call_stack.pop()
         if tovisit:
             NodeVisited[v] = True
             nodes_visit_order.append(v)
             NodeNums[v] = graph.next_visit_num
             graph.next_visit_num += 1
             stack.append(v)
         if w and not NodeInComponent[v]:
             NodeRoots[v] = nodes_visit_order[min(NodeNums[NodeRoots[v]],
                                                  NodeNums[NodeRoots[w]])]
         cont = 0
         for w in iterator:
             if not NodeVisited[w]:
                 cont = 1
                 call_stack.append((0, v, iterator, w))
                 call_stack.append((1, w, graph.getrow(w).nonzero()[1], None))
                 break
             if not NodeInComponent[w]:
                 NodeRoots[v] = nodes_visit_order[min(NodeNums[NodeRoots[v]],
                                                      NodeNums[NodeRoots[w]])]
         if cont:
             continue
         if NodeRoots[v] == v:
             c = []
             while 1:
                 w = stack.pop()
                 NodeInComponent[w] = c
                 c.append(w)
                 if w == v:
                     break
             components.append(c)
 def minValue(gameState, depth, agentIndex, numGhosts, alpha, beta):
     assert agentIndex > 0, "Pacman uses minValue function. BAD!!!"
     assert depth > 0, "Ghost shouldn't be the terminal agent."
     legalMoves = gameState.getLegalActions(agentIndex)
     # if no legal moves
     if len(legalMoves) == 0:
         return self.evaluationFunction(gameState)
     else:
         v = float("infinity")
         # the last ghost
         if agentIndex == numGhosts:
             for action in legalMoves:
                 v = min(v, maxValue(gameState.generateSuccessor(agentIndex, action), depth-1, 0,
                                     numGhosts, alpha, beta))
                 if v < alpha:
                     return v
                 beta = min(beta, v)
         else:
             for action in legalMoves:
                 v = min(v, minValue(gameState.generateSuccessor(agentIndex, action), depth, agentIndex+1,
                                     numGhosts, alpha, beta))
                 if v < alpha:
                     return v
                 beta = min(beta, v)
         return v
def getPartInfo( part ):
        points = part['points']
        n = len(points)
        area = cx = cy = 0
        xmin = ymin = 360
        xmax = ymax = -360
        pt = points[n-1];  xx = pt[0];  yy = pt[1]
        for pt in points:
                x = pt[0];  y = pt[1]
                # bounds
                xmin = min( x, xmin );  ymin = min( y, ymin )
                xmax = max( x, xmax );  ymax = max( y, ymax )
                # area and centroid
                a = xx * y - x * yy
                area += a
                cx += ( x + xx ) * a
                cy += ( y + yy ) * a
                # next
                xx = x;  yy = y
        area /= 2
        if area:
                centroid = [ cx / area / 6, cy / area / 6 ]
        else:
                centroid = None
        part.update({
                'area': abs(area),
                'bounds': [ [ xmin, ymin ], [ xmax, ymax ] ],
                'center': [ ( xmin + xmax ) / 2, ( ymin + ymax ) / 2 ],
                'centroid': centroid,
                'extent': [ abs( xmax - xmin ), abs( ymax - ymin ) ]
        })
Example #16
0
    def update(self, iterations=10):

        """ Iterates the graph layout and updates node positions.
        """

        # The graph fades in when initially constructed.
        self.alpha += 0.05
        self.alpha = min(self.alpha, 1.0)

        # Iterates over the graph's layout.
        # Each step the graph's bounds are recalculated
        # and a number of iterations are processed,
        # more and more as the layout progresses.
        if self.layout.i == 0:
            self.layout.prepare()
            self.layout.i += 1
        elif self.layout.i == 1:
            self.layout.iterate()
        elif self.layout.i < self.layout.n:
            n = min(iterations, self.layout.i / 10 + 1)
            for i in range(n):
                self.layout.iterate()

        # Calculate the absolute center of the graph.
        min_, max = self.layout.bounds
        print "w/h", _ctx #, _ctx.WIDTH, _ctx.HEIGHT
        self.x = _ctx.WIDTH - max.x*self.d - min_.x*self.d
        self.y = _ctx.HEIGHT - max.y*self.d - min_.y*self.d
        self.x /= 2
        self.y /= 2

        return not self.layout.done
Example #17
0
    def onMouse( self, event, x, y, flags, param ):
        """
        Mouse interactions with Main window:
            - Left mouse click gives pixel data under cursor
            - Left mouse drag selects rectangle

            - Right mouse button switches view mode
        """
        if event == cv2.EVENT_LBUTTONDOWN:
            if not self.gui_frame == None:
                self.drag_start = (x, y)

        if event == cv2.EVENT_LBUTTONUP:
                self.drag_start = None

                if self.selection == None:
                    pixel = self.gui_frame[y, x]
                    print "[X,Y][B G R](H, S, V):", [x, y], pixel, utils.BGRpix2HSV(pixel)
                else:
                    #self.track_window = self.selection
                    print self.selection    #self.track_window

        if self.drag_start:
            xmin = min( x, self.drag_start[0] )
            ymin = min( y, self.drag_start[1] )
            xmax = max( x, self.drag_start[0] )
            ymax = max( y, self.drag_start[1] )

            if xmax - xmin < 2 and ymax - ymin < 2:
                self.selection = None
            else:
                self.selection = ( xmin, ymin, xmax - xmin, ymax - ymin )

        if event == cv2.EVENT_RBUTTONDOWN:
            pass
Example #18
0
    def _get_icon_rect(self, opt, text_rect):
        """Get a QRect for the icon to draw.

        Args:
            opt: QStyleOptionTab
            text_rect: The QRect for the text.

        Return:
            A QRect.
        """
        icon_size = opt.iconSize
        if not icon_size.isValid():
            icon_extent = self.pixelMetric(QStyle.PM_SmallIconSize)
            icon_size = QSize(icon_extent, icon_extent)
        icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled
                     else QIcon.Disabled)
        icon_state = (QIcon.On if opt.state & QStyle.State_Selected
                      else QIcon.Off)
        # reserve space for favicon when tab bar is vertical (issue #1968)
        position = config.val.tabs.position
        if (position in [QTabWidget.East, QTabWidget.West] and
                config.val.tabs.favicons.show):
            tab_icon_size = icon_size
        else:
            actual_size = opt.icon.actualSize(icon_size, icon_mode, icon_state)
            tab_icon_size = QSize(
                min(actual_size.width(), icon_size.width()),
                min(actual_size.height(), icon_size.height()))

        icon_top = text_rect.center().y() + 1 - tab_icon_size.height() / 2
        icon_rect = QRect(QPoint(text_rect.left(), icon_top), tab_icon_size)
        icon_rect = self._style.visualRect(opt.direction, opt.rect, icon_rect)
        return icon_rect
Example #19
0
def dameraulevenshtein(seq1, seq2):
    """
    Calculate the Damerau-Levenshtein distance between sequences.

    codesnippet:D0DE4716-B6E6-4161-9219-2903BF8F547F
    Conceptually, this is based on a len(seq1) + 1 * len(seq2) + 1
    matrix. However, only the current and two previous rows are
    needed at once, so we only store those.

    Same code as word-level checking.
    """

    oneago = None
    thisrow = range(1, len(seq2) + 1) + [0]

    for x in xrange(len(seq1)):

        twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1]

        for y in xrange(len(seq2)):
            delcost = oneago[y] + 1
            addcost = thisrow[y - 1] + 1
            subcost = oneago[y - 1] + (seq1[x] != seq2[y])
            thisrow[y] = min(delcost, addcost, subcost)

            if x > 0 and y > 0 and seq1[x] == seq2[y - 1] and seq1[x - 1] == seq2[y] and seq1[x] != seq2[y]:
                thisrow[y] = min(thisrow[y], twoago[y - 2] + 1)

    return thisrow[len(seq2) - 1]
Example #20
0
def compare_chebhist(dname, mylambda, c, Nbin = 25):


    if mylambda == 'Do not exist':
        print('--!!Warning: eig file does not exist, can not display compare histgram')
    else:
        mylambda = 1 - mylambda
        lmin = max(min(mylambda), -1)
        lmax = min(max(mylambda),  1)

        # print c
        cheb_file_content = '\n'.join([str(st) for st in c])
        x = np.linspace(lmin, lmax, Nbin + 1)
        y = plot_chebint(c, x)
        u = (x[1:] + x[:-1]) / 2
        v =  y[1:] - y[:-1]

        plt.clf()
        plt.hold(True)
        plt.hist(mylambda,Nbin)
        plt.plot(u, v, "r.", markersize=10)
        plt.hold(False)
        plt.show()
        filename = 'data/' + dname + '.png'
        plt.savefig(filename)

        cheb_filename = 'data/' + dname + '.cheb'
        f = open(cheb_filename, 'w+')
        f.write(cheb_file_content)
        f.close()
Example #21
0
    def _label_iterations(self, lod):
        stroke_gradient = self.get_stroke_gradient()
        if lod == LOD.FULL and \
           self.get_style() != "flat" and stroke_gradient:
            root = self.get_layout_root()
            d = 0.4  # fake-emboss distance
            #d = max(src_size[1] * 0.02, 0.0)
            max_offset = 2

            alpha = self.get_gradient_angle()
            xo = root.context.scale_log_to_canvas_x(d * cos(alpha))
            yo = root.context.scale_log_to_canvas_y(d * sin(alpha))
            xo = min(int(round(xo)), max_offset)
            yo = min(int(round(yo)), max_offset)

            luminosity_factor = stroke_gradient * 0.25

            # shadow
            yield xo, yo, -luminosity_factor, False

            # highlight
            yield -xo, -yo, luminosity_factor, False

        # normal
        yield 0, 0, 0, True
Example #22
0
def fit_CSU_edges(profile):
    fitter = fitting.LevMarLSQFitter()

    amp1_est = profile[profile == min(profile)][0]
    mean1_est = np.argmin(profile)
    amp2_est = profile[profile == max(profile)][0]
    mean2_est = np.argmax(profile)
    
    g_init1 = models.Gaussian1D(amplitude=amp1_est, mean=mean1_est, stddev=2.)
    g_init1.amplitude.max = 0
    g_init1.amplitude.min = amp1_est*0.9
    g_init1.stddev.max = 3
    g_init2 = models.Gaussian1D(amplitude=amp2_est, mean=mean2_est, stddev=2.)
    g_init2.amplitude.min = 0
    g_init2.amplitude.min = amp2_est*0.9
    g_init2.stddev.max = 3

    model = g_init1 + g_init2
    fit = fitter(model, range(0,profile.shape[0]), profile)
    
    # Check Validity of Fit
    if abs(fit.stddev_0.value) <= 3 and abs(fit.stddev_1.value) <= 3\
       and fit.amplitude_0.value < -1 and fit.amplitude_1.value > 1\
       and fit.mean_0.value > fit.mean_1.value:
        x = [fit.mean_0.value, fit.mean_1.value]
        x1 = int(np.floor(min(x)-1))
        x2 = int(np.ceil(max(x)+1))
    else:
        x1 = None
        x2 = None

    return x1, x2
Example #23
0
def show_level(level, path=[]):
    """ Displays a level via a print statement.

    Args:
        level: The level to be displayed.
        path: A continuous path to be displayed over the level, if provided.

    """
    xs, ys = zip(*(list(level['spaces'].keys()) + list(level['walls'])))
    x_lo, x_hi = min(xs), max(xs)
    y_lo, y_hi = min(ys), max(ys)

    path_cells = set(path)

    chars = []
    inverted_waypoints = {point: char for char, point in level['waypoints'].items()}

    for j in range(y_lo, y_hi + 1):
        for i in range(x_lo, x_hi + 1):

            cell = (i, j)
            if cell in path_cells:
                chars.append('*')
            elif cell in level['walls']:
                chars.append('X')
            elif cell in inverted_waypoints:
                chars.append(inverted_waypoints[cell])
            elif cell in level['spaces']:
                chars.append(str(int(level['spaces'][cell])))
            else:
                chars.append(' ')

        chars.append('\n')

    print(''.join(chars))
Example #24
0
    def getPixelData(self, event):
        global data

        x = event.pos().x()
        y = event.pos().y()
        self.area.append([x, y])

        value = qRgb(flag[self.color][0], flag[self.color][1], flag[self.color][2])

        # if there's 2 points, then add the whole zone to the data
        if len(self.area) == 2:
            xi = min(self.area[0][0], self.area[1][0] + 1)
            xf = max(self.area[0][0], self.area[1][0] + 1)
            yi = min(self.area[0][1], self.area[1][1] + 1)
            yf = max(self.area[0][1], self.area[1][1] + 1)

            print('zone [' + str(xi) + ',' + str(yi) + '][' + str(xf) + ',' + str(yf) + ']  => ' + self.color)

            for i in range(xi, xf):
                for j in range(yi, yf):
                    rgb = QColor(self.image.pixel(i, j)).toRgb()
                    r = rgb.red()
                    g = rgb.green()
                    b = rgb.blue()
                    data[self.color].append([i, j, r, g, b])

                    self.image.setPixel(i, j, value)

            # update image to show the already selected pixels
            self.label.setPixmap(QPixmap.fromImage(self.image))
            # reset list with the zone limits
            self.area = []
Example #25
0
 def evaluate(self,  u):
 
     eps = 1e-10
     
     if u<min(self.knots)+eps:
         u = min(self.knots)+eps
         
     if u>=max(self.knots)-eps:
         u=max(self.knots)-eps
         
     # scale
     weighted_pts = [vscale(pt[0:-1],pt[-1])+[pt[-1]] for pt in self.pts]
     
             
     pts = []
     for i in range(len(self.pts)):
         pts.append(vscale(weighted_pts[i], self.N(i, self.order, u)))
         
     eval_pt = reduce(vadd, pts)
     
     
     # unscale
     if eval_pt[-1]!=0:
         unweighted_pt = vscale(eval_pt[0:-1], 1.0/eval_pt[-1]) 
     else:
         unweighted_pt = eval_pt[0:-1]
         
     
     return unweighted_pt
Example #26
0
    def get_box_intersection(self, bounding_region):
        """
        Given a bounding_region object computes and returns a new BoundingRegion that
        corresponds to the intersection of the bounding box of the current object with the
        box of the region given as argument. Retuns an empty BoundingRegion if the interseciton
        is empty.

        :param bounding_region: A BoundingRegion object to compute intersection with
        :type bounding_region: BoundingRegion
        :return: Bounding region of the intersection of the boxes
        :rtype: BoundingRegion
        """
        x1_1 = self.box[0]
        y1_1 = self.box[1]
        x1_2 = self.box[0] + self.box[2]
        y1_2 = self.box[1] + self.box[3]
        box2 = bounding_region.get_box_pixels()
        x2_1 = box2[0]
        y2_1 = box2[1]
        x2_2 = box2[0] + box2[2]
        y2_2 = box2[1] + box2[3]

        x3_1 = max(x1_1, x2_1)
        y3_1 = max(y1_1, y2_1)
        width = max(-1, min(x1_2, x2_2) - x3_1)
        height = max(-1, min(y1_2, y2_2) - y3_1)
        if width * height >= 0:
            return BoundingRegion(image_shape=self.image_shape, box=(x3_1, y3_1, width, height))
        else:
            return BoundingRegion()
Example #27
0
def plot_cache(data_match):
    
    data_list = glob.glob(data_match+"*")

    master_list = []

    for data_file in data_list:

        data = performance.load_score_dict(data_file)
    
        total = 0
        cum_list = []
        for entry in data:
            total += (entry)
            cum_list.append(entry)
            
        master_list.append(cum_list)

        print len(cum_list)

    avg_list = []
    std_list = []

    cum_len = min([len(x) for x in master_list])
    cum_len = min(200, cum_len)
    

    for i in range(cum_len):
        avg_list.append(np.mean([x[i] for x in master_list]))
        std_list.append(np.std([x[i] for x in master_list]))
    print avg_list

    plotting.query_cache(avg_list, std_list) 
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 propagateConstraints_int(x, y):
                if x is None or y is None:
                    return None, None
                x1, x2, y1, y2 = x.min, x.max, y.min, y.max
                if cmp_t == 'ge' or cmp_t == 'gt':
                    x1, x2, y1, y2 = y1, y2, x1, x2 

                #treat greater like less than swap before and afterwards
                if cmp_t == 'lt' or cmp_t == 'gt':
                    x2 = min(x2, y2-1)
                    y1 = max(x1+1, y1)
                elif cmp_t == 'le' or cmp_t == 'ge':
                    x2 = min(x2, y2)
                    y1 = max(x1, y1)
                elif cmp_t == 'eq':
                    x1 = y1 = max(x1, y1)
                    x2 = y2 = min(x2, y2)
                elif cmp_t == 'ne':
                    if x1 == x2 == y1 == y2:
                        return None, None
                    if x1 == x2:
                        y1 = y1 if y1 != x1 else y1+1
                        y2 = y2 if y2 != x2 else y2-1               
                    if y1 == y2:
                        x1 = x1 if x1 != y1 else x1+1
                        x2 = x2 if x2 != y2 else x2-1

                if cmp_t == 'ge' or cmp_t == 'gt':
                    x1, x2, y1, y2 = y1, y2, x1, x2 
                con1 = IntConstraint.range(x.width, x1, x2) if x1 <= x2 else None   
                con2 = IntConstraint.range(y.width, y1, y2) if y1 <= y2 else None   
                return con1, con2
Example #30
0
def training_stage3(dftrain,dfvalid,cat1,i):
    fname = ddir + 'joblib/stage3_'+str(cat1)+ext
    df = dftrain[dftrain.Categorie1 == cat1].reset_index(drop=True)
    dfv = dfvalid[dfvalid.Categorie1 == cat1].reset_index(drop=True)
    labels = np.unique(df.Categorie3)
    if len(labels)==1:
        joblib.dump((labels,None,None),fname)
        scv = -1
        sct = -1
        print 'training',cat1,'\t\t(',i,') : N=',len(df),'K=',len(labels)
        print 'training',cat1,'\t\t(',i,') : training=',sct,'validation=',scv
        return (sct,scv)
    vec,X = vectorizer_stage3(df.txt)
    Y = df['Categorie3'].values
    cla = LogisticRegression(C=best_regularisation.get(cat1,100))
    cla.fit(X,Y)
    labels = np.unique(df.Categorie3)
    sct = cla.score(X[:min(10000,len(df))],Y[:min(10000,len(df))])
    if len(dfv)==0:
        scv = -1
    else:
        Xv = vec.transform(dfv.txt)
        Yv = dfv['Categorie3'].values
        scv = cla.score(Xv,Yv)
    print 'training',cat1,'\t\t(',i,') : N=',len(df),'K=',len(labels)
    print 'training',cat1,'\t\t(',i,') : training=',sct,'validation=',scv
    joblib.dump((labels,vec,cla),fname)
    del vec,cla
    return (sct,scv)