Example #1
2
    def test_power_zero(self):
        # ticket #1271
        zero = np.array([0j])
        one = np.array([1 + 0j])
        cinf = np.array([complex(np.inf, 0)])
        cnan = np.array([complex(np.nan, np.nan)])

        def assert_complex_equal(x, y):
            x, y = np.asarray(x), np.asarray(y)
            assert_array_equal(x.real, y.real)
            assert_array_equal(x.imag, y.imag)

        # positive powers
        for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
            assert_complex_equal(np.power(zero, p), zero)

        # zero power
        assert_complex_equal(np.power(zero, 0), one)
        assert_complex_equal(np.power(zero, 0 + 1j), cnan)

        # negative power
        for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
            assert_complex_equal(np.power(zero, -p), cnan)
        assert_complex_equal(np.power(zero, -1 + 0.2j), cnan)

        def test_fast_power(self):
            x = np.array([1, 2, 3], np.int16)
            assert (x ** 2.00001).dtype is (x ** 2.0).dtype
Example #2
0
 def setCoefs(self):
     # If not closed, then this should change (less sides) !
     self.Nsides = len(self.xylist)
     self.ldList = []
     xy = self.xylist
     self.xlist = [xy[0][0]]; self.ylist = [xy[0][1]]
     self.z1 = []; self.z2 = []
     for i in range(self.Nsides-1):
         ld = LineDoublet(self.modelParent,xy[i][0],xy[i][1],xy[i+1][0],xy[i+1][1],\
                          self.aqin,self.aqout,self.Ndegree,self.overspec,addToModel=0)
         self.ldList = self.ldList + [ld]
         self.xlist = self.xlist + [xy[i+1][0]]; self.ylist = self.ylist + [xy[i+1][1]]
         self.z1 = self.z1 + [ complex( xy[i][0], xy[i][1] ) ]
         self.z2 = self.z2 + [ complex( xy[i+1][0], xy[i+1][1] ) ]
     if self.closed:
         ld = LineDoublet(self.modelParent,xy[-1][0],xy[-1][1],xy[0][0],xy[0][1],\
                          self.aqin,self.aqout,self.Ndegree,self.overspec,addToModel=0)
         self.ldList = self.ldList + [ld]
         self.xlist = self.xlist + [xy[0][0]]; self.ylist = self.ylist + [xy[0][1]]
         self.z1 = self.z1 + [ complex( xy[-1][0], xy[-1][1] ) ]
         self.z2 = self.z2 + [ complex( xy[0][0], xy[0][1] ) ]
     self.z1 = array(self.z1); self.z2 = array(self.z2)
     self.Nparam = 0
     for ld in self.ldList:
         self.Nparam = self.Nparam + ld.Ndegree  # Cause the constant and linear portions are joined
     self.parameters = zeros( (self.Nparam,1), 'd' )
Example #3
0
def getJumpPoint(begin, end, loop, runningJumpSpace):
    "Get running jump point inside loop."
    segment = begin - end
    segmentLength = abs(segment)
    if segmentLength == 0.0:
        return begin
    segment /= segmentLength
    distancePoint = DistancePoint(begin, loop, runningJumpSpace, segment)
    if distancePoint.distance == runningJumpSpace:
        return distancePoint.point
    effectiveDistance = distancePoint.distance
    jumpPoint = distancePoint.point
    segmentLeft = complex(0.70710678118654757, -0.70710678118654757)
    distancePoint = DistancePoint(begin, loop, runningJumpSpace, segmentLeft)
    distancePoint.distance *= 0.5
    if distancePoint.distance > effectiveDistance:
        effectiveDistance = distancePoint.distance
        jumpPoint = distancePoint.point
    segmentRight = complex(0.70710678118654757, 0.70710678118654757)
    distancePoint = DistancePoint(begin, loop, runningJumpSpace, segmentRight)
    distancePoint.distance *= 0.5
    if distancePoint.distance > effectiveDistance:
        effectiveDistance = distancePoint.distance
        jumpPoint = distancePoint.point
    return jumpPoint
Example #4
0
 def test_complex_nans(self):
     nan = np.nan
     for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
         arg1 = np.array([0, cnan, cnan], dtype=np.complex)
         arg2 = np.array([cnan, 0, cnan], dtype=np.complex)
         out = np.array([0, 0, nan], dtype=np.complex)
         assert_equal(np.fmin(arg1, arg2), out)
Example #5
0
    def potentialInfluence(self,aq,x,y):
        zin = complex(x,y)
        bigZ = ( 2.0*zin - (self.z1 + self.z2) )/ (self.z2 - self.z1)
        if abs(bigZ.imag) < self.tiny and abs(bigZ.real) < 1.0-self.tiny:  # point is on boundary; this could be nicer by setting the log
                if self.aqin == aq:
                    bigZ = complex(bigZ.real,self.tiny)
                elif self.aqout == aq:
                    bigZ = complex(bigZ.real,-self.tiny)
                zin = ( (self.z2-self.z1)*bigZ + (self.z1+self.z2) ) / 2.0
        bigZmin1 = bigZ - 1.0; bigZplus1 = bigZ + 1.0
##        if abs(bigZmin1) < self.tiny:
##            # point is at right corner; move back a little along element; may fail if corner is very pointy
##            # This needs to be moved by the PolygonInhom class; after all, that class decided it was inside.
##            if self.aqin == aq:
##                zin = self.z2 + complex(4.0,-1.0) * self.tiny * (self.z1 - self.z2)
##            else:
##                zin = self.z2 + complex(4.0,1.0) * self.tiny * (self.z1 - self.z2)
##        elif abs(bigZplus1) < self.tiny:  # point is at left corner, move up a little along ldLeft
##            if self.aqin == aq:
##                zin = self.ldLeft.z2 + complex(4.0,-1.0) * self.tiny * (self.ldLeft.z1 - self.ldLeft.z2)
##            else:
##                zin = self.ldLeft.z2 + complex(4.0,1.0) * self.tiny * (self.ldLeft.z1 - self.ldLeft.z2)
        if abs(bigZmin1) < self.tiny or abs(bigZplus1) < self.tiny: # gotta be inside; move point
            # zin = self.aqin.movePoint(zin)
            # doesn't have to be inside when inhoms butt-up
            zin = aq.movePoint(zin)
        #  Only works for line-doublet in one layer, so that is hardcoded (the zero lists)
        rv = zeros((self.Ndegree+1,aq.Naquifers),'d')
        x = zin.real; y = zin.imag
        potlapldho(x,y,self.x1,self.y1,self.x2,self.y2,self.Ndegree,self.potInf)
        rv[:,0] = self.potInf
        return rv
Example #6
0
    def test_power_complex(self):
        x = np.array([1 + 2j, 2 + 3j, 3 + 4j])
        assert_equal(x ** 0, [1.0, 1.0, 1.0])
        assert_equal(x ** 1, x)
        assert_almost_equal(x ** 2, [-3 + 4j, -5 + 12j, -7 + 24j])
        assert_almost_equal(x ** 3, [(1 + 2j) ** 3, (2 + 3j) ** 3, (3 + 4j) ** 3])
        assert_almost_equal(x ** 4, [(1 + 2j) ** 4, (2 + 3j) ** 4, (3 + 4j) ** 4])
        assert_almost_equal(x ** (-1), [1 / (1 + 2j), 1 / (2 + 3j), 1 / (3 + 4j)])
        assert_almost_equal(x ** (-2), [1 / (1 + 2j) ** 2, 1 / (2 + 3j) ** 2, 1 / (3 + 4j) ** 2])
        assert_almost_equal(x ** (-3), [(-11 + 2j) / 125, (-46 - 9j) / 2197, (-117 - 44j) / 15625])
        assert_almost_equal(x ** (0.5), [ncu.sqrt(1 + 2j), ncu.sqrt(2 + 3j), ncu.sqrt(3 + 4j)])
        norm = 1.0 / ((x ** 14)[0])
        assert_almost_equal(
            x ** 14 * norm, [i * norm for i in [-76443 + 16124j, 23161315 + 58317492j, 5583548873 + 2465133864j]]
        )

        # Ticket #836
        def assert_complex_equal(x, y):
            assert_array_equal(x.real, y.real)
            assert_array_equal(x.imag, y.imag)

        for z in [complex(0, np.inf), complex(1, np.inf)]:
            err = np.seterr(invalid="ignore")
            z = np.array([z], dtype=np.complex_)
            try:
                assert_complex_equal(z ** 1, z)
                assert_complex_equal(z ** 2, z * z)
                assert_complex_equal(z ** 3, z * z * z)
            finally:
                np.seterr(**err)
Example #7
0
    def mat_unitary(self):
        s = [
            math.sin(2 * self.at0),
            math.sin(2 * self.at1),
            math.sin(2 * self.aq0),
            math.sin(2 * self.aq1),
            math.sin(2 * self.aq2),
        ]
        c = [
            math.cos(2 * self.at0),
            math.cos(2 * self.at1),
            math.cos(2 * self.aq0),
            math.cos(2 * self.aq1),
            math.cos(2 * self.aq2),
        ]
        phi = [
            numpy.exp(complex(0, 4 * self.pt1)),
            numpy.exp(complex(0, 2 * self.pt2)),
            numpy.exp(complex(0, -2 * self.pt2)),
        ]

        U = numpy.array(
            [
                [c[2] * c[3], -phi[0] * s[0] * s[2] * c[3] - phi[1] * c[0] * s[1] * s[3]],
                [c[2] * s[3], -phi[0] * s[0] * s[2] * s[3] + phi[1] * c[0] * s[1] * c[3]],
                [s[2] * c[4], phi[0] * s[0] * c[2] * c[4] + phi[2] * c[0] * c[1] * s[4]],
                [s[2] * s[4], phi[0] * s[0] * c[2] * s[4] - phi[2] * c[0] * c[1] * c[4]],
            ]
        )

        theta = cmath.phase(U[0, 1])
        for i in range(4):
            U[i, 1] = U[i, 1] * numpy.exp(complex(0, -theta))

        return U
Example #8
0
 def complex_div(a, b):
     # This is CPython's algorithm (in _Py_c_quot()).
     areal = a.real
     aimag = a.imag
     breal = b.real
     bimag = b.imag
     if not breal and not bimag:
         raise ZeroDivisionError("complex division by zero")
     if abs(breal) >= abs(bimag):
         # Divide tops and bottom by b.real
         if not breal:
             return complex(NAN, NAN)
         ratio = bimag / breal
         denom = breal + bimag * ratio
         return complex(
             (areal + aimag * ratio) / denom,
             (aimag - areal * ratio) / denom)
     else:
         # Divide tops and bottom by b.imag
         if not bimag:
             return complex(NAN, NAN)
         ratio = breal / bimag
         denom = breal * ratio + bimag
         return complex(
             (a.real * ratio + a.imag) / denom,
             (a.imag * ratio - a.real) / denom)
Example #9
0
def zeta(s):
    """
    Riemann zeta function, real argument
    """
    if not isinstance(s, (float, int)):
        try:
            s = float(s)
        except (ValueError, TypeError):
            try:
                s = complex(s)
                if not s.imag:
                    return complex(zeta(s.real))
            except (ValueError, TypeError):
                pass
            raise NotImplementedError
    if s == 1:
        raise ValueError("zeta(1) pole")
    if s >= 27:
        return 1.0 + 2.0**(-s) + 3.0**(-s)
    n = int(s)
    if n == s:
        if n >= 0:
            return _zeta_int[n]
        if not (n % 2):
            return 0.0
    if s <= 0.0:
        return 0
    if s <= 2.0:
        if s <= 1.0:
            return _polyval(_zeta_0,s)/(s-1)
        return _polyval(_zeta_1,s)/(s-1)
    z = _polyval(_zeta_P,s) / _polyval(_zeta_Q,s)
    return 1.0 + 2.0**(-s) + 3.0**(-s) + 4.0**(-s)*z
Example #10
0
    def test_branches(self):
        with np.errstate(all="ignore"):
            for t in [np.complex64, np.complex128]:
                # tupled (numerator, denominator, expected)
                # for testing as expected == numerator/denominator
                data = list()

                # trigger branch: real(fabs(denom)) > imag(fabs(denom))
                # followed by else condition as neither are == 0
                data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0)))

                # trigger branch: real(fabs(denom)) > imag(fabs(denom))
                # followed by if condition as both are == 0
                # is performed in test_zero_division(), so this is skipped

                # trigger else if branch: real(fabs(denom)) < imag(fabs(denom))
                data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0)))

                for cases in data:
                    n = cases[0]
                    d = cases[1]
                    ex = cases[2]
                    result = t(complex(n[0], n[1])) / t(complex(d[0], d[1]))
                    # check real and imag parts separately to avoid comparison
                    # in array context, which does not account for signed zeros
                    assert_equal(result.real, ex[0])
                    assert_equal(result.imag, ex[1])
def removeIntersection( loop ):
	'Get loop without the first intersection.'
	for pointIndex, ahead in enumerate(loop):
		behind = loop[ ( pointIndex + len( loop ) - 1 ) % len( loop ) ]
		behindEnd = loop[ ( pointIndex + len( loop ) - 2 ) % len( loop ) ]
		behindMidpoint = 0.5 * ( behind + behindEnd )
		aheadEnd = loop[ (pointIndex + 1) % len( loop ) ]
		aheadMidpoint = 0.5 * ( ahead + aheadEnd )
		normalizedSegment = behind - behindMidpoint
		normalizedSegmentLength = abs( normalizedSegment )
		if normalizedSegmentLength > 0.0:
			normalizedSegment /= normalizedSegmentLength
			segmentYMirror = complex(normalizedSegment.real, -normalizedSegment.imag)
			behindRotated = segmentYMirror * behind
			behindMidpointRotated = segmentYMirror * behindMidpoint
			aheadRotated = segmentYMirror * ahead
			aheadMidpointRotated = segmentYMirror * aheadMidpoint
			y = behindRotated.imag
			xIntersection = euclidean.getXIntersectionIfExists( aheadRotated, aheadMidpointRotated, y )
			if xIntersection != None:
				if xIntersection > min( behindMidpointRotated.real, behindRotated.real ) and xIntersection < max( behindMidpointRotated.real, behindRotated.real ):
					intersectionPoint = normalizedSegment * complex( xIntersection, y )
					loop[ ( pointIndex + len( loop ) - 1 ) % len( loop ) ] = intersectionPoint
					del loop[pointIndex]
					return
def getTeardropPath(inclination, overhangRadians, overhangSpan, radiusArealized, sides):
	"Get vector3 teardrop path."
	sideAngle = 2.0 * math.pi / float(sides)
	overhangPlaneAngle = euclidean.getWiddershinsUnitPolar(overhangRadians)
	overhangRadians = math.atan2(overhangPlaneAngle.imag, overhangPlaneAngle.real * math.cos(inclination))
	tanOverhangAngle = math.tan(overhangRadians)
	beginAngle = overhangRadians
	beginMinusEndAngle = math.pi + overhangRadians + overhangRadians
	withinSides = int(math.ceil(beginMinusEndAngle / sideAngle))
	withinSideAngle = -beginMinusEndAngle / float(withinSides)
	teardropPath = []
	for side in xrange(withinSides + 1):
		unitPolar = euclidean.getWiddershinsUnitPolar(beginAngle)
		teardropPath.append(unitPolar * radiusArealized)
		beginAngle += withinSideAngle
	firstPoint = teardropPath[0]
	if overhangSpan <= 0.0:
		teardropPath.append(complex(0.0, firstPoint.imag + firstPoint.real / tanOverhangAngle))
	else:
		deltaX = (radiusArealized - firstPoint.imag) * tanOverhangAngle
		overhangPoint = complex(firstPoint.real - deltaX, radiusArealized)
		remainingDeltaX = max(0.0, overhangPoint.real - 0.5 * overhangSpan )
		overhangPoint += complex(-remainingDeltaX, remainingDeltaX / tanOverhangAngle)
		teardropPath.append(complex(-overhangPoint.real, overhangPoint.imag))
		teardropPath.append(overhangPoint)
	return euclidean.getVector3Path(teardropPath)
Example #13
0
def paz_2_amplitude_value_of_freq_resp(paz, freq):
    """
    Returns Amplitude at one frequency for the given poles and zeros

    :param paz: Given poles and zeros
    :param freq: Given frequency

    The amplitude of the freq is estimated according to "Of Poles and
    Zeros", Frank Scherbaum, p 43.

    .. rubric:: Example

    >>> paz = {'poles': [-4.44 + 4.44j, -4.44 - 4.44j],
    ...        'zeros': [0 + 0j, 0 + 0j],
    ...        'gain': 0.4}
    >>> amp = paz_2_amplitude_value_of_freq_resp(paz, 1)
    >>> print(round(amp, 7))
    0.2830262
    """
    jw = complex(0, 2 * np.pi * freq)  # angular frequency
    fac = complex(1, 0)
    for zero in paz['zeros']:  # numerator
        fac *= jw - zero
    for pole in paz['poles']:  # denominator
        fac /= jw - pole
    return abs(fac) * paz['gain']
Example #14
0
    def test_power_zero(self):
        # ticket #1271
        zero = np.array([0j])
        one = np.array([1+0j])
        cinf = np.array([complex(np.inf, 0)])
        cnan = np.array([complex(np.nan, np.nan)])

        def assert_complex_equal(x, y):
            x, y = np.asarray(x), np.asarray(y)
            assert_array_equal(x.real, y.real)
            assert_array_equal(x.imag, y.imag)

        # positive powers
        for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
            assert_complex_equal(np.power(zero, p), zero)

        # zero power
        assert_complex_equal(np.power(zero, 0), one)
        with np.errstate(invalid="ignore"):
            assert_complex_equal(np.power(zero, 0+1j), cnan)

            # negative power
            for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
                assert_complex_equal(np.power(zero, -p), cnan)
            assert_complex_equal(np.power(zero, -1+0.2j), cnan)
Example #15
0
 def _follow_vertical_line(self, x, y):
     """Find a vertical line with optional arrow heads."""
     # follow line to the bottom
     _, end_y, line_end_style = self._follow_line(x, y, dy=1, line_character='|')
     # follow line to the top
     _, start_y, line_start_style = self._follow_line(x, y, dy=-1, line_character='|')
     # if a '+' follows a line, then the line is stretched to hit the '+' center
     start_y_fix = end_y_fix = 0
     if self.get(x, start_y - 1) == '+':
         start_y_fix = -0.5
     if self.get(x, end_y + 1) == '+':
         end_y_fix = 0.5
     # tag characters as used (not the arrow heads)
     self.tag([(x, y) for y in range(start_y, end_y + 1)], CLASS_LINE)
     # return the new shape object with arrows etc.
     p1 = complex(self.hcenter(x), self.top(start_y + start_y_fix))
     p2 = complex(self.hcenter(x), self.bottom(end_y + end_y_fix))
     shapes = []
     if line_start_style:
         p1, arrow_shapes = line_start_style(p1, p2)
         shapes.extend(arrow_shapes)
     if line_end_style:
         p2, arrow_shapes = line_end_style(p2, p1)
         shapes.extend(arrow_shapes)
     shapes.append(Line(p1, p2))
     return group(shapes)
Example #16
0
 def _follow_horizontal_line(self, x, y, thick=False):
     """Find a horizontal line with optional arrow heads."""
     if thick:
         line_character = '='
     else:
         line_character = '-'
     # follow line to the right
     end_x, _, line_end_style = self._follow_line(x, y, dx=1, line_character=line_character)
     # follow line to the left
     start_x, _, line_start_style = self._follow_line(x, y, dx=-1, line_character=line_character)
     start_x_fix = end_x_fix = 0
     if self.get(start_x - 1, y) == '+':
         start_x_fix = -0.5
     if self.get(end_x + 1, y) == '+':
         end_x_fix = 0.5
     self.tag([(x, y) for x in range(start_x, end_x+1)], CLASS_LINE)
     # return the new shape object with arrows etc.
     p1 = complex(self.left(start_x + start_x_fix), self.vcenter(y))
     p2 = complex(self.right(end_x + end_x_fix), self.vcenter(y))
     shapes = []
     if line_start_style:
         p1, arrow_shapes = line_start_style(p1, p2)
         shapes.extend(arrow_shapes)
     if line_end_style:
         p2, arrow_shapes = line_end_style(p2, p1)
         shapes.extend(arrow_shapes)
     shapes.append(Line(p1, p2, thick=thick))
     return group(shapes)
Example #17
0
def generate_jpeg(width, height):
    # Mandelbrot fractal
    # FB - 201003254
    # drawing area
    xa = -2.0
    xb = 1.0
    ya = -1.5
    yb = 1.5
    maxIt = 25  # max iterations allowed
    # image size
    image = Image.new('RGB', (width, height))
    c = complex(random.random() * 2.0 - 1.0, random.random() - 0.5)

    for y in range(height):
        zy = y * (yb - ya) / (height - 1) + ya
        for x in range(width):
            zx = x * (xb - xa) / (width - 1) + xa
            z = complex(zx, zy)
            for i in range(maxIt):
                if abs(z) > 2.0:
                    break
                z = z * z + c
            r = i % 4 * 64
            g = i % 8 * 32
            b = i % 16 * 16
            image.putpixel((x, y), b * 65536 + g * 256 + r)

    output = StringIO()
    image.save(output, format='PNG')
    return output.getvalue()
Example #18
0
def rootWrapper(a,b,c,d):
    if a:
        # Monics formula see http://en.wikipedia.org/wiki/Cubic_function#Monic_formula_of_roots
        a,b,c = (b/a, c/a, d/a)
        m = 2.0*a**3 - 9.0*a*b + 27.0*c
        k = a**2 - 3.0*b
        n = m**2 - 4.0*k**3
        w1 = -.5 + .5*cmath.sqrt(-3.0)
        w2 = -.5 - .5*cmath.sqrt(-3.0)
        if n < 0:
            m1 = pow(complex((m+cmath.sqrt(n))/2),1./3)
            n1 = pow(complex((m-cmath.sqrt(n))/2),1./3)
        else:
            if m+math.sqrt(n) < 0:
                m1 = -pow(-(m+math.sqrt(n))/2,1./3)
            else:
                m1 = pow((m+math.sqrt(n))/2,1./3)
            if m-math.sqrt(n) < 0:
                n1 = -pow(-(m-math.sqrt(n))/2,1./3)
            else:
                n1 = pow((m-math.sqrt(n))/2,1./3)
        x1 = -1./3 * (a + m1 + n1)
        x2 = -1./3 * (a + w1*m1 + w2*n1)
        x3 = -1./3 * (a + w2*m1 + w1*n1)
        return (x1,x2,x3)
    elif b:
        det=c**2.0-4.0*b*d
        if det:
            return (-c+cmath.sqrt(det))/(2.0*b),(-c-cmath.sqrt(det))/(2.0*b)
        else:
            return -c/(2.0*b),
    elif c:
        return 1.0*(-d/c),
    return ()
Example #19
0
    def test_repr_roundtrip(self):
        vals = [0.0, 1e-500, 1e-315, 1e-200, 0.0123, 3.1415, 1e50, INF, NAN]
        vals += [-v for v in vals]

        # complex(repr(z)) should recover z exactly, even for complex
        # numbers involving an infinity, nan, or negative zero
        for x in vals:
            for y in vals:
                z = complex(x, y)
                roundtrip = complex(repr(z))
                self.assertFloatsAreIdentical(z.real, roundtrip.real)
                self.assertFloatsAreIdentical(z.imag, roundtrip.imag)

        # if we predefine some constants, then eval(repr(z)) should
        # also work, except that it might change the sign of zeros
        inf, nan = float('inf'), float('nan')
        infj, nanj = complex(0.0, inf), complex(0.0, nan)
        for x in vals:
            for y in vals:
                z = complex(x, y)
                roundtrip = eval(repr(z))
                # adding 0.0 has no effect beside changing -0.0 to 0.0
                self.assertFloatsAreIdentical(0.0 + z.real,
                                              0.0 + roundtrip.real)
                self.assertFloatsAreIdentical(0.0 + z.imag,
                                              0.0 + roundtrip.imag)
def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
Example #21
0
    def drawMandelbrot(self):

        start = self.start
        end = self.end

        print "drawing mandelbrot! ", start, end

        scale_x = complex((end-start).real/self.size, 0)
        scale_y = complex(0, (end-start).imag/self.size)

        for y in range(self.size):
            for x in range(self.size):
                z = 0j
                c = start + x*scale_x + y*scale_y
                for count in range(self.iterations):
                    if abs(z) <= 2:
                        z = z * z + c
                    else:
                        break
                color = self.getColor(count)
                ps = self.pointsize
                self.canvas.create_rectangle(x*ps, y*ps, x*ps + ps, y*ps + ps, fill=color, outline=color)

            if y % 32 == 0:
                root.update()
Example #22
0
 def test_getnewargs(self):
     self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0))
     self.assertEqual((1-2j).__getnewargs__(), (1.0, -2.0))
     self.assertEqual((2j).__getnewargs__(), (0.0, 2.0))
     self.assertEqual((-0j).__getnewargs__(), (0.0, -0.0))
     self.assertEqual(complex(0, INF).__getnewargs__(), (0.0, INF))
     self.assertEqual(complex(INF, 0).__getnewargs__(), (INF, 0.0))
Example #23
0
    def getD3Tensor(self, setting):
        '''
        Obtain third order anharmonic tensor from QE d3.x
        '''

        file = open(setting.get('fildyn'), 'r')
        lines = file.readlines()
        ntype = int(lines[2].split()[0])
        natom = int(lines[2].split()[1])
        d3tensor = []
        qpoints = []
        numberq = 0
        for index, line in enumerate(lines):
            if 'q = (' in line:
                numberq = numberq + 1
                qpoints.append([float(f) for f in lines[index].split()[3:6]])
                for mode in range(0,3*natom):
                    for i in range(0,natom):
                        for j in range(0,natom):
                            for idir in range(0,3):
                                _itemp = index+mode*(natom*natom*7 + 3)+\
                                         (i*natom+j)*7 + 6 + idir*natom
                                temp = lines[_itemp]+lines[_itemp + 1]
                                _val = [float(f) for f in temp.split()]
                                d3tensor.append(complex(_val[0],_val[1]))
                                d3tensor.append(complex(_val[2],_val[3]))
                                d3tensor.append(complex(_val[4],_val[5]))

        return  \
        (np.rollaxis(np.array(d3tensor).reshape(\
        numberq,natom,3,natom,natom,3,3),2,5), None), (np.array(qpoints), None),
    def test_receive(self):
        port = self.__get_free_port()
        receive_dialog = self.__get_recv_dialog()
        receive_dialog.device.set_server_port(port)
        receive_dialog.ui.btnStart.click()

        data = np.array([complex(1, 2), complex(3, 4), complex(5, 6)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertEqual(receive_dialog.device.current_index, 3)
        self.assertTrue(np.array_equal(receive_dialog.device.data[:3], data))

        receive_dialog.ui.btnStop.click()
        receive_dialog.ui.btnClear.click()

        self.assertEqual(receive_dialog.device.current_index, 0)

        self.__close_dialog(receive_dialog)
Example #25
0
def combined(c1, exp1, offset1, c2, exp2, offset2, width=500, height=500, real_min=-2.0, real_max=2.0, imag_min=-2.0, imag_max=2.0, pickColor=julia.timeBased, allPerlin = False):
	
	# Generate evenly spaced values over real and imaginary ranges
	real_range = numpy.arange(real_min, real_max, (real_max - real_min) / width)
	imag_range = numpy.arange(imag_max, imag_min, (imag_min - imag_max) / height)
	
	# Obtain image to work with
	image = Image.new('RGB', (width, height), (0, 0, 0))
	drawer = ImageDraw.Draw(image)
	
	# Generate pixel values
	for imag, ipix in itertools.izip(imag_range, range(height)):
		for real, rpix in itertools.izip(real_range, range(width)):
			z = complex(real, imag) + offset1
			n = 255
			while abs(z) < 10 and n >= 5:
				z = z ** exp1 + c1
				n -= 5
			m = 255
			z = (complex(real, imag) + offset2) * 2
			while abs(z) < 10 and n >= 5:
				z = z ** exp2 + c2
				n -= 5
			n = n - (m * 5)
			n = n % 255
			drawer.point((ipix, rpix), fill=pickColor(n, 0, real, imag)) # n varies between 255 and 5
	
	#time.increase()
	
	# And return results
	return image
Example #26
0
def test_inversion():
    N = 2**2    # Make mgrids without q1 = q2 = 0, since that case can be
                # problematic
    Q1, Q2 = np.mgrid[-8:8:complex(0, N), -8:8:complex(0, N)]
    epsilons = np.linspace(.1, .7, N)
    for epsilon in epsilons:
        check_inversions(Q1, Q2, epsilon)
    def test_spectrum(self):
        port = self.__get_free_port()
        spectrum_dialog = self.__get_spectrum_dialog()
        spectrum_dialog.device.set_server_port(port)
        spectrum_dialog.ui.btnStart.click()
        self.assertEqual(len(spectrum_dialog.scene_manager.peak), 0)

        data = np.array([complex(1, 1), complex(2, 2), complex(3, 3)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertGreater(len(spectrum_dialog.scene_manager.peak), 0)

        spectrum_dialog.ui.btnStop.click()

        self.__close_dialog(spectrum_dialog)
Example #28
0
    def createImage(self):
        self.updateProgress(0, self.height)
        for y in range(self.height):
            for x in range(self.width):
                z = complex(0.0, 0.0)
                k = complex(self.origin.real + \
                            float(x)/float(self.width)*self.range,
                            self.origin.imag - \
                            float(y) / float(self.height)*self.range)

                # calculate z = (z +k) * (z + k) over and over

                for iteration in range(self.depth):
                    real_part = z.real + k.real
                    imag_part = z.imag + k.imag
		    del z
                    z = complex(real_part * real_part - imag_part * \
                                imag_part, 2 * real_part * imag_part)
                    distance  = z.real * z.real + z.imag * z.imag

                    if distance >= self.maxDistance:
			cidx = int(distance % self.ncolors)
                        self.pixel(x, y, cidx)
                        break
            self.updateProgress(y)
        self.updateProgress(self.height, self.height)
        self.im.putpalette(self.rgb.getpalette())
        self.im.save("out.gif")
        self.img = PhotoImage(file="out.gif")
        self.label['image'] = self.img
Example #29
0
def divComplexNumbers(rA, iA, rB, iB):
    '''
    z.w = (a+bi).(c+di) = (ac-bd) + (ad+bc)i
    complex((rA*rB-iA*iB), (rA*iB+iA*rB))
    
    z/w = (z * conj(w)) / (w*conj(w))
    conjugado de w (a+bi) eh (a+(-b)i)
    
    ans = "{0}+{1}i".format( _sReal , _sImag)
    '''

    #A = complex(rA, iA)
    #B = complex(rB, iB)
    #cB = complex(rB, -iB)
    #cB = B.conjugate()
    
    num = mulComplexNumbers(rA, iA, rB, -iB) #A.__mul__(cB)
    dem = mulComplexNumbers(rB, iB, rB, -iB) #B.__mul__(cB)
    
    if num.imag == 0 and dem.imag == 0:
        return num.real / dem.real
    elif dem.imag == 0:
        rs = complex(num.real/dem.real, num.imag/dem.real)
        return rs
    else:
        rs = complex(num.real/dem.real, num.imag/dem.imag)
        return rs
Example #30
0
 def coherency_elements (self,observation):
   """helper method: returns the four components of the coherency matrix""";
   i,q,u,v = [ self.stokes(st) for st in STOKES ];
   # diagonal = (len(Context.active_correlations) == 2);
   diagonal = False;  # the above was bothersome -- even if we only use 2 corrs, we still want to do all intermediate computations in 2x2
   if observation.circular():
     if self._constant_flux:
       return (i+v,0,0,i-v) if diagonal else (i+v,complex(q,u),complex(q,-u),i-v);
     rr = self.ns.rr ** (self.stokes("I") + self.stokes("V"));
     if diagonal:
       rl = lr = 0;
     else:
       rl = self.ns.rl ** Meq.ToComplex(self.stokes("Q"),self.stokes("U"));
       lr = self.ns.lr ** Meq.Conj(rl);
     ll = self.ns.ll ** (self.stokes("I") - self.stokes("V"));
     return rr,rl,lr,ll;
   else:
     if self._constant_flux:
       return (i+q,0,0,i-q) if diagonal else (i+q,complex(u,v),complex(u,-v),i-q);
     xx = self.ns.xx ** (self.stokes("I") + self.stokes("Q"));
     if diagonal:
       xy = yx = 0;
     else:
       xy = self.ns.xy ** Meq.ToComplex(self.stokes("U"),self.stokes("V"));
       yx = self.ns.yx ** Meq.Conj(xy);
     yy = self.ns.yy ** (self.stokes("I") - self.stokes("Q"));
     return xx,xy,yx,yy;
Example #31
0
def solveTest3():
    x1,x2 = ev.solve(1.,5.,4.)
    return x1==complex(-1.,0.) and x2==complex(-4.,0.)
Example #32
0
    def test_phase(self):
        self.assertAlmostEqual(phase(0), 0.)
        self.assertAlmostEqual(phase(1.), 0.)
        self.assertAlmostEqual(phase(-1.), pi)
        self.assertAlmostEqual(phase(-1. + 1E-300j), pi)
        self.assertAlmostEqual(phase(-1. - 1E-300j), -pi)
        self.assertAlmostEqual(phase(1j), pi / 2)
        self.assertAlmostEqual(phase(-1j), -pi / 2)

        # zeros
        self.assertEqual(phase(complex(0.0, 0.0)), 0.0)
        self.assertEqual(phase(complex(0.0, -0.0)), -0.0)
        self.assertEqual(phase(complex(-0.0, 0.0)), pi)
        self.assertEqual(phase(complex(-0.0, -0.0)), -pi)

        # infinities
        self.assertAlmostEqual(phase(complex(-INF, -0.0)), -pi)
        self.assertAlmostEqual(phase(complex(-INF, -2.3)), -pi)
        self.assertAlmostEqual(phase(complex(-INF, -INF)), -0.75 * pi)
        self.assertAlmostEqual(phase(complex(-2.3, -INF)), -pi / 2)
        self.assertAlmostEqual(phase(complex(-0.0, -INF)), -pi / 2)
        self.assertAlmostEqual(phase(complex(0.0, -INF)), -pi / 2)
        self.assertAlmostEqual(phase(complex(2.3, -INF)), -pi / 2)
        self.assertAlmostEqual(phase(complex(INF, -INF)), -pi / 4)
        self.assertEqual(phase(complex(INF, -2.3)), -0.0)
        self.assertEqual(phase(complex(INF, -0.0)), -0.0)
        self.assertEqual(phase(complex(INF, 0.0)), 0.0)
        self.assertEqual(phase(complex(INF, 2.3)), 0.0)
        self.assertAlmostEqual(phase(complex(INF, INF)), pi / 4)
        self.assertAlmostEqual(phase(complex(2.3, INF)), pi / 2)
        self.assertAlmostEqual(phase(complex(0.0, INF)), pi / 2)
        self.assertAlmostEqual(phase(complex(-0.0, INF)), pi / 2)
        self.assertAlmostEqual(phase(complex(-2.3, INF)), pi / 2)
        self.assertAlmostEqual(phase(complex(-INF, INF)), 0.75 * pi)
        self.assertAlmostEqual(phase(complex(-INF, 2.3)), pi)
        self.assertAlmostEqual(phase(complex(-INF, 0.0)), pi)

        # real or imaginary part NaN
        for z in complex_nans:
            self.assert_(math.isnan(phase(z)))
Example #33
0
def table_to_hdu(table, character_as_bytes=False):
    """
    Convert an `~astropy.table.Table` object to a FITS
    `~astropy.io.fits.BinTableHDU`.

    Parameters
    ----------
    table : astropy.table.Table
        The table to convert.
    character_as_bytes : bool
        Whether to return bytes for string columns when accessed from the HDU.
        By default this is `False` and (unicode) strings are returned, but for
        large tables this may use up a lot of memory.

    Returns
    -------
    table_hdu : `~astropy.io.fits.BinTableHDU`
        The FITS binary table HDU.
    """
    # Avoid circular imports
    from .connect import is_column_keyword, REMOVE_KEYWORDS
    from .column import python_to_tdisp

    # Header to store Time related metadata
    hdr = None

    # Not all tables with mixin columns are supported
    if table.has_mixin_columns:
        # Import is done here, in order to avoid it at build time as erfa is not
        # yet available then.
        from astropy.table.column import BaseColumn
        from astropy.time import Time
        from astropy.units import Quantity
        from .fitstime import time_to_fits

        # Only those columns which are instances of BaseColumn, Quantity or Time can
        # be written
        unsupported_cols = table.columns.not_isinstance((BaseColumn, Quantity, Time))
        if unsupported_cols:
            unsupported_names = [col.info.name for col in unsupported_cols]
            raise ValueError(f'cannot write table with mixin column(s) '
                             f'{unsupported_names}')

        time_cols = table.columns.isinstance(Time)
        if time_cols:
            table, hdr = time_to_fits(table)

    # Create a new HDU object
    tarray = table.as_array()
    if isinstance(tarray, np.ma.MaskedArray):
        # Fill masked values carefully:
        # float column's default mask value needs to be Nan and
        # string column's default mask should be an empty string.
        # Note: getting the fill value for the structured array is
        # more reliable than for individual columns for string entries.
        # (no 'N/A' for a single-element string, where it should be 'N').
        default_fill_value = np.ma.default_fill_value(tarray.dtype)
        for colname, (coldtype, _) in tarray.dtype.fields.items():
            if np.all(tarray.fill_value[colname] == default_fill_value[colname]):
                if issubclass(coldtype.type, np.complexfloating):
                    tarray.fill_value[colname] = complex(np.nan, np.nan)
                elif issubclass(coldtype.type, np.inexact):
                    tarray.fill_value[colname] = np.nan
                elif issubclass(coldtype.type, np.character):
                    tarray.fill_value[colname] = ''

        # TODO: it might be better to construct the FITS table directly from
        # the Table columns, rather than go via a structured array.
        table_hdu = BinTableHDU.from_columns(tarray.filled(), header=hdr,
                                             character_as_bytes=character_as_bytes)
        for col in table_hdu.columns:
            # Binary FITS tables support TNULL *only* for integer data columns
            # TODO: Determine a schema for handling non-integer masked columns
            # with non-default fill values in FITS (if at all possible).
            int_formats = ('B', 'I', 'J', 'K')
            if not (col.format in int_formats or
                    col.format.p_format in int_formats):
                continue

            fill_value = tarray[col.name].fill_value
            col.null = fill_value.astype(int)
    else:
        table_hdu = BinTableHDU.from_columns(tarray, header=hdr,
                                             character_as_bytes=character_as_bytes)

    # Set units and format display for output HDU
    for col in table_hdu.columns:

        if table[col.name].info.format is not None:
            # check for boolean types, special format case
            logical = table[col.name].info.dtype == bool

            tdisp_format = python_to_tdisp(table[col.name].info.format,
                                           logical_dtype=logical)
            if tdisp_format is not None:
                col.disp = tdisp_format

        unit = table[col.name].unit
        if unit is not None:
            # Local imports to avoid importing units when it is not required,
            # e.g. for command-line scripts
            from astropy.units import Unit
            from astropy.units.format.fits import UnitScaleError
            try:
                col.unit = unit.to_string(format='fits')
            except UnitScaleError:
                scale = unit.scale
                raise UnitScaleError(
                    f"The column '{col.name}' could not be stored in FITS "
                    f"format because it has a scale '({str(scale)})' that "
                    f"is not recognized by the FITS standard. Either scale "
                    f"the data or change the units.")
            except ValueError:
                # Warn that the unit is lost, but let the details depend on
                # whether the column was serialized (because it was a
                # quantity), since then the unit can be recovered by astropy.
                warning = (
                    f"The unit '{unit.to_string()}' could not be saved in "
                    f"native FITS format ")
                if any('SerializedColumn' in item and 'name: '+col.name in item
                       for item in table.meta.get('comments', [])):
                    warning += (
                        "and hence will be lost to non-astropy fits readers. "
                        "Within astropy, the unit can roundtrip using QTable, "
                        "though one has to enable the unit before reading.")
                else:
                    warning += (
                        "and cannot be recovered in reading. If pyyaml is "
                        "installed, it can roundtrip within astropy by "
                        "using QTable both to write and read back, "
                        "though one has to enable the unit before reading.")
                warnings.warn(warning, AstropyUserWarning)

            else:
                # Try creating a Unit to issue a warning if the unit is not
                # FITS compliant
                Unit(col.unit, format='fits', parse_strict='warn')

    # Column-specific override keywords for coordinate columns
    coord_meta = table.meta.pop('__coordinate_columns__', {})
    for col_name, col_info in coord_meta.items():
        col = table_hdu.columns[col_name]
        # Set the column coordinate attributes from data saved earlier.
        # Note: have to set these, even if we have no data.
        for attr in 'coord_type', 'coord_unit':
            setattr(col, attr, col_info.get(attr, None))
        trpos = col_info.get('time_ref_pos', None)
        if trpos is not None:
            setattr(col, 'time_ref_pos', trpos)

    for key, value in table.meta.items():
        if is_column_keyword(key.upper()) or key.upper() in REMOVE_KEYWORDS:
            warnings.warn(
                f"Meta-data keyword {key} will be ignored since it conflicts "
                f"with a FITS reserved keyword", AstropyUserWarning)
            continue

        # Convert to FITS format
        if key == 'comments':
            key = 'comment'

        if isinstance(value, list):
            for item in value:
                try:
                    table_hdu.header.append((key, item))
                except ValueError:
                    warnings.warn(
                        f"Attribute `{key}` of type {type(value)} cannot be "
                        f"added to FITS Header - skipping", AstropyUserWarning)
        else:
            try:
                table_hdu.header[key] = value
            except ValueError:
                warnings.warn(
                    f"Attribute `{key}` of type {type(value)} cannot be "
                    f"added to FITS Header - skipping", AstropyUserWarning)
    return table_hdu
Example #34
0
# Token 0 -> Hola
# Token 1 -> ,
# Token 2-> Mundo
# Token 3 -> !

# ahora cambia el parseador, aceptando saludos con mas que una sola palabra antes que ','
saludo = Group(OneOrMore(Word(alphas))) + ',' + Word(alphas) + oneOf('! . ?')
tokens = saludo.parseString("Hasta mañana, Mundo !")

for i, token in enumerate(tokens):
    print("Token %d -> %s" % (i, token))

# Ahora parseamos algunas cadenas, usando el metodo runTests
saludo.runTests("""\
    Hola, Mundo!
    Hasta mañana, Mundo !
""",
                fullDump=False)

# Por supuesto, se pueden "reutilizar" gramáticas, por ejemplo:
numimag = Word(nums) + 'i'
numreal = Word(nums)
numcomplex = numreal + '+' + numimag
print(numcomplex.parseString("3+5i"))

# Cambiar a complejo numero durante parsear:
numcomplex.setParseAction(lambda t: complex(''.join(t).replace('i', 'j')))
print(numcomplex.parseString("3+5i"))

# Excelente!!, bueno, los dejo, me voy a seguir tirando código...
def hamiltonian_3nu_vacuum_energy_independent(s12,
                                              s23,
                                              s13,
                                              dCP,
                                              D21,
                                              D31,
                                              compute_matrix_multiplication=False
                                              ):
    r"""Returns the three-neutrino Hamiltonian for vacuum oscillations.

    Computes and returns the 3x3 complex three-neutrino Hamiltonian for
    oscillations in vacuum, parametrized by three mixing angles ---
    theta_12, theta_23, theta_13 --- one CP-violation phase --- delta_CP
    --- and two mass-squared difference --- Delta m^2_21, Delta m^2_31.
    The Hamiltonian is H = (1/2)*R.M2.R^dagger, with R the 3x3 PMNS
    matrix and M2 the mass matrix.  The multiplicative factor 1/E is not
    applied.

    Parameters
    ----------
    s12 : float
        Sin(theta_12).
    s23 : float
        Sin(theta_23).
    s13 : float
        Sin(theta_13).
    D21 : float
        Mass-squared difference Delta m^2_21.
    D31 : float
        Mass-squared difference Delta m^2_31.
    compute_matrix_multiplication : bool, optional
        If False (default), use the pre-computed expressions; otherwise,
        multiply R.M2.R^dagger live.

    Returns
    -------
    list
        Hamiltonian 3x3 matrix.
    """
    c12 = sqrt(1.0 - s12 * s12)
    c23 = sqrt(1.0 - s23 * s23)
    c13 = sqrt(1.0 - s13 * s13)

    f = 1. / 2.

    if not compute_matrix_multiplication:

        # All Hij have units of [eV^2]
        H00 = c13 * c13 * D21 * s12 * s12 + D31 * s13 * s13
        H01 = c12*c13*c23*D21*s12 + \
                c13*(D31-D21*s12*s12)*s13*s23*complex(cos(dCP),-sin(dCP))
        H02 = c13*c23*(D31-D21*s12*s12)*s13*complex(cos(dCP),-sin(dCP)) - \
                c12*c13*D21*s12*s23
        H10 = c12*c13*c23*D21*s12 + \
                c13*(D31-D21*s12*s12)*s13*s23*complex(cos(dCP),sin(dCP))
        H11 = c12*c12*c23*c23*D21 + (c13*c13*D31 + D21*s12*s12*s13*s13)*s23*s23 - \
                2.0*c12*c23*D21*s12*s13*s23*cos(dCP)
        H12 = c13*c13*c23*D31*s23 + \
                (c23*s12*s13*complex(cos(dCP),-sin(dCP)) + c12*s23) * \
                (-c12*c23*D21 + D21*s12*s13*s23*complex(cos(dCP),sin(dCP)))
        H20 = c13*c23*(D31-D21*s12*s12)*s13*complex(cos(dCP),sin(dCP)) - \
                c12*c13*D21*s12*s23
        H21 = c13*c13*c23*D31*s23 - \
                D21*(c23*s12*s13*complex(cos(dCP),sin(dCP)) + c12*s23) * \
                (c12*c23 - s12*s13*s23*complex(cos(dCP),-sin(dCP)))
        H22 = c23*c23*(c13*c13*D31 + D21*s12*s12*s13*s13) + c12*c12*D21*s23*s23 + \
                2.0*c12*c23*D21*s12*s13*s23*cos(dCP)

        H = [[H00 * f, H01 * f, H02 * f], [H10 * f, H11 * f, H12 * f],
             [H20 * f, H21 * f, H22 * f]]

    else:

        # PMNS matrix
        R = np.array(pmns_mixing_matrix(s12, s23, s13, dCP))
        # Mass matrix
        M2 = np.array([[0.0, 0.0, 0.0], [0.0, D21, 0.0], [0.0, 0.0, D31]])
        #scalar NSI matrix
        #N = np.array([[0.0,0.0,0.0], [0.0,np.sqrt(D31)*0.1,0.0], [0.0,0.0,0.0]])
        #H2 = list(f*np.matmul(R, np.matmul(N,np.conj(matrix.transpose(R)))))

        #M1=M2+N
        # Hamiltonian
        H = list(
            f * np.matmul(R, np.matmul(M2, np.conj(matrix.transpose(R))))
        )  #+np.array([[0.1,0.0,0.0], [0.0,0.1,0.0], [0.0,0.0,(f*D31*0.01)]])

    return H
Example #36
0
plt.xlabel('frequency [Hz]')
plt.ylabel('magnitude [dB]')
plt.xscale('log')


#%%
# this plots the raw values as they are stored in the trace
# TRACe:DATA
# the data are tuples of real and imag parts
# combine into complex array
# take abs value of complex and generate dB value with log10

freq = np.logspace(1, 4, len(disp_val))

real = raw_val[::2]
imag = raw_val[1::2]
comp = np.ndarray(len(real), dtype=complex)
for v in range(len(real)):
    comp[v] = complex(real[v], imag[v])
    
magn = np.log10(np.abs(comp))

plt.figure(figsize=(8,5))
plt.plot(freq, magn)
plt.grid()
plt.xlabel('frequency [Hz]')
plt.ylabel('magnitude [dB]')
plt.xscale('log')
#plt.savefig('Network_Analyzer_Capacitor.png', dpi=200)  # 200dpi -> 1600x1000

Example #37
0
a1 = '10'
b1 = int(a1, base=10)     # 将x转换为一个整数 base:进制
a2 = '101'
b2 = int(a2, 2)
a3 = '1234'
b3 = int(a3, 5)
a4 = '12334276'
b4 = int(a4, 8)
print(b1, b2, b3, b4)

a5 = 12
b5 = float(a5)      # 将x转换到一个浮点数
print(b5)   # 12.0

a6 = complex(1, 2)
print(a6)   # (1+2j)

a7 = "www"
b7 = str(a7)    # 将对象 x 转换为字符串  给用户看
print(b7)   # www
print(isinstance(b7, str))   # True

a8 = "www"
b8 = repr(a8)   # 将对象 x 转换为表达式字符串   给机器看
print(b8)   # 'www'
print(isinstance(b8, str))  # True


a9 = 7
b8 = eval('3 * a9')     # 用来简单计算在字符串中的有效Python表达式,并返回一个对象
Example #38
0
    def test_abs(self):
        # zeros
        for z in complex_zeros:
            self.assertEqual(abs(z), 0.0)

        # infinities
        for z in complex_infinities:
            self.assertEqual(abs(z), INF)

        # real or imaginary part NaN
        self.assertEqual(abs(complex(NAN, -INF)), INF)
        self.assert_(math.isnan(abs(complex(NAN, -2.3))))
        self.assert_(math.isnan(abs(complex(NAN, -0.0))))
        self.assert_(math.isnan(abs(complex(NAN, 0.0))))
        self.assert_(math.isnan(abs(complex(NAN, 2.3))))
        self.assertEqual(abs(complex(NAN, INF)), INF)
        self.assertEqual(abs(complex(-INF, NAN)), INF)
        self.assert_(math.isnan(abs(complex(-2.3, NAN))))
        self.assert_(math.isnan(abs(complex(-0.0, NAN))))
        self.assert_(math.isnan(abs(complex(0.0, NAN))))
        self.assert_(math.isnan(abs(complex(2.3, NAN))))
        self.assertEqual(abs(complex(INF, NAN)), INF)
        self.assert_(math.isnan(abs(complex(NAN, NAN))))

        # result overflows
        if float.__getformat__("double").startswith("IEEE"):
            self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308))
Example #39
0
    def test_specific_values(self):
        if not float.__getformat__("double").startswith("IEEE"):
            return

        def rect_complex(z):
            """Wrapped version of rect that accepts a complex number instead of
            two float arguments."""
            return cmath.rect(z.real, z.imag)

        def polar_complex(z):
            """Wrapped version of polar that returns a complex number instead of
            two floats."""
            return complex(*polar(z))

        for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
            arg = complex(ar, ai)
            expected = complex(er, ei)
            if fn == 'rect':
                function = rect_complex
            elif fn == 'polar':
                function = polar_complex
            else:
                function = getattr(cmath, fn)
            if 'divide-by-zero' in flags or 'invalid' in flags:
                try:
                    actual = function(arg)
                except ValueError:
                    continue
                else:
                    test_str = "%s: %s(complex(%r, %r))" % (id, fn, ar, ai)
                    self.fail('ValueError not raised in test %s' % test_str)

            if 'overflow' in flags:
                try:
                    actual = function(arg)
                except OverflowError:
                    continue
                else:
                    test_str = "%s: %s(complex(%r, %r))" % (id, fn, ar, ai)
                    self.fail('OverflowError not raised in test %s' % test_str)

            actual = function(arg)

            if 'ignore-real-sign' in flags:
                actual = complex(abs(actual.real), actual.imag)
                expected = complex(abs(expected.real), expected.imag)
            if 'ignore-imag-sign' in flags:
                actual = complex(actual.real, abs(actual.imag))
                expected = complex(expected.real, abs(expected.imag))

            # for the real part of the log function, we allow an
            # absolute error of up to 2e-15.
            if fn in ('log', 'log10'):
                real_abs_err = 2e-15
            else:
                real_abs_err = 5e-323

            if not (almostEqualF(
                    expected.real, actual.real, abs_err=real_abs_err)
                    and almostEqualF(expected.imag, actual.imag)):
                error_message = (
                    "%s: %s(complex(%r, %r))\n" % (id, fn, ar, ai) +
                    "Expected: complex(%r, %r)\n" %
                    (expected.real, expected.imag) +
                    "Received: complex(%r, %r)\n" %
                    (actual.real, actual.imag) +
                    "Received value insufficiently close to expected value.")
                self.fail(error_message)
Example #40
0
 def polar_complex(z):
     """Wrapped version of polar that returns a complex number instead of
     two floats."""
     return complex(*polar(z))
Example #41
0
# The complex() function returns a complex number by specifying a real number and an imaginary number.
# z = x + jy

x1 = 2
y1 = 3
x2 = 4
y2 = 5
print("complex(x1, y1):", complex(x1, y1))
print("complex(x2, y2):", complex(x2, y2))
print("complex(x1, y1) + complex(x2, y2):", complex(x1, y1) + complex(x2, y2))

print("complex(\"2+3j\") + complex(\"2-3j\"):",
      complex("2+3j") + complex("2-3j"))
"""
complex(x1, y1): (2+3j)
complex(x2, y2): (4+5j)
complex(x1, y1) + complex(x2, y2): (6+8j)
complex("2+3j") + complex("2-3j"): (4+0j)
"""
Example #42
0
from test.test_support import run_unittest
from test.test_math import parse_testfile, test_file
import unittest
import os, sys
import cmath, math
from cmath import phase, polar, rect, pi

INF = float('inf')
NAN = float('nan')

complex_zeros = [complex(x, y) for x in [0.0, -0.0] for y in [0.0, -0.0]]
complex_infinities = [
    complex(x, y) for x, y in [
        (INF, 0.0),  # 1st quadrant
        (INF, 2.3),
        (INF, INF),
        (2.3, INF),
        (0.0, INF),
        (-0.0, INF),  # 2nd quadrant
        (-2.3, INF),
        (-INF, INF),
        (-INF, 2.3),
        (-INF, 0.0),
        (-INF, -0.0),  # 3rd quadrant
        (-INF, -2.3),
        (-INF, -INF),
        (-2.3, -INF),
        (-0.0, -INF),
        (0.0, -INF),  # 4th quadrant
        (2.3, -INF),
        (INF, -INF),
Example #43
0
# 1. 아래 문자열의 길이를 구해보세요.
q1 = "dk2jd923i1jdk2jd93jfd92jd918943jfd8923"
print(len(q1))

# 2. print 함수를 사용해서 아래와 같이 출력해보세요.
#    apple;orange;banana;lemon
print('apple;orange;banana;lemon')

# 3. 화면에 * 기호 100개를 표시하세요.
print('*' * 100)

# 4. 문자열 "30" 을 각각 정수형, 실수형, 복소수형, 문자형으로 변환해보세요.
print(int('30'))
print(float('30'))
print(complex('30'))
print(str('30'))

# 5. 다음 문자열 "Niceman" 에서 "man" 문자열만 추출해보세요.
a = 'Niceman'
print(a[4:])

# 6. 다음 문자열을 거꾸로 출력해보세요. : "Strawberry"
a = 'Strawberry'
print(a[::-1])

# 7. 다음 문자열에서 '-'를 제거 후 출력하세요. : "010-7777-9999"
a = '010-7777-9999'
print(a.replace('-',' '))
#정규표현식
import re
Example #44
0
data = zeros([N, N], int)

# two arrays of N evenly spaced intervals from -2 to 2
xcoords = linspace(-2, 2, N)
ycoords = linspace(-2, 2, N)

# enumerate function: https://docs.python.org/3/library/functions.html#enumerate
# see also: https://docs.python.org/2.3/whatsnew/section-enumerate.html
# saves iterator value in u and v
# saves coordinate value in x and y
for butts, x in enumerate(xcoords):
    for craps, y in enumerate(ycoords):

        # two complex numbers used
        # c becomes the coordinates evaluated
        z = complex(0, 0)
        c = complex(x, y)

        # up to 100 iterations of calculation
        for iterations in range(max_iterations):

            # calculate from 0 and reuse in each iteration after
            z_prime = z**2 + c
            z = z_prime
            # if |z| is greater than 2, then you're done
            # save the number of iterations to the data map
            if abs(z) > 2.0:
                data[craps, butts] = iterations
                break

# output number of iterations on the grid
Example #45
0
print(type(x))
print(type(y))
print(type(z))

print('---------------------')

# dalam tipe data number kita bisa konversikan ke tipe yang lain
# kecuali tipe data complex tidak bisa diconvert ke tipe data yang lain

x = 1
y = 2.8
z = 1j

a = float(x)
b = int(y)
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

print('----------------------')

# ada juga build in fungsi yang sudah ada di python yang kita harus
# import dulu contohnya random()

import random
Example #46
0
def test_expressions():
    # Test expressions by wrapping them in an RX gate for convenience
    def _expr(expression, expected):
        parse_equals("RX(" + expression + ") 0", RX(expected, 0))

    # Decimals
    _expr("+123", 123)
    _expr("-123", -123)
    _expr("123.456", 123.456)
    _expr("+123.456", 123.456)
    _expr("-123.456", -123.456)

    # Exponential
    _expr("1e3", 1000.0)
    _expr("1.5e2", 150.0)
    _expr("3.5919865395417361e-05", 3.5919865395417361e-05)
    _expr("3.5919865395417361E-05", 3.5919865395417361e-05)

    # Complex
    _expr("123.456i", complex(0, 123.456))
    _expr("+123.456i", complex(0, 123.456))
    # Edge case: making the whole complex number negative makes the real part -0.0
    _expr("-123.456i", complex(-0., -123.456))
    _expr("777+123.456i", complex(777, 123.456))
    _expr("777-123.456i", complex(777, -123.456))
    _expr("+777-123.456i", complex(777, -123.456))

    # Imaginary
    _expr("i * 2", complex(0, 2))
    _expr("2i", complex(0, 2))
    _expr("1 ^ 2", 1)

    # Pi
    _expr("pi", np.pi)
    _expr("pi / 2", np.pi / 2)
    _expr("-pi / 2", np.pi / -2)

    # Expressions
    _expr("1+2", 3)
    _expr("1-2", -1)
    _expr("3*4", 12)
    _expr("6/2", 3.0)
    _expr("2^3", 8)

    # Order of operations
    _expr("3 + 6 * (5 + 4) / 3 - 7", 14.0)
    _expr("3 ^ 2 + 5", 14)

    # Functions
    _expr("sin(0)", 0.0)
    _expr("cos(0)", 1.0)
    _expr("sqrt(4)", 2.0)
    _expr("exp(0)", 1.0)
    _expr("cis(0)", complex(1, 0))

    # Unary precedence
    # https://github.com/rigetticomputing/pyquil/issues/246
    _expr("-3+4", 1)
    _expr("-(3+4)", -7)
    _expr("-(3-4)", 1)
    _expr("-0.1423778799706841+0.5434363975682295i",
          complex(-0.1423778799706841, 0.5434363975682295))
Example #47
0
def dampingTest5():
    a,b,c = complex(2.,2.),complex(2.,3.),1.
    res = ev.damping(a,b,c)
    check1 = str(res.real)=='-0.890659452156'
    check2 = str(res.imag)=='-0.59646815482'
    return check1 and check2
Example #48
0
def dampingTest6():
    a,b,c = complex(2.,2.),complex(2.,3.),complex(2.,4.)
    res = ev.damping(a,b,c)
    check1 = str(res.real)=='-0.506549632262'
    check2 = str(res.imag)=='-0.0185075645167'
    return check1 and check2
Example #49
0
def dampingTest3():
    a,b,c = 1.,complex(1.,1.),complex(1.,1.)
    res = ev.damping(a,b,c)
    check1 = str(res.real)=='-0.549342056734'
    check2 = str(res.imag)=='-0.227544930281'
    return check1 and check2
Example #50
0
def dampingTest4():
    a,b,c = complex(2.,2.),1.,1.
    res = ev.damping(a,b,c)
    check1 = str(res.real)=='-0.274671028367'
    check2 = str(res.imag)=='0.113772465141'
    return check1 and check2
Example #51
0
def angle_of_vector(vector):
    """
    Returns polar coordinate theta when vector is project on xy plane
    """
    return np.angle(complex(*vector[:2]))
Example #52
0
def dampingTest2():
    a,b,c = 1.,1.,complex(1.,1.)
    res = ev.damping(a,b,c)
    check1 = str(res.real)=='-0.388443493508'
    check2 = str(res.imag)=='0.160898563226'
    return check1 and check2
Example #53
0
# Title: 1a.py
# Purpose: To compute mean square error (MSE) vs. number of components (N) for the signal given in part 2b of EE 321's Project 3
# Developers: Siddesh Sood, Shawn Boyd, Cameron Palmer
# Last Modified: October 22, 2020

# Importing libraries
import numpy as np
import matplotlib.pyplot as plt
import math as m

# Defining constants
PI = np.pi  # Pi
j = complex(0, 1)  # A complex number
e = m.e
T = 2  # Period between pulses
OMEGA = (2 * PI) / T

# How many components to create and sum (a large number)
N = 100

# Create an independent variable t to fit exactly one period T
indep_var = np.array(np.arange(0, T, 0.01).tolist())

# An array of Ns. Set NMax to the maximum number of Ns you want your signals to go to
NMax = 1000
NArray = np.array(np.arange(10, NMax, 10).tolist())

# Create the variable that will hold all signals
signals = np.zeros((len(indep_var), len(NArray) + 1))

signals[:,
Example #54
0
def parallel_to_serial(z: complex) -> complex:
    """Convert parallel impedance to serial impedance equivalent"""
    z_sq_sum = z.real**2 + z.imag**2
    # TODO: Fix divide by zero
    return complex(z.real * z.imag**2 / z_sq_sum,
                   z.real**2 * z.imag / z_sq_sum)
Example #55
0
import cmath
a = float(input('请输入一个实数字:'))
b = float(input('请输入一个虚数字:'))
num_sqrt = cmath.sqrt(complex(a, b))
print('{0:0.3f}+{1:0.3f}j的平方根为 {2:0.3f}+{3:0.3f}j'.format(
    a, b, num_sqrt.real, num_sqrt.imag))
#求复数的平方根
Example #56
0
 def z(self) -> complex:
     """ return the s value complex number """
     return complex(self.re, self.im)
Example #57
0
import matplotlib.cm as cm

def iter_count(C, max_iter):
	X = C
	for n in range(max_iter):
		if abs(X) > 2.:
			return n
		X = X ** 2 + C
	return max_iter

N = 512
max_iter = 64
xmin, xmax, ymin, ymax = -2.2, .8, -1.5, 1.5
X = numpy.linspace(xmin, xmax, N)
Y = numpy.linspace(ymin, ymax, N)
Z = numpy.empty((N, N))

for i, y in enumerate(Y):
	for j, x in enumerate(X):
		Z[i, j] = iter_count(complex(x, y), max_iter)

plot.imshow(Z,
            cmap = cm.binary,
            interpolation = 'bicubic',
            extent=(xmin, xmax, ymin, ymax))

cb = plot.colorbar(orientation='horizontal', shrink=.75)
cb.set_label('iteration count')

plot.show()
Example #58
0
a = 3.14e10
b = 5
print(int(a))
print(complex(a))
print(complex(a,b))
print(float(b))
print(a ** -2)
print(float(a))
print(b ** -2)

print(8/5)
print(8//5)
print(int(8/5))
print(4/2)
print(8.0//5)
print(8//5.0)

print("我叫%s今年%d岁"%('小明',12))
print('hello'.capitalize())
print(max('hello'))
Example #59
0
 def phase(a, b):
     ap = a.pos
     bp = b.pos
     phase = -B * (0.5 * (ap[1] + bp[1]) * (bp[0] - ap[0]))
     return -complex(cos(phase), sin(phase))
Example #60
0
# c)Complex
c = 6 + 9j
print(type(c))

#Convert float to int
a = 5.6
b = int(a)
print(type(b))
print(b)

#Convert int to float
print(float(b))

#Convert to complex
k = 6
print(complex(b,k))

#d) boolean(they are placed in numeric because true is 1 and false is 0)
t = b<k
print(t)
f = b>k
print(f)
#boolean convert to int.
print(int(t))
print(int(f))


# ----------------------------------------------------------------------------------------------- #
# 3) Sequence
			#list
			#set