Example #1
0
 def __eq__(self, rhs):
     #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
     return (
             abs(self.x-rhs.x)<11e-3
             and abs(self.y-rhs.y)<11e-3
             and abs(self.z-rhs.z)<11e-3
             )
 def getDist(self):
     mainCharX = self.mainChar.getPos().x
     mainCharY = self.mainChar.getPos().y
     pandaX = self.pandaActor2.getPos().x
     pandaY = self.pandaActor2.getPos().y
     dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2)
     return dist
Example #3
0
    def get_ruler_distances(self, x1, y1, x2, y2):
        mode = self.t_drawparams.get('units', 'arcmin')
        try:
            image = self.fitsimage.get_image()
            if mode == 'arcmin':
                # Calculate RA and DEC for the three points
                # origination point
                ra_org, dec_org = image.pixtoradec(x1, y1)

                # destination point
                ra_dst, dec_dst = image.pixtoradec(x2, y2)

                # "heel" point making a right triangle
                ra_heel, dec_heel = image.pixtoradec(x2, y1)

                text_h = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_dst, dec_dst)
                text_x = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_heel, dec_heel)
                text_y = image.get_starsep_RaDecDeg(ra_heel, dec_heel, ra_dst, dec_dst)
            else:
                dx = abs(x2 - x1)
                dy = abs(y2 - y1)
                dh = math.sqrt(dx**2 + dy**2)
                text_x = str(dx)
                text_y = str(dy)
                text_h = ("%.3f" % dh)
                
        except Exception, e:
            text_h = 'BAD WCS'
            text_x = 'BAD WCS'
            text_y = 'BAD WCS'
Example #4
0
def test_scal(vector_array):
    v = vector_array
    for ind in valid_inds(v):
        if v.len_ind(ind) != v.len_ind_unique(ind):
            with pytest.raises(Exception):
                c = v.copy()
                c[ind].scal(1.)
            continue
        ind_complement_ = ind_complement(v, ind)
        c = v.copy()
        c[ind].scal(1.)
        assert len(c) == len(v)
        assert np.all(almost_equal(c, v))

        c = v.copy()
        c[ind].scal(0.)
        assert np.all(almost_equal(c[ind], v.zeros(v.len_ind(ind))))
        assert np.all(almost_equal(c[ind_complement_], v[ind_complement_]))

        for x in (1., 1.4, np.random.random(v.len_ind(ind))):
            c = v.copy()
            c[ind].scal(x)
            assert np.all(almost_equal(c[ind_complement_], v[ind_complement_]))
            assert np.allclose(c[ind].sup_norm(), v[ind].sup_norm() * abs(x))
            assert np.allclose(c[ind].l2_norm(), v[ind].l2_norm() * abs(x))
            if hasattr(v, 'data'):
                y = v.data.copy()
                if NUMPY_INDEX_QUIRK and len(y) == 0:
                    pass
                else:
                    if isinstance(x, np.ndarray) and not isinstance(ind, Number):
                        x = x[:, np.newaxis]
                    y[ind] *= x
                assert np.allclose(c.data, y)
Example #5
0
    def defaultGait(self,leg):        
        # just walk forward for now
        travelX = 50
        travelY = 0
        travelRotZ = 0

        if abs(travelX)>5 or abs(travelY)>5 or abs(travelRotZ) > 0.05:   # are we moving?
            if(self.order[leg] == self.step):
                # up, middle position                    
                self[leg][0] = 0        # x
                self[leg][1] = 0        # y
                self[leg][2] = -20      # z
                self[leg][3] = 0        # r
            elif (self.order[leg]+1 == self.step) or (self.order[leg]-7 == self.step):   # gaits in step -1 
                # leg down!                    
                self[leg][0] = travelX/2
                self[leg][1] = travelY/2
                self[leg][2] = 0       
                self[leg][3] = travelRotZ/2      
            else:
                # move body forward 
                self[leg][0] = self[leg][0] - travelX/6
                self[leg][1] = self[leg][1] - travelY/6
                self[leg][2] = 0       
                self[leg][3] = self[leg][3] - travelRotZ/6    
        return self[leg]
Example #6
0
def demoNoiseWS(iteration=11):
    print("reading image...")
    image = readImage('../samples/monsters.png', grayScale=True)
    adj4 = AdjacencyNdRegular.getAdjacency2d4(image.embedding.size)
    image = rescaleGray(image, 0, 1)
    convolve = False
    noiseInImage = True
    sal0 = None
    for i in range(iteration):
        print("-> Iteration " + str(i))
        print("Constructing gradient graph...")
        if noiseInImage:
            im2 = imageMap(image, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=False)
            adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(im2[i] - im2[j]))
        else:
            adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(image[i] - image[j]))
            adjacency = imageMap(adjacency, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=True)


        print("Constructing area watershed...")
        # wsh = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(adjacency))
        # addAttributeArea(wsh)
        # wsha= transformBPTtoAttributeHierarchy(wsh,"area")
        wsha = constructExactRandomSeedsWatershed(adjacency)
        sal = computeSaliencyMapFromAttribute(wsha, adj4)

        print("Averaging and Drawing saliency...")
        if convolve:
            lineGraph = WeightedAdjacency.createLineGraph(sal)
            adjLineGraph = WeightedAdjacency.createReflexiveRelation(lineGraph)
            meanSal = spatialFilter(sal, adjLineGraph, BasicAccumulator.getMeanAccumulator())
        else:
            meanSal = sal

        saveImage(normalizeToByte(
            imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, meanSal), 0, 1), lambda x: x ** 0.33333)),
            "Results/Random noise gradient " + str(i) + ".png")
        if sal0 is None:
            sal0 = meanSal
            for j in range(len(sal0)):
                sal0[j] = [sal0[j]]
        else:
            for j in range(len(sal0)):
                sal0[j].append(meanSal[j])
    print("Merging results...")

    for i in range(len(sal0)):
        sal0[i] = meanV(sal0[i])

    saveImage(normalizeToByte(
        imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, sal0), 0, 1), lambda x: x ** 0.33333)),
        "Results/Random noise combined gradient.png")

    print("Ultra metric opening...")
    bpt = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(sal0))
    addAttributeArea(bpt)

    nbpt = filterBPTbyCriterion(bpt, lambda i: min(bpt.area[bpt.children[i][0]], bpt.area[bpt.children[i][1]]) < 10)
    saveImage(drawSaliencyForVisualisation(bpt, image), "Results/Random noise WS bpt.png")
    saveImage(drawSaliencyForVisualisation(nbpt, image), "Results/Random noise WS filteredbpt.png")
def test():
    '''Test the basic workings of `parse_slice`.'''
    
    r1 = range(5)
    r2 = range(2, 10)
    r3 = range(100, 3, -7)
    ranges = [r1, r2, r3]
    
    slices = [slice(3), slice(5), slice(9), slice(1, 4), slice(4, 7),
              slice(6, 2), slice(1, 4, 1), slice(1, 5, 3), slice(6, 2, 3),
              slice(6, 2, -3),  slice(8, 2, -1), slice(2, 5, -2),
              slice(None, 5, -2), slice(6, None, -2), slice(8, 4, None),
              slice(None, None, -2)]
    
    for slice_ in slices:
        (start, stop, step) = parse_slice(slice_)
        
        # Replacing `infinity` with huge number cause Python's lists can't
        # handle `infinity`:
        if abs(start) == infinity: start = 10**10 * math_tools.get_sign(start)
        if abs(stop) == infinity: stop = 10**10 * math_tools.get_sign(stop)
        if abs(step) == infinity: step = 10**10 * math_tools.get_sign(step)
        #######################################################################
            
        assert [start, stop, step].count(None) == 0
        
        parsed_slice = slice(start, stop, step)
        for range_ in ranges:
            assert range_[slice_] == range_[parsed_slice]
Example #8
0
def mouseInput():    
    
    cont = logic.getCurrentController()
    owner = cont.owner 
    
    centerX = (render.getWindowWidth()//2)/render.getWindowWidth()
    centerY = (render.getWindowHeight()//2)/render.getWindowHeight()
    
    global oldMouseVec
    if oldMouseVec == None:
        oldMouseVec = mathutils.Vector([0.0,0.0])
        logic.mouse.position = (centerX,centerY)
        return mathutils.Vector([0,0])
            
    x = logic.mouse.position[0] - centerX
    if abs(x) < abs(2/render.getWindowWidth()): x = 0
    y = centerY - logic.mouse.position[1]
    if abs(y) < abs(2/render.getWindowWidth()): y = 0
    newMouseVec = mathutils.Vector([x, y])  
    
    global mouseSensitivity 
    
    newMouseVec *= mouseSensitivity
    
    # Smooth movement
    global mouseSmooth
    
    oldMouseVec = oldMouseVec*mouseSmooth + newMouseVec*(1.0-mouseSmooth)
    newMouseVec = oldMouseVec
    
    # Center mouse in game window
    logic.mouse.position = (centerX,centerY)    
    
    return mathutils.Vector(newMouseVec)
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 #10
0
    def to_polynomial(self, c):
        """
        Convert clause to :class:`sage.rings.polynomial.pbori.BooleanPolynomial`

        INPUT:

        - ``c`` - a clause

        EXAMPLE::

            sage: B.<a,b,c> = BooleanPolynomialRing()
            sage: from sage.sat.converters.polybori import CNFEncoder
            sage: from sage.sat.solvers.dimacs import DIMACS
            sage: fn = tmp_filename()
            sage: solver = DIMACS(filename=fn)
            sage: e = CNFEncoder(solver, B, max_vars_sparse=2)
            sage: _ = e([a*b + a + 1, a*b+ a + c])
            sage: e.to_polynomial( (1,-2,3) )
            a*b*c + a*b + b*c + b
        """
        def product(l):
            # order of these multiplications for performance
            res = l[0]
            for p in l[1:]:
                res = res*p
            return res

        phi = self.phi
        product = self.ring(1)
        for v in c:
            if phi[abs(v)] is None:
                raise ValueError("Clause containst an XOR glueing variable.")
            product *= phi[abs(v)] + int(v>0)
        return product
Example #11
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 #12
0
def karatsuba_multiply(x, y):
  if x == 0 or y == 0: return 0
  sign = 1
  if (x < 0 and y > 0) or (x > 0 and y < 0): sign = -1
  x = abs(x)
  y = abs(y)
  max_digit = max(x.bit_length(), y.bit_length())

  if max_digit == 1: return 1

  half_digit = max_digit // 2
  filter_mask = (1 << half_digit) - 1

  x_upper_half = x >> half_digit
  x_lower_half = x & filter_mask
  y_upper_half = y >> half_digit
  y_lower_half = y & filter_mask

  z_0 = karatsuba_multiply(x_lower_half, y_lower_half)
  z_2 = karatsuba_multiply(x_upper_half, y_upper_half)
  z_1 = karatsuba_multiply((x_lower_half + x_upper_half), (y_lower_half + y_upper_half)) - z_0 - z_2

  abs_res = ((z_2  << half_digit << half_digit) +
          (z_1 << half_digit) +
          z_0)
  if sign == -1: return ~abs_res + 1
  else: return abs_res
Example #13
0
    def test_translational_alignment(self):
        """ Test the translational alignment in 2D routine """
        random.seed()
        name=self.get_input_file_name("1z5s-projection-2.spi")
        srw = IMP.em2d.SpiderImageReaderWriter()
        image=IMP.em2d.Image()
        image.read(name,srw)
        translated=IMP.em2d.Image()
        # random translation
        trans=IMP.algebra.Vector2D(random.random()*10,random.random()*10)
        transformation = IMP.algebra.Transformation2D(trans)
        IMP.em2d.get_transformed(image.get_data(),translated.get_data(),
                                 transformation)
        fn_translated = self.get_input_file_name("translated.spi")
#        translated.write(fn_translated,srw)
        result=IMP.em2d.get_translational_alignment(
                image.get_data(),translated.get_data(),True)
        fn_aligned = self.get_input_file_name("trans_aligned.spi")
 #       translated.write(fn_aligned,srw)
        # -1 to get the translation applied to reference.
        # Result contains the translation required for align the second matrix
        determined_trans= (-1)*result[0].get_translation()
        # Tolerate 1 pixel error
        self.assertAlmostEqual(abs(determined_trans[0]-trans[0]),0, delta=1,
                msg="1st coordinate is incorrect: Applied %f Determined %f" \
                    % (trans[0], determined_trans[0]))
        self.assertAlmostEqual(abs(determined_trans[1]-trans[1]),0, delta=1,
                msg="2nd coordinate is incorrect: Applied %f Determined %f" \
                    % (trans[1], determined_trans[1]))
Example #14
0
    def test_rotational_alignment(self):
        """ Test the rotational alignment in 2D routine (new) """
        random.seed()
        name=self.get_input_file_name("1z5s-projection-2.spi")
        srw = IMP.em2d.SpiderImageReaderWriter()
        image=IMP.em2d.Image()
        image.read(name,srw)
        rotated=IMP.em2d.Image()
        # random rotation
        angle=random.random()*2*pi
        rot=IMP.algebra.Rotation2D(angle)
        transformation = IMP.algebra.Transformation2D(rot)
        IMP.em2d.get_transformed(image.get_data(),rotated.get_data(),
                                 transformation)

        fn_rotated = self.get_input_file_name("rotated.spi")
#        rotated.write(fn_rotated,srw)
        result=IMP.em2d.get_rotational_alignment(
                image.get_data(),rotated.get_data(),True)
        fn_aligned = self.get_input_file_name("rot_aligned.spi")
 #       rotated.write(fn_aligned,srw)
        determined_angle=result[0].get_rotation().get_angle()
        # approximately 6 degrees tolerance, 0.1 rad.
        x = angle+determined_angle
        modulo = (abs(x % (2*pi)) < 0.1) or (abs(x % (2*pi)-2*pi) < 0.1)
        self.assertEqual(modulo,True,msg="Angles applied %f and "
          "determined %f are different, difference %f" % (angle
                                                      ,determined_angle,x))
Example #15
0
def G(x, k):
	result = []
	X = np.fft.fft(x, k)
	for i in range(len(X)):
		result.append(1/len(X) * (abs(X[i]) * abs(X[i])))

	return result
Example #16
0
def has_split_dividents(mdata, from_date, to_date):
    ''' Verifies if market data interval has splits, dividends '''
    from_diff = abs(mdata['close'][from_date] - mdata['adj_close'][from_date])
    to_diff = abs(mdata['close'][to_date] - mdata['adj_close'][to_date])
    if approx_equal(from_diff, to_diff, 0.0001):
        return False
    return not percent_equal(from_diff, to_diff, mdata['close'][to_date], 0.8)
Example #17
0
	def addExtrusionIntro( self, line ):
		"Adds the additional linear gcode movement for the extrusion intro."
		splitG1Line = self.firstLinearGcodeMovement.split()
		firstMovementLocation = gcodec.getLocationFromSplitLine(None, splitG1Line)
		firstMovementFeedrate = gcodec.getFeedRateMinute(self.feedRateMinute/self.repository.firstPerimeterFeedrateOverFeedrate.value, splitG1Line)
		introX = abs( self.repository.absMaxXIntro.value )
		introY = abs( self.repository.absMaxYIntro.value )
		xAxisFirst=False
		if abs( firstMovementLocation.x ) < abs( firstMovementLocation.y ):
			xAxisFirst=True	
		if (xAxisFirst and firstMovementLocation.x > 0) or (not xAxisFirst and firstMovementLocation.x < 0):
			introX = -introX;
		if (xAxisFirst and firstMovementLocation.y < 0) or (not xAxisFirst and firstMovementLocation.y > 0):
			introY = -introY;
		introLine = self.deriveIntroLine(self.firstLinearGcodeMovement, splitG1Line, introX, introY, firstMovementFeedrate)
		self.distanceFeedRate.addLine(introLine)
		self.distanceFeedRate.addLine( line )
		if xAxisFirst:
			introLine = self.deriveIntroLine(self.firstLinearGcodeMovement, splitG1Line, firstMovementLocation.x, introY, self.feedRateMinute)
		else:
			introLine = self.deriveIntroLine(self.firstLinearGcodeMovement, splitG1Line, introX, firstMovementLocation.y, self.feedRateMinute)
		self.distanceFeedRate.addLine(introLine)
		introLine = self.getRaftlessSpeededLine(self.firstLinearGcodeMovement, splitG1Line)
		self.distanceFeedRate.addLine(introLine)
		self.wantsExtrusionIntro = False
    def _str(self, i, x):
        """Handles string formatting of cell data

            i - index of the cell datatype in self._dtype 
            x - cell data to format
        """
        try:
            f = float(x)
        except:
            return str(x)

        n = self._precision
        dtype = self._dtype[i]

        if dtype == 'i':
            return str(int(round(f)))
        elif dtype == 'f':
            return '%.*f' % (n, f)
        elif dtype == 'e':
            return '%.*e' % (n, f)
        elif dtype == 't':
            return str(x)
        else:
            if f - round(f) == 0:
                if abs(f) > 1e8:
                    return '%.*e' % (n, f)
                else:
                    return str(int(round(f)))
            else:
                if abs(f) > 1e8:
                    return '%.*e' % (n, f)
                else:
                    return '%.*f' % (n, f)
Example #19
0
 def test_testUfuncs1 (self):
     "Test various functions such as sin, cos."
     (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
     self.assertTrue (eq(numpy.cos(x), cos(xm)))
     self.assertTrue (eq(numpy.cosh(x), cosh(xm)))
     self.assertTrue (eq(numpy.sin(x), sin(xm)))
     self.assertTrue (eq(numpy.sinh(x), sinh(xm)))
     self.assertTrue (eq(numpy.tan(x), tan(xm)))
     self.assertTrue (eq(numpy.tanh(x), tanh(xm)))
     olderr = numpy.seterr(divide='ignore', invalid='ignore')
     try:
         self.assertTrue (eq(numpy.sqrt(abs(x)), sqrt(xm)))
         self.assertTrue (eq(numpy.log(abs(x)), log(xm)))
         self.assertTrue (eq(numpy.log10(abs(x)), log10(xm)))
     finally:
         numpy.seterr(**olderr)
     self.assertTrue (eq(numpy.exp(x), exp(xm)))
     self.assertTrue (eq(numpy.arcsin(z), arcsin(zm)))
     self.assertTrue (eq(numpy.arccos(z), arccos(zm)))
     self.assertTrue (eq(numpy.arctan(z), arctan(zm)))
     self.assertTrue (eq(numpy.arctan2(x, y), arctan2(xm, ym)))
     self.assertTrue (eq(numpy.absolute(x), absolute(xm)))
     self.assertTrue (eq(numpy.equal(x, y), equal(xm, ym)))
     self.assertTrue (eq(numpy.not_equal(x, y), not_equal(xm, ym)))
     self.assertTrue (eq(numpy.less(x, y), less(xm, ym)))
     self.assertTrue (eq(numpy.greater(x, y), greater(xm, ym)))
     self.assertTrue (eq(numpy.less_equal(x, y), less_equal(xm, ym)))
     self.assertTrue (eq(numpy.greater_equal(x, y), greater_equal(xm, ym)))
     self.assertTrue (eq(numpy.conjugate(x), conjugate(xm)))
     self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, ym))))
     self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((x, y))))
     self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, y))))
     self.assertTrue (eq(numpy.concatenate((x, y, x)), concatenate((x, ym, x))))
def genData():
    c1 = 0.5
    r1 = 0.4
    r2 = 0.3
    Ndat = 1000
    # generate enough data to filter
    N = 20* Ndat
    X = array(random_sample(N))
    Y = array(random_sample(N))
    X1 = X[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1]
    Y1 = Y[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1]
    X2 = X1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2]
    Y2 = Y1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2]
    X3 = X2[ abs(X2-Y2)>0.05 ]
    Y3 = Y2[ abs(X2-Y2)>0.05 ]
    #X3 = X2[ X2-Y2>0.15 ]
    #Y3 = Y2[ X2-Y2>0.15]
    X4=zeros( Ndat, dtype=float32)
    Y4=zeros( Ndat, dtype=float32)
    for i in xrange(Ndat):
        if (X3[i]-Y3[i]) >0.05:
            X4[i] = X3[i] + 0.08
            Y4[i] = Y3[i] + 0.18
        else:
            X4[i] = X3[i] - 0.08
            Y4[i] = Y3[i] - 0.18
    print "X", size(X3[0:Ndat]), "Y", size(Y3)
    return vstack((X4[0:Ndat],Y4[0:Ndat])), vstack((array(random_sample(Ndat)),array(random_sample(Ndat))))
Example #21
0
def secant(func, x0, x1, eps, max_iter=50):

  # Evaluate the function at the interval
  f_l = func(x0)
  f_x = func(x1)

  # Set the initial x
  if abs(f_l) < abs(f_x):
    x = x0
    xl = x1
    f_l, f_x = f_x, f_l
  else:
    xl = x0
    x = x1

  # Iterate
  for i in range(max_iter):
    dx = (xl - x) * f_x / (f_x - f_l)
    xl = x
    f_l = f_x
    x += dx
    f_x = func(x)

    # If we've reached the root, return
    if abs(dx) < eps or f_x == 0.0:
      return x

  # Raise an exception if we reach maximum iterations
  raise RuntimeError('Maximum iterations reached')
Example #22
0
	def get_balance(self):
		if not getlist(self.doclist,'entries'):
			msgprint("Please enter atleast 1 entry in 'GL Entries' table")
		else:
			flag, self.doc.total_debit, self.doc.total_credit = 0, 0, 0
			diff = flt(self.doc.difference, 2)
			
			# If any row without amount, set the diff on that row
			for d in getlist(self.doclist,'entries'):
				if not d.credit and not d.debit and diff != 0:
					if diff>0:
						d.credit = diff
					elif diff<0:
						d.debit = diff
					flag = 1
					
			# Set the diff in a new row
			if flag == 0 and diff != 0:
				jd = addchild(self.doc, 'entries', 'Journal Voucher Detail', self.doclist)
				if diff>0:
					jd.credit = abs(diff)
				elif diff<0:
					jd.debit = abs(diff)
					
			# Set the total debit, total credit and difference
			for d in getlist(self.doclist,'entries'):
				self.doc.total_debit += flt(d.debit, 2)
				self.doc.total_credit += flt(d.credit, 2)

			self.doc.difference = flt(self.doc.total_debit, 2) - flt(self.doc.total_credit, 2)
Example #23
0
    def drawLink(self, src, dst, style):
        p = self.params
        lineStyle = self.scene.lineStyles[style]

        # shorten the line by the radius of the node to prevent
        # parts of the line from being covered by the node
        endpoints = computeLinkEndPoints(src, dst, p.nodesize)

        # both nodes are on the same location, link not visible
        if endpoints == None: return

        (sx, sy, dx, dy) = endpoints

        # draw nothing if the line is not visible after shortened
        if abs(dx-sx) < 0.01 and abs(dy-sy) < 0.01: return

        if lineStyle.arrow == 'both':
            arrow = "ArrowHead ArrowTail"
        elif lineStyle.arrow == 'head':
            arrow = "ArrowHead"
        elif lineStyle.arrow == 'tail':
            arrow = "ArrowTail"
        else:
            arrow = ""

        print >> self.stream, "LS%d %7.2f %7.2f %7.2f %7.2f %s Line" % (
              style, sx, sy, dx, dy, arrow
              )
	def process(self,Y,X=None,Xt=None,tests=None):
		self.setYX(Y,X,Xt)
		bivariter = 0
		sumSSE = 0
		esiter = list()
		es.state()["iterations"] = esiter
		# in the first iteration we calculate W by using ones on U
		U = ssp.csc_matrix(ones(self.u.shape))
		while True:
			esiterdict = dict()
			esiterdict["i"] = bivariter
			logger.debug("Starting iteration: %d"%bivariter)
			bivariter += 1
			W,w_bias,err = self.calculateW(U,tests=tests)
			esiterdict["w"] = W
			esiterdict["w_sparcity"] = (abs(W) > 0).sum()
			esiterdict["w_bias"] = w_bias
			esiterdict["w_test_err"] = err
			if "test" in err: logger.debug("W sparcity=%d,test_total_err=%2.2f,test_err=%s"%(esiterdict["w_sparcity"],err['test']["totalsse"],str(err['test']["diffsse"])))
			W = ssp.csc_matrix(W)
			U,u_bias,err = self.calculateU(W,tests=tests)
			esiterdict["u"] = U
			esiterdict["u_sparcity"] = (abs(U) > 0).sum()
			esiterdict["u_bias"] = u_bias
			esiterdict["u_test_err"] = err
			if "test" in err: logger.debug("U sparcity=%d,test_total_err=%2.2f,test_err=%s"%(esiterdict["u_sparcity"],err['test']["totalsse"],str(err['test']["diffsse"])))
			U = ssp.csc_matrix(U)
			self.u = U
			self.w = W
			self.w_bias = w_bias
			self.u_bias = u_bias
			esiter += [esiterdict]
			if self.allParams['bivar_max_it'] <= bivariter:
				break
		return sumSSE
def resize(image, dim):
    #print "Resizing"
    todo = [True, True]
    while any(todo):
        if dim[1] != image.shape[1]:
            virtical_seams = find_seams(cost(image.sum(axis=-1)/3.))
            num_needed = abs(image.shape[1]-dim[1])
            #print "Found %d vert seams (%d more)"%(len(virtical_seams), num_needed)
            allpaths = reduce(lambda a,b : a+b, (seam["path"] for seam in virtical_seams[:num_needed]))
            if dim[1] < image.shape[1]:
                image = remove_path(image, allpaths)
            else:
                image = stretch_path(image, allpaths)
        else:
            todo[1] = False

        if dim[0] != image.shape[0]:
            horizontal_seams = find_seams(cost((image.sum(axis=-1)/3.).T))
            num_needed = abs(image.shape[0]-dim[0])
            #print "Found %d horiz seams (%d more)"%(len(horizontal_seams), num_needed)
            allpaths = reduce(lambda a,b : a+b, (seam["path"] for seam in horizontal_seams[:num_needed]))
            if dim[0] < image.shape[0]:
                image = remove_path(image.swapaxes(0,1), allpaths).swapaxes(0,1)
            else:
                image = stretch_path(image.swapaxes(0,1), allpaths).swapaxes(0,1)
        else:
            todo[0] = False
    return image
Example #26
0
    def __new__(cls, latitude=None, longitude=None, altitude=None):
        single_arg = longitude is None and altitude is None
        if single_arg and not isinstance(latitude, util.NUMBER_TYPES):
            arg = latitude
            if arg is None:
                pass
            elif isinstance(arg, Point):
                return cls.from_point(arg)
            elif isinstance(arg, basestring):
                return cls.from_string(arg)
            else:
                try:
                    seq = iter(arg)
                except TypeError:
                    raise TypeError(
                        "Failed to create Point instance from %r." % (arg,)
                    )
                else:
                    return cls.from_sequence(seq)

        latitude = float(latitude or 0)
        if abs(latitude) > 90:
            latitude = ((latitude + 90) % 180) - 90

        longitude = float(longitude or 0)
        if abs(longitude) > 180:
            longitude = ((longitude + 180) % 360) - 180

        altitude = float(altitude or 0)

        self = super(Point, cls).__new__(cls)
        self.latitude = latitude
        self.longitude = longitude
        self.altitude = altitude
        return self
Example #27
0
def solve_matrix(mat, variables):
    m, n = mat.shape
    if len(variables) != n - 1:
        raise ValueError("Expected %d variables" % (n - 1,))

    if m >= n:
        # add fake columns at the front
        mat = numpy.hstack((numpy.zeros((m, m-n)), mat))
        variables[0:0] = ["_fake%d" % (i,) for i in range(m-n)]
        m, n = mat.shape

    eliminate(mat)
    assignments = {}
    
    for row in mat[::-1]:
        nonzero = list(itertools.dropwhile(lambda v: abs(v) <= EPSILON, row))
        if not nonzero:
            continue
        const = nonzero.pop(-1)
        if not nonzero:
            # a row of the form (0 0 ... 0 x) means a contradiction
            raise NoSolutionsExist()
        vars = variables[-len(nonzero):]
        assignee = vars.pop(0)
        assert abs(nonzero.pop(0) - 1) <= EPSILON
        assignments[assignee] = const
        
        for i, v in enumerate(vars):
            if v not in assignments:
                assignments[v] = FreeVar(v)
            assignments[assignee] -= nonzero[i] * assignments[v]
    
    return assignments
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 #29
0
 def calc_radius(self, x1, y1, radius):
     # scale radius
     cx1, cy1 = self.canvascoords(x1, y1)
     cx2, cy2 = self.canvascoords(x1, y1 + radius)
     # TODO: the accuracy of this calculation of radius might be improved?
     cradius = math.sqrt(abs(cy2 - cy1)**2 + abs(cx2 - cx1)**2)
     return (cx1, cy1, cradius)
def dec(a, b):
    if 0 <= abs(a) / abs(b) <= 1:
        return a / b
    elif 0 <= abs(b) / abs(a) <= 1:
        return b / a
    else:
        return 0