Esempio n. 1
0
def write_BP_files(raw_cal,fit_cal,filename='test'):
    from cmath import phase
    n_bands = 24
    n_tiles = 128
    flagged_channels = [0,1,16,30,31]
    bp_freqs = "0.080000, 0.120000, 0.160000, 0.200000, 0.240000, 0.280000, 0.320000, 0.360000, 0.400000, 0.440000, 0.480000, 0.520000, 0.560000, 0.600000, 0.680000, 0.720000, 0.760000, 0.800000, 0.840000, 0.880000, 0.920000, 0.960000, 1.000000, 1.040000, 1.080000, 1.120000, 1.160000\n"
    for n in range(raw_cal.n_bands):
        band_file = 'Bandpass_' + filename + '%03d.dat' % (n+1)
        fp = open(band_file,'w+')
        fp.write(bp_freqs)
        for i in range(n_tiles):
            if(raw_cal.antennas[i] is not None):
                if(raw_cal.antennas[i].BP_jones[n] is not None):
                    for pol1 in [0,1]:
                        for pol2 in [0,1]:
                            fp.write('%d' % (i+1))
                            for ch_n,ch in enumerate(raw_cal.antennas[i].BP_jones[n]):
                                if(ch_n not in flagged_channels):
                                    fp.write(', %f, %f' % (abs(ch[pol1,pol2]), phase(ch[pol1,pol2])))
                            fp.write('\n')
                            fp.write('%d' % (i+1))
                            for ch_n,ch in enumerate(fit_cal.antennas[i].BP_jones[n]):
                                if(ch_n not in flagged_channels):
                                    fp.write(', %f, %f' % (abs(ch[pol1,pol2]), phase(ch[pol1,pol2])))
                            fp.write('\n')
                    
        fp.close()
Esempio n. 2
0
def angle_between(a, b):
    a_phase = phase(a)
    b_phase = phase(b)
    angle = abs(a_phase - b_phase)
    while angle > pi:
        angle -= pi
    return angle
Esempio n. 3
0
 def publish_scan(self):
     if self.scan_pub: 
         self.scan_data.header.seq += 1
         self.scan_data.header.stamp = rospy.Time.now()
         self.scan_data.ranges = [self.scan_data.range_max + 1.0] * int((self.scan_data.angle_max-self.scan_data.angle_min)/self.scan_data.angle_increment + 1)
         scan_lines = []
         angle = self.scan_data.angle_min
         while angle <= self.scan_data.angle_max:
             scan_dir = self.orientation + angle
             scan_line = shapely.geometry.LineString([(self.pos.x+self.scan_data.range_min*math.cos(scan_dir), self.pos.y+self.scan_data.range_min*math.sin(scan_dir)),
                                                      (self.pos.x+self.scan_data.range_max*math.cos(scan_dir), self.pos.y+self.scan_data.range_max*math.sin(scan_dir))])
             scan_lines.append(scan_line)
             angle += self.scan_data.angle_increment
         scan_sector = shapely.geometry.MultiLineString(scan_lines)
         effective_scene = self.warehouse.scene.intersection(self.pos.buffer(self.scan_data.range_max*1.27, 6))
         intersection = scan_sector.intersection(effective_scene)
         if isinstance(intersection, shapely.geometry.Point) or isinstance(intersection, shapely.geometry.LineString):
             intersection = [intersection]
         for geom in intersection:
             if isinstance(geom, shapely.geometry.Point):
                 i = int((cmath.phase(complex(geom.x, geom.y)) - self.orientation + self.scan_data.angle_min)/self.scan_data.angle_increment)
                 if geom.distance(self.pos) < self.scan_data.ranges[i]:
                     self.scan_data.ranges[i] = geom.distance(self.pos)
             elif isinstance(geom, shapely.geometry.LineString):
                 for point in shapely.geometry.MultiPoint(list(geom.coords)):
                     i = int((cmath.phase(complex(point.x, point.y)) - self.orientation + self.scan_data.angle_min)/self.scan_data.angle_increment)
                     if point.distance(self.pos) < self.scan_data.ranges[i]:
                         self.scan_data.ranges[i] = point.distance(self.pos)
         self.scan_pub.publish(self.scan_data)
Esempio n. 4
0
  def from_unitary(self,V):
    '''Calculate the Reck scheme (circuit) parameters from an
existing unitary matrix
V      : unitary matrix
return : None'''
    U=V.copy()
    for i in range(self.dim-1):
      # Reverse the i-th diagonal
      for j in range(self.dim-1,i,-1):
        # Reverse the j-th element in that diagonal
        # Phase shift on mode j-1
        z=U[j-1,i]/U[j,i]
        self.params[j,i]=cmath.phase(z)
        phi=z.conjugate()/abs(z)
        U[j-1,:]*=phi
        # MZI on modes j-1,j
        r=abs2(U[j-1,i])/(abs2(U[j-1,i])+abs2(U[j,i])) # Power reflectivity
        self.params[i,j]=2*numpy.arcsin(numpy.sqrt(r))
        phi=numpy.exp(-0.5j*(self.params[i,j]+numpy.pi))
        t=phi*numpy.sqrt(1-r)  # Amplitude transmission
        r=phi*numpy.sqrt(r)    # Amplitude reflection
        U[j-1,:],U[j,:]=r*U[j-1,:]+t*U[j,:], t*U[j-1,:]-r*U[j,:]
    for i in range(self.dim):
      # Reverse input phases
      self.params[i,i]=cmath.phase(U[i,i])
      U[i,i]=abs(U[i,i])
Esempio n. 5
0
    def test_perp(self):
        from cmath import phase

        two_pi = 2 * math.pi
        half_pi = math.pi / 2

        def wrap_angle(a):
            """Wrap an angle so that it is between -pi and pi."""
            while a > math.pi:
                a -= two_pi
            while a < -math.pi:
                a += two_pi
            return a

        self.assertEqual(perp((1, 2)), (-2, 1))
        for v in test_vectors:
            if len(v) != 2:
                continue
            p = perp(v)
            self.assertAlmostEqual(angle(v, p), half_pi)
            self.assertEqual(dot(v, p), 0)

            av = phase(complex(*v))
            ap = phase(complex(*p))
            self.assertAlmostEqual(wrap_angle(av - ap), -half_pi)
            self.assertAlmostEqual(wrap_angle(ap - av), half_pi)
Esempio n. 6
0
def deconstruct_single_qubit_matrix_into_angles(
        mat: np.ndarray) -> Tuple[float, float, float]:
    """Breaks down a 2x2 unitary into more useful ZYZ angle parameters.

    Args:
        mat: The 2x2 unitary matrix to break down.

    Returns:
        A tuple containing the amount to phase around Z, then rotate around Y,
        then phase around Z (all in radians).
    """
    # Anti-cancel left-vs-right phase along top row.
    right_phase = cmath.phase(mat[0, 1] * np.conj(mat[0, 0])) + math.pi
    mat = np.dot(mat, _phase_matrix(-right_phase))

    # Cancel top-vs-bottom phase along left column.
    bottom_phase = cmath.phase(mat[1, 0] * np.conj(mat[0, 0]))
    mat = np.dot(_phase_matrix(-bottom_phase), mat)

    # Lined up for a rotation. Clear the off-diagonal cells with one.
    rotation = math.atan2(abs(mat[1, 0]), abs(mat[0, 0]))
    mat = np.dot(_rotation_matrix(-rotation), mat)

    # Cancel top-left-vs-bottom-right phase.
    diagonal_phase = cmath.phase(mat[1, 1] * np.conj(mat[0, 0]))

    # Note: Ignoring global phase.
    return right_phase + diagonal_phase, rotation * 2, bottom_phase
Esempio n. 7
0
def test_mod_cpm():
    tb = gr.top_block()
    precode = mlse.xor_encode_bb()
    nrz = gr.map_bb([1,-1])
    mod = gr.gmskmod_bc(1,0.3,4)
    #src = gr.vector_source_b([0,0,0,0,1,1,1,1,0,0])
    #src = gr.vector_source_b([1,1,0,0,1,0,0,1,1,1,0,0,0,0])
    src = gr.vector_source_b((1,)*1000)
    sink = gr.vector_sink_c()
    derot = mlse.derotate_cc(1,4)
    tb.connect(src, precode, nrz, mod, derot, sink)
    precode_probe = gr.vector_sink_b()
    tb.connect(nrz, precode_probe)
    tb.run()
    d = sink.data()
    from cmath import phase, pi, rect
    real = lambda x: x.real
    import operator
    d_r = d#list(decimate(d,5,2))
    d2 = [ int(round((phase(i)/pi)*100)) for i in d ]
    derotate = [ (-1j)**(i+1) for i in range(len(d_r))]
    d3 = map(operator.mul, d_r, derotate)
#    print "\n".join(map(str,map(real,d3)))
    print precode_probe.data()
#    print "\n".join(map(str,map(phase,d)))
    print "\n".join([str(phase(i)/pi) for i in d])
    print len(d)
    print derotate
    def testDrift(self):
        """ This was a test case to test the oscilator error due to floating point accumulation errors
            we pass in all "ones" with no filtering or decimation to just get out the tuner value.  
            Then we measure that the magnitude of the tunner stays near one and that it maintains minimal phase errors
        """
        fs= 100e3
        freq = 12345.6789
        self.setProps(TuneMode="IF", TuningIF=freq,FilterBW=100.0e3, DesiredOutputRate=100.0e3)
        #sig = genSinWave(fs, freq, 1024*1024)
        sig = [1]*5000000
 
        out = self.main(sig,sampleRate=fs, complexData=False)
        
        self.assertTrue(len(out)>0)
        print "got %s out" %len(out)
        #print out[200]
        outSteadyState = out[500:]
        #check for phase errors
        tuner = outSteadyState[0]
        dPhase = -2*math.pi*freq/fs
        phase = cmath.phase(outSteadyState[0])
        for i, val in enumerate(outSteadyState):
            #print phase, val
            valPhase = cmath.phase(val)
            #check for plus/minus pi ambiguity here
            if valPhase <-3.1 and phase > 3.1:
               valPhase+= 2*math.pi
            elif valPhase >3.1 and phase < -3.1:
                phase+=2*math.pi
            self.assertAlmostEqual(phase, valPhase, 2)
            phase=valPhase+dPhase
            if phase<-math.pi:
                phase+=2*math.pi
        #check for magnitude errors - the abs of each output should be approximately one
        self.assertTrue(all([abs(abs(x)-1.0) <1e-3 for x in outSteadyState]))
Esempio n. 9
0
def periods_relative_sign(p_1, p_2):
    """
    This function determines the relative sign between 
    two numerically computed periods. 
    It also checks that they are reasonably similar, 
    it will print a message to warn if they aren't, 
    but it will let the code go on nevertheless.
    """
    trouble = ' '
    sign = 1.0

    if -1.0 * pi / 4.0 < phase(p_1 / p_2) < 1.0 * pi / 4.0:
        sign = 1.0
    elif 3.0 * pi / 4.0 < phase(p_1 / p_2) <= pi or \
       -1.0 * pi <= phase(p_1 / p_2) < -3.0 * pi / 4.0:
       sign = -1.0
    else:
        trouble += ' phase discrepancy too large, '

    if 0.5 < abs(p_1) / abs(p_2) < 2.0:
        pass
    else:
        trouble += ' modulus discrepancy too large '

    if trouble != ' ':
        logging.info('\
            \nWARNING: could not reliably determine the positive period, \
            \ndue to: {}'.format(trouble))

    return sign
Esempio n. 10
0
def get_phase_diff(target_freq, fs, a, b):
    # sample rate (Hz)
    sample_rate = fs

    # Highest frequency captured - limited by sample rate (Hz)
    high_freq_bound = sample_rate / 2

    # Number samples (bins)
    sample_number = len(a)

    # Signal freq held in each index of arrays (Hz/bin)
    scale = sample_rate / sample_number

    # Index of arrays for complex number we want (bin)
    index = target_freq / scale

    # Update target frequency to one that matches scale of fft
    target_freq = scale * index

    # Getting our phases (radians)
    a_phase = phase(fft(a)[index])
    b_phase = phase(fft(b)[index])
    b_phase = relative_wraparound(a_phase, b_phase)
    print("a_phase = %f pi radians" % (a_phase / math.pi))
    print("b_phase = %f pi radians" % (b_phase / math.pi))

    # Compute phase difference
    phase_diff = b_phase - a_phase
    print("b leads a by %fpi radians" % (phase_diff / math.pi))

    return phase_diff
Esempio n. 11
0
def place_tiles_along_line(start, L, slopes, crossings, coords):

    m = slopes[L[0]]
    v = I * complex(1, m) # positive normal to (direction vector for L with positive x coord).   
    v = v / abs(v)        # make that a unit normal

    direction = 1
    if(m < -eps):  # if slope is negative, do everything backwards.
        direction = -1
        crossings.reverse()

    e1 = (start, start + v)

    for L2 in crossings:
        m2 = slopes[L2[0]]
        w = I * complex(1,m2) #again a unit normal to L2
        w = w / abs(w)
        # Is w the right orientation?  Suppose first direction = 1.  
        # Then w should be on the "positive" side of v.
        # So we should have Arg v - pi < Arg w < Arg v.
        # That's the same as 0 < Arg v - Arg w, because of where the branch cut of arg is. 
        # 
        # If direction = -1, though, then w should be on the negative side of v.
        if 0 > direction * (cmath.phase(v) - cmath.phase(w)):
            w = -w

        e2 = (e1[0] + w, e1[1] + w)
        coords[(L, L2)] = (e1, e2)
        e1 = e2 
Esempio n. 12
0
        def corner(self, v1, v2, xy):
            s = v1 + v2 # vector at mid angle - centre of arc lies on this line
            s /= abs(s) # unit vector
            angle = cmath.phase(s) - cmath.phase(v1)
            d = abs(radius / math.tan(angle)) # distance to start of arc from vertex
            v1 *= d
            v2 *= d
            # distance along s vector to centre of arc
            h = abs(complex(radius, d))
            s *= h

            v0 = s + xy # centre of arc
            va = v1 - s # vectors to cut points
            vb = v2 - s
            # angles to cut points from arc centre
            a0, a1 = [ degrees(cmath.phase(v)) for v in [ va, vb ] ]
            # add the arc
            if normalise_angle(a1 - a0) > 180:
                a0, a1 = a1, a0
            if inside:
                a0, a1 = a1, a0
            c = Arc((v0.real, v0.imag), radius, a0, a1)
            self.parent.add(c)

            # return end points of polygon
            return v1 + xy, v2 + xy
def main():
  z = input()  # seems to auto detect complex numbers
  # convert complex number to polar coordinate. polar coordinate consists of
  # phi, the phase angle
  # r, the modulus

  print abs(z)
  print cmath.phase(z) 
Esempio n. 14
0
 def contraint(self, load, target):
     gl = z_to_gamma(load)
     gt = z_to_gamma(target)
     pl = cmath.phase(gl)
     pt = cmath.phase(gt)
     if pt > pl:
         pt -= 2 * math.pi
     self.set_property("normval", (pt - pl)/(-4*math.pi))
     return gamma_to_z(cmath.rect(abs(gl), cmath.phase(gt)))
 def new_arc(self, s, e, layer='gearteeth', r=None, color = 0):
     if r == None:
         r = abs(s)    
     sa = phase(s)
     ea = phase(e)
     return dxf.arc(radius = r,
                    startangle=degrees(sa),
                    endangle=degrees(ea),
                    layer = layer, thickness=0.0)
def define_sector(m, position):
    cur_phase = phase(m[-1][0]) - 2 * pi
    for i in range(len(m)):
        prev_phase = cur_phase
        cur_phase = phase(m[i][0])
        if min(prev_phase, cur_phase) < phase(position) <= max(prev_phase, cur_phase):
            # position does not lie between i-1-th and i-th points of m
            return i
    raise AssertionError("phase(%s) = %f was not found anywhere in the m" % (str(position), phase(position)))
Esempio n. 17
0
def realBorder(U):
  for i in range(4):
    phi = cmath.phase(U[i,0])
    U[i,0] *= np.exp(complex(0,-phi))
    U[i,1] *= np.exp(complex(0,-phi))
  phi = cmath.phase(U[0,1])
  for i in range(4):
    U[i,1] *= np.exp(complex(0,-phi))
  return U
Esempio n. 18
0
def color(x, y, z, phi):

    x_phase = math.pi*2*phi
    r_phase = cmath.phase(complex(x, y)) + x_phase*7
    g_phase = cmath.phase(complex(y, z)) + x_phase*8
    b_phase = cmath.phase(complex(z, x)) + x_phase*9

    r, g, b = ( (math.sin(x)+1.)/2. for x in (r_phase, g_phase, b_phase) )

    return int(r**2 *255),int(g**2 *255),int(b**2 *255)
Esempio n. 19
0
 def publish_vision(self):
     if self.vision_pub:
         vision = warehouse_simulator.msg.AbstractVision()
         vision.header.stamp = rospy.Time.now()
         for gate in self.warehouse.gates:
             pos_rel = shapely.affinity.rotate(gate.centroid, -self.orientation, self.pos, use_radians=True)
             z = complex(pos_rel.x - self.pos.x, pos_rel.y - self.pos.y)
             if abs(cmath.phase(z)) <= self.robot_description['vision_angle'] and abs(z) <= self.robot_description['vision_range']:
                 vision.direction.append(cmath.phase(z))
                 vision.dist.append(abs(z))
                 vision.type.append(0)
                 vision.orientation.append(gate.orientation - self.orientation)
                 vision.uid.append(gate.uid)
         for robot in self.warehouse.robots:
             #TODO exclude self
             pos_rel = shapely.affinity.rotate(robot.pos, -self.orientation, self.pos, use_radians=True)
             z = complex(pos_rel.x - self.pos.x, pos_rel.y - self.pos.y)
             if abs(cmath.phase(z)) <= self.robot_description['vision_angle'] and abs(z) <= self.robot_description['vision_range']:
                 vision.direction.append(cmath.phase(z))
                 vision.dist.append(abs(z))
                 vision.type.append(1)
                 vision.orientation.append(robot.orientation - self.orientation)
                 vision.uid.append(robot.uid)
                 if robot.carry:
                     vision.direction.append(cmath.phase(z))
                     vision.dist.append(abs(z))
                     vision.type.append(2)
                     vision.orientation.append(robot.orientation - self.orientation)
                     vision.uid.append(robot.carry.uid)
         for item in self.warehouse.items:
             pos_rel = shapely.affinity.rotate(item.pos, -self.orientation, self.pos, use_radians=True)
             z = complex(pos_rel.x - self.pos.x, pos_rel.y - self.pos.y)
             if abs(cmath.phase(z)) <= self.robot_description['vision_angle'] and abs(z) <= self.robot_description['vision_range']:
                 vision.direction.append(cmath.phase(z))
                 vision.dist.append(abs(z))
                 vision.type.append(2)
                 vision.orientation.append(item.orientation - self.orientation)
                 vision.uid.append(item.uid)
         for shelf in self.warehouse.shelves:
             pos_rel = shapely.affinity.rotate(shelf.pos, -self.orientation, self.pos, use_radians=True)
             z = complex(pos_rel.x - self.pos.x, pos_rel.y - self.pos.y)
             if abs(cmath.phase(z)) <= self.robot_description['vision_angle'] and abs(z) <= self.robot_description['vision_range']:
                 vision.direction.append(cmath.phase(z))
                 vision.dist.append(abs(z))
                 vision.type.append(3)
                 vision.orientation.append(shelf.orientation - self.orientation)
                 vision.uid.append(shelf.uid)
                 for item in shelf.carry:
                     if item:
                         vision.direction.append(cmath.phase(z))
                         vision.dist.append(abs(z))
                         vision.type.append(2)
                         vision.orientation.append(shelf.orientation - self.orientation)
                         vision.uid.append(item.uid)
         self.vision_pub.publish(vision)
Esempio n. 20
0
    def calc_ang_pot(self,A,B,Pr,Vr):
        absA = abs(A)
        alfa = cm.phase(A)
        absB = abs(B)
        beta = cm.phase(B)

        ang_pot = (beta - np.arccos((Pr + absA*np.power(Vr,2)/absB*np.cos(beta-alfa))/(self.U1*Vr/absB)))
        ang_pot = (np.degrees(ang_pot))
        #print(ang_pot)

        return ang_pot
Esempio n. 21
0
    def range(self, load, target):
        gl = z_to_gamma(load)
        gt = z_to_gamma(target)

        pl = cmath.phase(gl)
        pt = cmath.phase(gt)
        if pt > pl:
            pt -= 2 * math.pi

        for phase in ranges.lin(pl, pt):
            yield gamma_to_z(cmath.rect(abs(gl), phase))
Esempio n. 22
0
 def getPhase(self):
     """
     Method to get the phase difference between the two componets of 
     the current JonesVector as a float in the range -pi -> pi
     returns phase as a float.
     """
     delta = cmath.phase(self.y) - cmath.phase(self.x)
     if delta > math.pi :
         delta -= 2*math.pi
     if delta < -math.pi:
         delta += 2*math.pi
     return delta
Esempio n. 23
0
def load_data(file = "H4/Tagged_Training_07_26_1343286001.mat"):
    ''' Load the .mat files. '''
    taggingData = io.loadmat(file, struct_as_record=False, squeeze_me=True)
    #taggingInfoData = io.loadmat('data/H4/AllTaggingInfo.mat', struct_as_record=False, squeeze_me=True)

    # Extract tables
    buf = taggingData['Buffer']
#    pdb.set_trace()
    d = DataStore()
    LF1V = buf.LF1V
    LF1I = buf.LF1I
    LF2V = buf.LF2V
    LF2I = buf.LF2I

    # L1 and L2 time ticks occur every 0.166s.
    d.L1_TimeTicks = buf.TimeTicks1
    d.L2_TimeTicks = buf.TimeTicks2
    d.HF            = buf.HF
                             
    d.HF_TimeTicks = buf.TimeTicksHF
    
    if hasattr(buf, 'TaggingInfo'):
        d.taggingInfo = buf.TaggingInfo
        d.tags = make_tags(d.taggingInfo)
     
    # Calculate power by convolution
    L1_P = LF1V * LF1I.conjugate()
    L2_P = LF2V * LF2I.conjugate()
    
    L1_ComplexPower = L1_P.sum(axis=1)
    L2_ComplexPower = L2_P.sum(axis=1)
    
    # Extract components
    d.L1_Real = L1_ComplexPower.real
    d.L1_Imag = L1_ComplexPower.imag
    L1_App  = abs(L1_ComplexPower)
    d.L2_Real = L2_ComplexPower.real
    d.L2_Imag = L2_ComplexPower.imag
    L2_App  = abs(L2_ComplexPower)

    L1_Pf = [cos(phase(L1_P[i,0])) for i in range(len(L1_P[:,0]))]
    L2_Pf = [cos(phase(L2_P[i,0])) for i in range(len(L2_P[:,0]))]
    d.L1_Pf = np.array(L1_Pf,dtype='float64')
    d.L2_Pf = np.array(L2_Pf,dtype='float64')

    d.start = d.L1_TimeTicks[0]
    d.end = d.L1_TimeTicks[-1]

    print("start: ")
    print(date_str(d.start))
    print("end : ")
    print(date_str(d.end))
    return d
Esempio n. 24
0
def convertTrainingData(filepathin, filepathout):

    taggingData = io.loadmat(filepathin, struct_as_record=False, squeeze_me=True)

    # Extract tables
    buf = taggingData['Buffer']
    LF1V = buf.LF1V
    LF1I = buf.LF1I
    LF2V = buf.LF2V
    LF2I = buf.LF2I
    L1_TimeTicks = buf.TimeTicks1
    L2_TimeTicks = buf.TimeTicks2
    HF = buf.HF
                         
    HF_TimeTicks = buf.TimeTicksHF

    taggingInfo = buf.TaggingInfo

    # Calculate power (by convolution)
    L1_P = LF1V * LF1I.conjugate()
    L2_P = LF2V * LF2I.conjugate()
    L1_ComplexPower = L1_P.sum(axis=1) 
    L2_ComplexPower = L2_P.sum(axis=1)

    # Extract components
    L1_Real = L1_ComplexPower.real
    L1_Imag = L1_ComplexPower.imag
    L1_App  = abs(L1_ComplexPower)
    L2_Real = L2_ComplexPower.real
    L2_Imag = L2_ComplexPower.imag
    L2_App  = abs(L2_ComplexPower)
    #
    L1_Pf = [cos(phase(L1_P[i,0])) for i in range(len(L1_P[:,0]))]
    L2_Pf = [cos(phase(L2_P[i,0])) for i in range(len(L2_P[:,0]))]
    L1_Pf = np.array(L1_Pf,dtype='float64')
    L2_Pf = np.array(L2_Pf,dtype='float64')

    f = file(filepathout, "wb")
    #np.save(f, HF)
    #np.save(f, HF_TimeTicks)
    np.save(f, taggingInfo)
    np.save(f, L1_TimeTicks)
    np.save(f, L1_Real)
    np.save(f, L1_Imag)
    np.save(f, L1_App)
    np.save(f, L1_Pf)
    np.save(f, L2_TimeTicks)
    np.save(f, L2_Real)
    np.save(f, L2_Imag)
    np.save(f, L2_App)
    np.save(f, L2_Pf)

    f.close()
Esempio n. 25
0
def realBorder(U):
  '''Real-bordered form of a unitary matrix
U      : arbitrary (normally unitary) matrix
return : real-bordered form of U'''
  for i in range(4):
    phi = cmath.phase(U[i,0])
    U[i,0] *= np.exp(complex(0,-phi))
    U[i,1] *= np.exp(complex(0,-phi))
  phi = cmath.phase(U[0,1])
  for i in range(4):
    U[i,1] *= np.exp(complex(0,-phi))
  return U
Esempio n. 26
0
 def get_freq(self, data):
     freqs = []
     for r1, r2 in zip(data[:-1], data[1:]):
         diff = cmath.phase(r1) - cmath.phase(r2)
         if diff > math.pi:
             diff -= 2*math.pi
         if diff < -math.pi:
             diff += 2*math.pi
         freqs.append(diff)
     freq = float(sum(freqs)) / len(freqs)
     freq /= 2*math.pi
     return freq
Esempio n. 27
0
def calculate_heading(target_freq, fs, a, b):
    """
    Takes a pair of signal vs. time data "a" and "b", and computes an angle
    pointing towards the signal source relative to the "b" direction.
    Args:
        target_freq: frequency of signal emitted by source
        fs: Sampling frequency used to capture signals "a" and  "b"
        a: numpy array of sinusoidal signal data for channel a
        b: numpy array of sinusoidal signal data for channel b

    Notes: "One important parameter is the physical distance between
    the two elements used to capture the signal data in the first place.
    Rather than pass it in as an argument, it's more reasonable to
    hard code a constant. To change this constant, simple change the
    "d" constant used in the phase_diff_to_x_and_y function.
    """

    # sample rate (Hz)
    sample_rate = fs

    # Highest frequency captured - limited by sample rate (Hz)
    high_freq_bound = sample_rate / 2

    # Number samples (bins)
    sample_number = len(a)

    # Signal freq held in each index of arrays (Hz/bin)
    scale = sample_rate / sample_number

    # Index of arrays for complex number we want (bin)
    index = target_freq / scale

    # Update target frequency to one that matches scale of fft
    target_freq = scale * index

    # Getting our phases (radians)
    a_phase = phase(fft(a)[index])
    b_phase = phase(fft(b)[index])
    b_phase = relative_wraparound(a_phase, b_phase)
    print("a_phase = %f pi radians" % (a_phase / math.pi))
    print("b_phase = %f pi radians" % (b_phase / math.pi))

    # Compute phase difference
    phase_diff = a_phase - b_phase
    print("a leads b by %fpi radians" % (phase_diff / math.pi))

    # Get proportional x and y components (meters)
    (y, x) = phase_diff_to_x_and_y(phase_diff, target_freq)
    print("x=%f meters and y=%f meters." % (x, y))

    # Calculate and return heading using tan-1(y/x)
    return math.atan2(y, x) * 180 / math.pi
def plot_transimpedance_difference_paperPlotter_phase(results):
    plt.clf()
    lib.plot.formatter.plot_params['margin']['bottom'] = 0.20
    lib.plot.formatter.plot_params['margin']['top'] = 0.05
    lib.plot.formatter.plot_params['margin']['left'] = 0.12
    lib.plot.formatter.plot_params['margin']['right'] = 0.01
    lib.plot.formatter.format(style='Thesis')
    ax1 = plt.subplot()
    locator = matplotlib.ticker.IndexLocator(1, 0)
    xticks = []
    for i, measurement in enumerate(results):
        stim = str(measurement.stim)
        meas = str(measurement.meas)
        if stim[0] not in meas and stim[1] not in meas:
            xticks.append(str(measurement.stim) + ',' + str(measurement.meas))

    for (ax, mode) in [(ax1, 'mag')]:
        xs = []
        ys = []
        ys2 = []
        count = 0
        for i, measurement in enumerate(results):
            stim = str(measurement.stim)
            meas = str(measurement.meas)
            if stim[0] not in meas and stim[1] not in meas:
                count += 1
                xs.append(count)
                ys.append(conditionPhase(cmath.phase(measurement.result_sim)))
                ys2.append(conditionPhase(cmath.phase(measurement.result_meas)))

        ax.plot(xs, ys2, color='blue', label='Measured', mec='blue', marker='o', markersize=4)
        ax.plot(xs, ys, color='red', label='Simulated')
        ax.set_xticklabels(xticks)
        print ys2
        ax.xaxis.set_major_locator(locator)
    plt.gcf().subplots_adjust(hspace=0.1)
#    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.xticks(rotation=90)
    #ax1.set_ylim(-90,90)
    plt.yticks([-90,-45,0,45,90])
    formy = plt.ScalarFormatter()
    formy.set_scientific(False)
    ax1.yaxis.set_major_formatter(formy)
#     ax2.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%i' % x))
#     ax1.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%i' % x))
    ax1.set_ylabel('Phase (Degrees)')
    ax1.set_xlabel('Electrode pairs  (stimulus, measured)')
    ax1.set_xlim(left=0, right=26)
 #   ax1.set_yscale('log')
    ax1.legend(loc=0, frameon=False)

    plt.savefig('optimise_sheep_transimpedance_doubleFit_phase_thesis.pdf', format='pdf')
Esempio n. 29
0
def color(x, y, z, phi):

    #r = int(x > 0) *255
    #g = int(y > 0) *255
    #b = int(z > 0) *255

    #return r,g,b

    r = int( ( cmath.phase(complex(x, y))/math.pi/2 - phi*7 )*256 ) % 256
    g = int( ( cmath.phase(complex(y, z))/math.pi/2 - phi*9 )*256 ) % 256
    b = int( ( cmath.phase(complex(z, x))/math.pi/2 - phi*8 )*256 ) % 256

    return r, g, b
Esempio n. 30
0
def _tcf(s, x):

    # 1 - |a|² = |b|² = |xa|²  =>  |a|² = 1/(|x|² + 1)
    a = math.sqrt(1 / (abs(x)**2 + 1))
    b = a * x
    b_ = b.conjugate()
    u_A = np.array([
        [ a,  b],
        [-b_, a],
    ])

    #t0, t1 = np.tensordot(u_A, [t0, t1], 1)
    u_A = kron(u_A, np.eye(4))

    s1 = u_A @ s
    t = s1.reshape((2, 2, 2))

    # Now diagonalize  T₀ = U^† S V^†   <=>     D = U T₀ V
    #                                   <=>     |ψ'> = (1 ⊗ U ⊗ V^T) |ψ>
    U_, S, V_ = np.linalg.svd(t[0])
    u_BC = kron(np.eye(2), dagger(U_), dagger(V_).T)

    s2 = u_BC @ s1

    # Next, absorb phases into |0>_A, |1>_A, |1>_B, |1>_C:

    phi = {i: cmath.phase(s2[i])
           for i in (0, 5, 6, 7)}

    A0 = cmath.rect(1, -phi[0])
    A1 = cmath.rect(1, phi[7] - phi[5] - phi[6])
    B = cmath.rect(1, phi[5] - phi[7])
    C = cmath.rect(1, phi[6] - phi[7])

    U_phase = np.array([
        [[A0, 0],
         [0, A1]],
        [[1, 0],
         [0, B]],
        [[1, 0],
         [0, C]],
    ])

    s3 = kron(*U_phase) @ s2

    assert np.allclose(0, s3[1:4])
    assert np.allclose(0, [
        cmath.phase(x) for x in s3[[0, 5, 6, 7]]
    ])

    return s3
Esempio n. 31
0
import cmath

print("podaj z")
z = input()
z = complex(z)
print("z =", z)

modul_z = abs(z)
print("|z| =", modul_z)

argument_z = cmath.phase(z)
print("argument z =", argument_z)

sprzezenie_z = z.conjugate()
print("sprzezenie z =", sprzezenie_z)
Esempio n. 32
0
 def heading(self):
     if self.vec:
         return cmath.phase(self.vec)
     else:
         raise ValueError("vector (0,0) has no defined heading")
rate0 = zeros(len(time) // a + 1)

Ki = 1
K = (1 /
     sqrt(2 * pi)) * (-(Ki * tau_i) /
                      (j * omega * tau_i + 1) * exp(-j * omega * deltasyn) +
                      (K0_e * tau_e) / (j * omega * tau_e + 1))
Ipost_wout_noise0 = linspace(complex(0, 0), complex(0, 0), len(time))
I_pre = linspace(0, 0, len(time))

for i in range(iter):
    Vm0[0:iter, -1] = 0
    for j, t in enumerate(time):
        noise[i, j] = gauss(mu, SD)
        I_post0[i, j] = sqrt(2 * pi) * r_omega * abs(K) * cos(
            omega * t + cmath.phase(K)) + SD * sqrt(Cm * gm) * noise[i, j]  #A
        Ipost_wout_noise0[j] = sqrt(
            2 * pi) * r_omega * abs(K) * cos(omega * t + cmath.phase(K))
        I_pre[j] = r_omega * cos(omega * t)

        # membrane potential variations
        if Vm0[i, j - 1] >= V_spike:
            Vm0[i, j] = V_reset
        else:
            Vm0[i, j] = (-Vm0[i, j - 1] +
                         I_post0[i, j - 1] / gm) * dt / tau_m + Vm0[i, j - 1]
        if Vm0[i, j] >= Vth:
            Vm0[i, j] = V_spike

#compteur spikes
        if Vm0[i, j] >= V_spike:
from cmath import phase

s = input()
l = s.split("+")
x = int(l[0])
l[1].split()
y = int(l[1][0])
print((abs(complex(x, y))))
print(phase(complex(x, y)))
 def _get_agent_image(self, original, state, scale):
     angle = phase(state.heading) * 180 / pi
     rotated = pygame.transform.rotate(original, angle)
     rectangle = rotated.get_rect()
     rectangle.center = to_px(state.position, scale, self.size)
     return rotated, rectangle
Esempio n. 36
0
def _add_agline_to_dict(geo,
                        line,
                        d={},
                        idx=0,
                        mesh_size=1e-2,
                        n_elements=0,
                        bc=None):
    """Draw a new Air Gap line and add it to GMSH dictionary if it does not exist

    Parameters
    ----------
    geo : Model
        GMSH Model objet
    line : Object
        Line Object
    d : Dictionary
        GMSH dictionary
    idx : int
        Surface index it belongs to
    mesh_size : float
        Points mesh size
    n_elements : int
        Number of elements on the line for meshing control

    Returns
    -------
    None
    """

    # TO-DO: Allow repeated points for the rotor and stator sliding bands
    dlines = list()
    ltag = None
    btag, bx, by = _find_point_tag(d, line.get_begin())
    etag, ex, ey = _find_point_tag(d, line.get_end())
    if btag is None:
        btag = geo.addPoint(bx, by, 0, meshSize=mesh_size, tag=-1)
    else:
        dlines.extend(_find_lines_from_point(d, btag))
    if etag is None:
        etag = geo.addPoint(ex, ey, 0, meshSize=mesh_size, tag=-1)
    else:
        dlines.extend(_find_lines_from_point(d, etag))
    if isinstance(line, Arc):
        ctag, cx, cy = _find_point_tag(d, line.get_center())
        if ctag is None:
            ctag = geo.addPoint(cx, cy, 0, meshSize=mesh_size, tag=-1)
        else:
            dlines.extend(_find_lines_from_point(d, ctag))
        if len(dlines) > 0:
            for iline in dlines:
                p = _find_points_from_line(d, iline)
                if p[0] == btag and p[1] == etag and p[2] == ctag:
                    ltag = iline
                    break
                elif p[0] == etag and p[1] == btag and p[2] == ctag:
                    ltag = -iline
                    break
                else:
                    pass
            if ltag is None:
                ltag = geo.addCircleArc(btag, ctag, etag, tag=-1)
                if n_elements > 0:
                    geo.mesh.setTransfiniteCurve(ltag, n_elements + 1,
                                                 "Progression")
        else:
            ltag = geo.addCircleArc(btag, ctag, etag, tag=-1)
            if n_elements > 0:
                geo.mesh.setTransfiniteCurve(ltag, n_elements + 1,
                                             "Progression")

        # To avoid fill the dictionary with repeated lines
        repeated = False
        for lvalues in d[idx].values():
            if type(lvalues) is not dict:
                continue
            else:
                if lvalues["tag"] == ltag:
                    repeated = True

        if not repeated:
            nline = len(d[idx]) - 2
            arc_angle = cmath.phase(complex(ex, ey)) - cmath.phase(
                complex(bx, by))
            d[idx].update({
                nline: {
                    "tag": ltag,
                    "n_elements": n_elements,
                    "bc_name": bc,
                    "begin": {
                        "tag": btag,
                        "coord": complex(bx, by)
                    },
                    "end": {
                        "tag": etag,
                        "coord": complex(ex, ey)
                    },
                    "cent": {
                        "tag": ctag,
                        "coord": complex(cx, cy)
                    },
                    "arc_angle": arc_angle,
                    "line_angle": None,
                }
            })

    else:
        if len(dlines) > 0:
            for iline in dlines:
                p = _find_points_from_line(d, iline)
                if p[0] == btag and p[1] == etag:
                    ltag = iline
                    break
                elif p[0] == etag and p[1] == btag:
                    ltag = -iline
                    break
                else:
                    pass
            if ltag is None:
                ltag = geo.addLine(btag, etag, tag=-1)
                if n_elements > 0:
                    geo.mesh.setTransfiniteCurve(ltag, n_elements + 1,
                                                 "Progression")
        else:
            ltag = geo.addLine(btag, etag, tag=-1)
            if n_elements > 0:
                geo.mesh.setTransfiniteCurve(ltag, n_elements + 1,
                                             "Progression")

        # To avoid fill the dictionary with repeated lines
        repeated = False
        for lvalues in d[idx].values():
            if type(lvalues) is not dict:
                continue
            else:
                if lvalues["tag"] == ltag:
                    repeated = True

        if not repeated:
            nline = len(d[idx]) - 2
            line_angle = 0.5 * (cmath.phase(complex(ex, ey)) +
                                cmath.phase(complex(bx, by)))
            d[idx].update({
                nline: {
                    "tag": ltag,
                    "n_elements": n_elements,
                    "bc_name": bc,
                    "begin": {
                        "tag": btag,
                        "coord": complex(bx, by)
                    },
                    "end": {
                        "tag": etag,
                        "coord": complex(ex, ey)
                    },
                    "arc_angle": None,
                    "line_angle": line_angle,
                }
            })

    return None
Esempio n. 37
0
cumuphase2 = 0.0
for num, plaq in enumerate(plaqs):
    B = complex(1, 0)
    area = plaq[1]
    for i, point in enumerate(plaq[0]):
        #print (i+1)%4
        dot_matrix = find_dot_matrix([point, plaq[0][(i + 1) % 4]],
                                     unique_bonds_and_dots)
        if (i == 0): Bmatrix = copy.deepcopy(dot_matrix)
        if (i == 1 or i == 2 or i == 3): Bmatrix = Bmatrix * dot_matrix
        #if (i==2 or i==3):Bmatrix=Bmatrix*N.linalg.inv(dot_matrix)
    B = N.linalg.det(Bmatrix)
    #B=(B/abs(B))
    #B=B*dot_val
    Bdgamma = (
        cmath.phase(B) / (2 * pi)
    )  # factor of 16 to go from a1,a2 to theta1, theta2 -> full flux
    if (float(plaq[0][0][0]) <= float(plaq[0][0][1])):
        cumuphase1 = cumuphase1 + Bdgamma
    if (float(plaq[0][0][0]) > float(plaq[0][0][1])):
        cumuphase2 = cumuphase2 + Bdgamma
    areatot = areatot + (area)
    cumuphase = cumuphase + Bdgamma
    print "Total Theta for plaquette ", '%03i' % num, "[", '%+05f' % (
        0.5 * (float(plaq[0][0][0]) + float(plaq[0][1][0]))), ",", '%+05f' % (
            0.5 * (float(plaq[0][0][1]) +
                   float(plaq[0][3][1]))), "]", " = ", '%+08f' % (Bdgamma)
print
print "===================================================================================================="
print "Total Bdgamma (lower)/(2*pi)(a1,a2)    for all plaquettes = ", '%+10f' % cumuphase1
print "Total Bdgamma (upper)/(2*pi)(a1,a2)    for all plaquettes = ", '%+10f' % cumuphase2
Esempio n. 38
0
    def fix(self):
        """
        Proceeds the fixing of the rule, if possible.
        """
        from copy import deepcopy
        module = self.module

        if self.check():
            if self.refDesError:
                ref = self.module.reference
                if self.checkReference():
                    ref['value'] = 'REF**'
                    ref['layer'] = 'F.SilkS'
                    ref['font']['width'] = KLC_TEXT_WIDTH
                    ref['font']['height'] = KLC_TEXT_HEIGHT
                    ref['font']['thickness'] = KLC_TEXT_THICKNESS
            for graph in self.bad_width:
                graph['width'] = KLC_SILK_WIDTH
            for inter in self.intersections:
                pad = inter['pad']
                graph = inter['graph']
                if 'angle' in graph:
                    #TODO
                    pass
                elif 'center' in graph:
                    #TODO
                    pass
                else:
                    padComplex = complex(pad['pos']['x'], pad['pos']['y'])
                    startComplex = complex(graph['start']['x'], graph['start']['y'])
                    endComplex = complex(graph['end']['x'], graph['end']['y'])
                    if endComplex.imag < startComplex.imag:
                        tmp = endComplex
                        endComplex = startComplex
                        startComplex = tmp
                        graph['start']['x'] = startComplex.real
                        graph['start']['y'] = startComplex.imag
                        graph['end']['x'] = endComplex.real
                        graph['end']['y'] = endComplex.imag

                    vector = endComplex - startComplex
                    padComplex = padComplex - startComplex
                    length = abs(vector)
                    phase = cmath.phase(vector)
                    vectorR = cmath.rect(1, -phase)
                    padComplex = padComplex * vectorR
                    distance = cmath.sqrt((pad['size']['x'] / 2.0 + 0.226) ** 2 - (padComplex.imag) ** 2).real
                    padMin = padComplex.real - distance
                    padMax = padComplex.real + distance

                    if padMin < length and padMin > 0:
                        if padMax > length:
                            padComplex = (padMin + 0j) * cmath.rect(1, phase) + startComplex
                            graph['end']['x'] = round(padComplex.real, 3)
                            graph['end']['y'] = round(padComplex.imag, 3)
                        else:
                            padComplex = (padMin + 0j) * cmath.rect(1, phase) + startComplex
                            graph2 = deepcopy(graph)
                            graph['end']['x'] = round(padComplex.real, 3)
                            graph['end']['y'] = round(padComplex.imag, 3)
                            padComplex = (padMax + 0j) * cmath.rect(1, phase) + startComplex
                            graph2['start'].update({'x':round(padComplex.real, 3)})
                            graph2['start'].update({'y':round(padComplex.imag, 3)})
                            module.lines.append(graph2)
                    elif padMin < 0 and padMax > 0 and padMax < length:
                        padComplex = (padMax + 0j) * cmath.rect(1, phase) + startComplex
                        graph['start']['x'] = round(padComplex.real, 3)
                        graph['start']['y'] = round(padComplex.imag, 3)
                    elif (padMax > length and padMin < 0):
                        module.lines.remove(graph)
Esempio n. 39
0
def log_complexe(Z):
    if Z==0:
        print("L'équation exp(z)=",Z," n'a pas de solutions)")
    else:
        print("Les solution de l'équation exp(z)=",Z," sont de la forme :\n",cm.log(abs(Z)),"+ i *(",cm.phase(Z),"+2 * k * pi ) avec k entier") 
Esempio n. 40
0
        elif phase > halfPeriod + 2:
            phase -= corr
            #sampleInstants[i] = -.5
        else:
            pass
            #sampleInstants[i] = .1
    if phase >= period:
        #sampleInstants[i] = 2*bi[i]-1
        phase -= period

        latestXrSquared[lxsIndex] = (xdi[i] + 1j * xdq[i])**2
        lxsIndex += 1
        if lxsIndex >= len(latestXrSquared):
            lxsIndex = 0

        th = shift + cmath.phase(sum(latestXrSquared)) / 2
        if abs(th - theta[-1]) > 2:
            if th < theta[-1]:
                shift += math.pi
                th += math.pi
                #thetaShift.append(10)
            else:
                shift -= math.pi
                th -= math.pi
                #thetaShift.append(-10)
            #bitphase ^= 1
        else:
            pass
            #thetaShift.append(0)
        theta.append(th)
Esempio n. 41
0
# https://www.hackerrank.com/challenges/polar-coordinates/problem

import cmath

n = complex(input())
print(abs(n))
print(cmath.phase(n))
Esempio n. 42
0
def mean_angle(rad_list):
    return np.array(
        phase(sum(rect(1, rad) for rad in rad_list) / len(rad_list)))
Esempio n. 43
0
 def __init__(self, n, c):
     self.amplitude = abs(c)
     self.frequency = n
     self.phase = cmath.phase(c)
Esempio n. 44
0

def place(q):
    """Convert projection coordinates into drawing coordinates"""
    return q * scale + offset


# Start making a drawing
svg = SVG(bbox * (1 + 1j), sys.stdout)

# Show the edges
svg.group(style={"fill": "none", "stroke": "black"})
for v in graph:
    for w in graph[v]:
        p = project(v)
        r = project(w)
        if phase(p / r) > 0.01:
            q = project(midpoint(v, w))
            svg.arc(place(p), place(r), arcradius(p, q, r) * scale)
        elif phase(p / r) > -0.01 and abs(p) > abs(r):
            svg.segment(place(p), place(r))
svg.ungroup()

# Show the vertices
svg.group(style={"fill": "#BC1E47", "stroke": "black"})
for v in vertices:
    svg.circle(place(project(v)), 4)
svg.ungroup()

svg.close()
Esempio n. 45
0
import cmath
import math

AB = int(input())
BC = int(input())

A = complex(0, AB)
B = complex(0, 0)
C = complex(BC, 0)

MBC = int(round(math.degrees(cmath.phase(B + C + A))))
print(str(MBC) + "°")
Esempio n. 46
0
def get_ckmangle_gamma(par):
    r"""Returns the CKM angle $\gamma$."""
    V = get_ckm(par)
    # see eq. (12.16) of http://pdg.lbl.gov/2015/reviews/rpp2014-rev-ckm-matrix.pdf
    return phase(-V[0,0]*V[0,2].conj()/V[1,0]/V[1,2].conj())
Esempio n. 47
0
nbr = int(input())
out = []
points = []


def norm(a):
    return (a[0]**2 + a[1]**2)**(1 / 2)


for i in range(nbr):
    x, y = [int(e) for e in input().split(' ')]
    points.append(f"{x} {y}")
    x -= r[0]
    y -= r[1]
    if y == 0 and x < 0:
        out.append(math.pi)
    else:
        tmp = cmath.phase(complex(x, y))
        out.append(tmp)

res = []
for i in out[1:]:
    an = i - out[0]
    if an < 0:
        an += 2 * math.pi
    res.append(an)

#print(out)
#print(res)
print(points[res.index(min(res)) + 1])
# https://www.hackerrank.com/challenges/polar-coordinates/problem

from math import sqrt
from cmath import phase

c = complex(input())

real, imag = c.real, c.imag

r = sqrt(real**2 + imag**2)
p = phase(c)

print(round(r, 3))
print(round(p, 3))

# github.com/ArutselvanManivannan
Esempio n. 49
0
    def OdometryCallBack(self, msg):
        self.cmd_vel = rospy.Publisher('cmd_vel_mux/input/navi',
                                       Twist,
                                       queue_size=10)
        #self.r = rospy.Rate(20)
        if (not self.gotOrigAngle):
            current_orientation = msg.pose.pose.orientation
            #print(current_orientation.y)
            #print(current_orientation.x)
            #print(current_orientation.z)
            w = current_orientation.w
            z = current_orientation.z
            angle = 2 * math.atan2(z, w)
            self.objective_angle = angle
            self.gotOrigAngle = 1
        elif (self.enableDrive):
            current_orientation = msg.pose.pose.orientation
            #print(current_orientation.y)
            #print(current_orientation.x)
            #print(current_orientation.z)
            w = current_orientation.w
            z = current_orientation.z
            angle = 2 * math.atan2(z, w)
            zcur = cmath.rect(1, angle)
            if (self.isFirstRun):
                self.zdes = cmath.rect(1, angle)
                self.isFirstRun = 0
            zerr = self.zdes / zcur
            phase_err = cmath.phase(zerr)
            w = self.adjustPhase(phase_err)
            #rospy.loginfo("destination angle: %f current angle: %f error: %f adjusted phase: %f"%(cmath.phase(self.zdes),angle,phase_err,w))
            # Twist is a datatype for velocity
            error_cmd = Twist()
            error_cmd.linear.x = 0.2
            error_cmd.angular.z = w

            self.cmd_vel.publish(error_cmd)
        elif (self.enableRotate):
            current_orientation = msg.pose.pose.orientation
            #print(current_orientation.y)
            #print(current_orientation.x)
            #print(current_orientation.z)
            w = current_orientation.w
            z = current_orientation.z
            angle = 2 * math.atan2(z, w)
            zcur = cmath.rect(1, angle)
            #if (self.isFirstRun):
            # Set zdes to a certain value
            self.zdes = cmath.rect(1, self.objective_angle)
            #self.isFirstRun = 0
            zerr = self.zdes / zcur
            phase_err = cmath.phase(zerr)
            w = self.adjustPhase(phase_err)
            #rospy.loginfo("destination angle: %f current angle: %f error: %f adjusted phase: %f"%(cmath.phase(self.zdes),angle,phase_err,w))
            # Twist is a datatype for velocity
            range = 0
            if (cmath.phase(zerr) == range):
                error_cmd = Twist()
                error_cmd.linear.x = 0
                error_cmd.angular.z = 0
            else:
                error_cmd = Twist()
                error_cmd.linear.x = 0
                error_cmd.angular.z = w

            self.cmd_vel.publish(error_cmd)
        else:
            stay_put = Twist()
            self.cmd_vel.publish(stay_put)
Esempio n. 50
0
##############################

##############################
# Activité 1 - Module/argument
##############################

##############################
## Question 1 ##

import cmath  # ne pas faire "from cmath import *" car conflit sqrt
from math import *

z = 1+3j

module = abs(z)
argument = cmath.phase(z)

print("Module :", module)
print("Argument :", argument)

# z = complex(1+1j)
z = 1+1j
print("Module, Argument :", cmath.polar(z))

##############################
## Question 2 ##

z = cmath.rect(2,pi/3)
print("z =",z)

z = cmath.rect(3,5*pi/6)
Esempio n. 51
0
def angle(a,b,c,r=False):
    if r==True:
        return cm.phase((a-b)/(c-b))
    else:
        return cm.phase((a-b)/(c-b))*180/cm.pi
Esempio n. 52
0
import math
import cmath

a = input()
phi = cmath.phase(complex(a))
r = abs(complex(a))

print("{}\n{}".format(r, phi))
Esempio n. 53
0
from cmath import phase
c = complex(input())
print(abs(c))
print(phase(c))
import cmath
z=input()
print(abs(complex(z)))
print(cmath.phase(complex(z)))
import cmath as cm

if __name__ == '__main__':
    n = complex(input())  # Complex number in the form z = x + iy

    # Polar coordinates of n
    print(abs(n))  # Absolut distance from origin
    print(cm.phase(n))  # Counter-clockwise angle in radians
#!/usr/bin/python2
# https://www.hackerrank.com/domains/python/py-math

from cmath import phase

if __name__ == '__main__':
    n = complex(raw_input())
    print abs(n)
    print phase(n)
Esempio n. 57
0
import cmath

complex_num = input()
print('{:.3f}'.format(abs(complex(complex_num))))
print('{:.3f}'.format(cmath.phase(complex(complex_num))))
''' 
Aim: Read a complex number as input from user, complex_num and print 
its value in polar coordinates.

'''

#importing cmath library
import cmath

#getting the input
complex_num = complex(int(input("Enter your x value : ")),
                      int(input("Enter your y value: ")))

#using library converting the complex values into coordinates
r = float(abs(complex_num))
theta = float(cmath.phase(complex_num))

#printing the output
print("Your inputed complex number is :", complex_num)
print("r : ", r)
print("theta :", theta)
print("Hence Polar co-ordinates are : {0:0.4f} + i{1:0.4f}".format(r, theta))
'''
sample input 1 :
x : 4 y : 3
sample output 1 :
r : 5.0 theta : 0.643

sample input 2 :
x : 1 y : 2
sample output 2 : 
Esempio n. 59
0
    def checkIntersections(self):

        module = self.module

        for graph in (self.f_silk + self.b_silk):
            if 'angle' in graph:
                #TODO
                pass
            elif 'center' in graph:
                for pad in module.pads:
                    padComplex = complex(pad['pos']['x'], pad['pos']['y'])
                    padOffset = 0 + 0j
                    if 'offset' in pad['drill']:
                        if 'x' in pad['drill']['offset']:
                            padOffset = complex(pad['drill']['offset']['x'], pad['drill']['offset']['y'])

                    edgesPad = {}
                    edgesPad[0] = complex(pad['size']['x'] / 2.0, pad['size']['y'] / 2.0) + padComplex + padOffset
                    edgesPad[1] = complex(-pad['size']['x'] / 2.0, -pad['size']['y'] / 2.0) + padComplex + padOffset
                    edgesPad[2] = complex(pad['size']['x'] / 2.0, -pad['size']['y'] / 2.0) + padComplex + padOffset
                    edgesPad[3] = complex(-pad['size']['x'] / 2.0, pad['size']['y'] / 2.0) + padComplex + padOffset

                    vectorR = cmath.rect(1, cmath.pi / 180 * pad['pos']['orientation'])
                    for i in range(4):
                        edgesPad[i] = (edgesPad[i] - padComplex) * vectorR + padComplex

                    centerComplex = complex(graph['center']['x'], graph['center']['y'])
                    endComplex = complex(graph['end']['x'], graph['end']['y'])
                    radius = abs(endComplex - centerComplex)
                    if 'circle' in pad['shape']:
                        distance = radius + pad['size']['x'] / 2.0 + 0.075
                        if (abs(centerComplex - padComplex) < distance and
                            abs(centerComplex - padComplex) > abs(-radius + pad['size']['x'] / 2.0 + 0.075)):
                            self.intersections.append({'pad':pad, 'graph':graph})
                    else:
                        # if there are edges inside and outside the circle, we have an intersection
                        edgesInside = []
                        edgesOutside = []
                        for i in range(4):
                            if abs(centerComplex - edgesPad[i]) < radius:
                                edgesInside.append(edgesPad[i])
                            else:
                                edgesOutside.append(edgesPad[i])
                        if edgesInside and edgesOutside:
                            self.intersections.append({'pad':pad, 'graph':graph})
            else:
                for pad in module.pads:

                    # Skip checks on NPTH and Connect holes
                    if pad['type'] in ['np_thru_hole', 'connect']:
                        continue

                    padComplex = complex(pad['pos']['x'], pad['pos']['y'])
                    padOffset = 0 + 0j
                    if 'offset' in pad['drill']:
                        if 'x' in pad['drill']['offset']:
                            padOffset = complex(pad['drill']['offset']['x'], pad['drill']['offset']['y'])

                    edgesPad = {}
                    edgesPad[0] = complex(pad['size']['x'] / 2.0, pad['size']['y'] / 2.0) + padComplex + padOffset
                    edgesPad[1] = complex(-pad['size']['x'] / 2.0, -pad['size']['y'] / 2.0) + padComplex + padOffset
                    edgesPad[2] = complex(pad['size']['x'] / 2.0, -pad['size']['y'] / 2.0) + padComplex + padOffset
                    edgesPad[3] = complex(-pad['size']['x'] / 2.0, pad['size']['y'] / 2.0) + padComplex + padOffset

                    vectorR = cmath.rect(1, cmath.pi / 180 * pad['pos']['orientation'])
                    for i in range(4):
                        edgesPad[i] = (edgesPad[i] - padComplex) * vectorR + padComplex

                    startComplex = complex(graph['start']['x'], graph['start']['y'])
                    endComplex = complex(graph['end']['x'], graph['end']['y'])
                    if endComplex.imag > startComplex.imag:
                        vector = endComplex - startComplex
                        padComplex = padComplex - startComplex
                        for i in range(4):
                            edgesPad[i] = edgesPad[i] - startComplex
                    else:
                        vector = startComplex - endComplex
                        padComplex = padComplex - endComplex
                        for i in range(4):
                            edgesPad[i] = edgesPad[i] - endComplex
                    length = abs(vector)

                    vectorR = cmath.rect(1, -cmath.phase(vector))
                    padComplex = padComplex * vectorR
                    for i in range(4):
                            edgesPad[i] = edgesPad[i] * vectorR

                    if 'circle' in pad['shape']:
                        distance = cmath.sqrt((pad['size']['x'] / 2.0) ** 2 - (padComplex.imag) ** 2).real
                        padMinX = padComplex.real - distance
                        padMaxX = padComplex.real + distance
                    else:
                        edges = [[0,3],[0,2],[2,1],[1,3]] #lines of the rectangle pads
                        x0 = [] #vector of value the x to y=0
                        for edge in edges:
                            x1 = edgesPad[edge[0]].real
                            x2 = edgesPad[edge[1]].real
                            y1 = edgesPad[edge[0]].imag
                            y2 = edgesPad[edge[1]].imag
                            if y1 != y2:
                                x = -y1 / (y2 - y1) * (x2 - x1) + x1
                                if x < max(x1, x2) and x > min(x1, x2):
                                    x0.append(x)
                        if x0:
                            padMinX = min(x0)
                            padMaxX = max(x0)
                        else:
                            continue
                    if ((padMinX < length and padMinX > 0) or
                        (padMaxX < length and padMaxX > 0) or
                        (padMaxX > length and padMinX < 0)) :
                        if 'circle' in pad['shape']:
                            distance = pad['size']['x'] / 2.0
                            padMin = padComplex.imag - distance
                            padMax = padComplex.imag + distance
                        else:
                            padMin = min(edgesPad[0].imag, edgesPad[1].imag, edgesPad[2].imag, edgesPad[3].imag)
                            padMax = max(edgesPad[0].imag, edgesPad[1].imag, edgesPad[2].imag, edgesPad[3].imag)
                        try:
                            differentSign = padMax / padMin
                        except:
                            differentSign = padMin / padMax
                        if (differentSign < 0) or (abs(padMax) < 0.075) or (abs(padMin) < 0.075):
                            self.intersections.append({'pad':pad, 'graph':graph})
col_14 = []
phase_col_13_5 = []
phase_col_13 = []
phase_col_14 = []

for line in f1.readlines():
    if '\t' in line:
        line = line.replace('\n', '').replace('\t', ' ').split(' ')

        #print(line[0])

        if eval(line[0]) == 13:
            col_13.append(
                20 * np.log10(np.sqrt(eval(line[1])**2 + eval(line[2])**2)))
            phase_col_13.append(
                cmath.phase(complex(eval(line[1]), eval(line[2]))) / np.pi *
                180 % 360)
        elif eval(line[0]) == 13.5:
            col_13_5.append(
                20 * np.log10(np.sqrt(eval(line[1])**2 + eval(line[2])**2)))
            phase_col_13_5.append(
                cmath.phase(complex(eval(line[1]), eval(line[2]))) / np.pi *
                180 % 360)
        elif eval(line[0]) == 14:
            col_14.append(
                20 * np.log10(np.sqrt(eval(line[1])**2 + eval(line[2])**2)))
            phase_col_14.append(
                cmath.phase(complex(eval(line[1]), eval(line[2]))) / np.pi *
                180 % 360)

col_x = np.arange(7, 10.7, 0.2)