예제 #1
0
파일: trimble5500.py 프로젝트: falu/ulyxes
    def Result(self, msgs, anss):
        """ Parse answer from message

            :param msgs: messages sent to instrument
            :param anss: answers got from instrument
            :returns: dictionary
        """
        msgList = re.split('\|', msgs)
        ansList = re.split('\|', anss)
        res = {}
        for msg, ans in zip(msgList, ansList):
            if len(msg.strip()) == 0:
                continue
            # get command id form message
            ansBufflist = re.split('\n=', ans)
            commandID = ansBufflist[0]
            if commandID == self.codes['HA']:
                res['hz'] = Angle(float(ansBufflist[1]), 'PDEG')
            elif commandID == self.codes['VA']:
                res['v'] = Angle(float(ansBufflist[1]), 'PDEG')
            elif commandID == self.codes['SD']:
                res['distance'] = float(ansBufflist[1])
            elif commandID == self.codes['EASTING']:
                res['easting'] = float(ansBufflist[1])
            elif commandID == self.codes['NORTHING']:
                res['northing'] = float(ansBufflist[1])
            elif commandID == self.codes['ELE']:
                res['elevation'] = float(ansBufflist[1])
            # TODO add all codes!
        return res
예제 #2
0
    def GetNext(self):
        """ Get fields in dictionary from next line considering filter

            :returns: values in dict, empty dict on EOF
        """
        res = {}
        w = self.GetLine()
        if self.state != self.RD_OK:
            return res
        w = w.strip('\n\r')
        buf = re.split('[\{\}]', w)
        for ww in buf:
            if len(ww) > 2:
                www = ww.split(' ')
                key = int(www[0])
                if key in self.codes:
                    if key in (7, 8, 21):  # angles
                        # angles in DMS?
                        if re.search('-', www[1]):
                            res[self.codes[key]] = Angle(www[1], 'DMS')
                        else:
                            res[self.codes[key]] = Angle(float(www[1]))
                    elif key in (3, 6, 9, 11, 20, 37, 38, 39):
                        res[self.codes[key]] = float(www[1])  # numeric
                    elif key == 112:
                        res[self.codes[key]] = int(www[1])  # numeric
                    elif key == 51:
                        try:
                            res[self.codes[key]] = time.strptime(
                                ' '.join(www[1:]), '%Y-%m-%d %H:%M:%S')
                        except:
                            pass  # skip if datetime format is not valid
                    else:
                        res[self.codes[key]] = ' '.join(www[1:])
        return res
예제 #3
0
def make_angle(lineM, lineN):
    meet = intersection(lineM, lineN)
    A = Angle(lineM.endPoint1, meet, lineN.endPoint1)
    B = Angle(lineM.endPoint1, meet, lineN.endPoint2)
    C = Angle(lineM.endPoint2, meet, lineN.endPoint1)
    D = Angle(lineM.endPoint2, meet, lineN.endPoint2)
    return (A, B, C, D)
예제 #4
0
파일: georeader.py 프로젝트: GRSEB9S/ulyxes
    def GetNext(self):
        """ Get fields in dictionary from next line considering filter

            :returns: values in dict, empty dict on EOF
        """
        res = {}
        w = self.GetLine().strip('\n\r')
        buf = re.split('[\{\}]', w)
        for ww in buf:
            if len(ww) > 2:
                www = ww.split(' ')
                key = int(www[0])
                if key in self.codes:
                    if key in (7, 8, 21):  # angles
                        # angles in DMS?
                        if re.search('-', www[1]):
                            res[self.codes[key]] = Angle(www[1], 'DMS')
                        else:
                            res[self.codes[key]] = Angle(float(www[1]))
                    elif key in (3, 6, 9, 11, 37, 38, 39):
                        res[self.codes[key]] = float(www[1])  # numeric
                    elif key == 112:
                        res[self.codes[key]] = int(www[1])  # numeric
                    else:
                        res[self.codes[key]] = ' '.join(www[1:])
        return res
예제 #5
0
def angle_from_p1_to_p2(p1, p2):
    p1 = np.asarray(p1)
    p2 = np.asarray(p2)
    v = p2 - p1
    if v[0] < 0:
        return Angle(radians=np.arctan(v[1] / v[0]) + math.pi)
    return Angle(radians=np.arctan(v[1] / v[0]))
예제 #6
0
    def Result(self, msgs, anss):
        """ Parse answer from message

            :param msgs: messages sent to instrument
            :param anss: answers got from instrument
            :returns: dictionary
        """
        msgList = msgs.split('|')
        ansList = anss.split('|')
        res = {}
        for msg, ans in zip(msgList, ansList):
            if len(msg.strip()) == 0:
                continue
            # get command id form message
            ansBufflist = ans.split('\n')
            for ans1 in ansBufflist:
                if '=' in ans1:
                    buf = ans1.strip('\r|').split('=')
                    commandID = int(buf[0])
                    if commandID == self.codes['HA']:
                        res['hz'] = Angle(float(buf[1]), 'PDEG')
                    elif commandID == self.codes['VA']:
                        res['v'] = Angle(float(buf[1]), 'PDEG')
                    elif commandID == self.codes['SD']:
                        res['distance'] = float(buf[1])
                    elif commandID == self.codes['EASTING']:
                        res['east'] = float(buf[1])
                    elif commandID == self.codes['NORTHING']:
                        res['north'] = float(buf[1])
                    elif commandID == self.codes['ELE']:
                        res['elev'] = float(buf[1])
                    # TODO add all codes!
        return res
예제 #7
0
def test_angle():
    with pytest.raises(ValueError):
        Angle(0, 0, 1)

    with pytest.raises(ValueError):
        Angle(-1, 1, 2)

    with pytest.raises(ValueError):
        Angle(1, -1, 2)

    with pytest.raises(ValueError):
        Angle(1, 0, -2)

    a1 = Angle(0, 1, 2)
    a2 = Angle(0, 2, 1)
    assert a1 == a2

    a3 = Angle(1, 2, 0)
    assert a3 != a1
    assert a3 != a2

    a4 = Angle(0, 1, 3)
    assert a4 != a1

    # a funky setup to trigger the first return statement in __eq__ of angle
    a1 = Angle(0, 1, 2)
    a2 = Angle(1, 2, 3)
    the_same = a1 == a2
    assert not the_same
예제 #8
0
파일: filegen.py 프로젝트: GRSEB9S/ulyxes
    def run(self):
        """ generate observetion list

            :returns: list of observation dicts ordered by hz
        """
        observations = []
        for coo in self.coords:
            if self.station_id == coo['id']:
                #skip station
                continue
            obs = {}
            d_north = coo['north'] - self.station_north
            d_east = coo['east'] - self.station_east
            d_elev = coo['elev'] - self.station_elev - self.station_ih
            bearing = math.atan2(d_east, d_north)
            dist = math.hypot(d_east, d_north)
            zenith = math.atan2(dist, d_elev)
            obs['id'] = coo['id']
            obs['ih'] = self.station_ih
            obs['hz'] = Angle(bearing).Positive()
            obs['v'] = Angle(zenith).Positive()
            obs['distance'] = math.hypot(dist, d_elev)
            obs['code'] = 'ATR'
            obs['faces'] = self.faces
            if 'code' in coo and coo['code'] in modes1:
                obs['code'] = coo['code']
            observations.append(obs)
        observations = sorted(observations, key=lambda a: a['hz'].GetAngle())
        obs = {}
        obs['station'] = self.station_id
        obs['ih'] = self.station_ih
        observations.insert(0, obs)
        return observations
예제 #9
0
 def test_degrees(self):
     small_angle = Angle(60)
     self.assertEqual(60, small_angle.degrees)
     self.assertTrue(small_angle.is_acute())
     big_angle = Angle(320)
     self.assertFalse(big_angle.is_acute())
     funny_angle = Angle(1081)
     self.assertEqual(1, funny_angle.degrees)
예제 #10
0
    def __init__(self,
                 lengths,
                 ee1x=None,
                 ee1y=None,
                 ee1_angles=None,
                 ee2x=None,
                 ee2y=None,
                 ee2_angles=None,
                 ee1_grappled=False,
                 ee2_grappled=False):
        """
        Constructor for RobotConfig - we suggest using make_robot_config_from_ee1() or make_robot_config_from_ee2()
        to construct new instances of RobotConfig rather than calling this function directly.
        """
        self.lengths = lengths
        self.ee1_grappled = ee1_grappled
        self.ee2_grappled = ee2_grappled
        if ee1x is not None and ee1y is not None and ee1_angles is not None:
            points = [(ee1x, ee1y)]
            net_angle = Angle(radians=0)
            for i in range(len(ee1_angles)):
                x, y = points[-1]
                net_angle = net_angle + ee1_angles[i]
                x_new = x + (lengths[i] * math.cos(net_angle.in_radians()))
                y_new = y + (lengths[i] * math.sin(net_angle.in_radians()))
                points.append((x_new, y_new))

            self.ee1_angles = ee1_angles
            # 1st angle is last angle of e1_angles + pi, others are all -1 * e1_angles (in reverse order)
            self.ee2_angles = [math.pi + net_angle] + \
                              [-ee1_angles[i] for i in range(len(ee1_angles) - 1, 0, -1)]
            self.points = points

        elif ee2x is not None and ee2y is not None and ee2_angles is not None:
            points = [(ee2x, ee2y)]
            net_angle = Angle(radians=0)
            for i in range(len(ee2_angles)):
                x, y = points[0]
                net_angle = net_angle + ee2_angles[i]
                x_new = x + (lengths[-i - 1] *
                             math.cos(net_angle.in_radians()))
                y_new = y + (lengths[-i - 1] *
                             math.sin(net_angle.in_radians()))
                points.insert(0, (x_new, y_new))

            # 1st angle is last angle of e2_angles + pi, others are all -1 * e2_angles (in reverse order)
            self.ee1_angles = [math.pi + sum(ee2_angles)] + \
                              [-ee2_angles[i] for i in range(len(ee2_angles) - 1, 0, -1)]
            self.ee2_angles = ee2_angles
            self.points = points

        else:
            raise Exception(
                "Could not create RobotConfig - Insufficient information given"
            )
예제 #11
0
    def ChangeFace(self):
        """ Change face

            :returns: empty dictionary
        """
        msg = self.measureUnit.ChangeFaceMsg()
        if msg is None:
            angles = self.GetAngles()
            angles['hz'] += Angle(180, 'DEG')
            angles['v'] = Angle(360, 'DEG') - angles['v']
            return self.Move(angles['hz'], angles['v'])
        return self._process(msg)
예제 #12
0
파일: players.py 프로젝트: jaytouz/pyChoplo
 def create_empty_data_struct(self):
     COF = Joint(None, None, "COF")
     COM = Joint(None, None, "COF")
     C7 = Joint(None, None, "COF")
     angle_lower = Angle(None, None, "angle_lower")
     angle_trunk = Angle(None, None, "angle_trunk")
     phase = OLD_PHASE_OUT_PHASE(None, None, None, name="phase")
     return Move(cof=COF,
                 com=COM,
                 c7=C7,
                 angle_l=angle_lower,
                 angle_t=angle_trunk,
                 phase=phase)
예제 #13
0
    def Result(self, msg, ans):
        """ process the answer from GNSS

            :param msg: MNEA message to get
            :param ans: NMEA message from GNSS unit
            :returns: processed message or None if msg and ans do not match
        """
        res = {}
        if ans[3:len(msg) + 3] != msg:
            return None
        # check checksum
        data, cksum = re.split('\*', ans)
        cksum1 = 0
        for s in data[1:]:
            cksum1 ^= ord(s)
        if ('0x' + cksum).lower() != hex(cksum1).lower():
            logging.error(' Checksum error')
            return None
        anslist = ans.split(',')
        if msg == 'GGA':
            # no fix
            if int(anslist[6]) == 0:
                return None
            try:
                mul = 1 if anslist[3] == 'N' else -1
                res['latitude'] = Angle(mul * float(anslist[2]), 'NMEA')
                mul = 1 if anslist[5] == 'E' else -1
                res['longitude'] = Angle(mul * float(anslist[4]), 'NMEA')
                res['quality'] = int(anslist[6])
                res['nsat'] = int(anslist[7])
                res['altitude'] = float(anslist[9])
                res['hdop'] = float(anslist[8])
                if self.date_time is not None:
                    res['datetime'] = self.date_time
                    self.date_time = None
            except:
                logging.error(" invalid nmea sentence: " + ans)
                return None
        elif msg == 'ZDA':
            try:
                # TODO microseconds
                self.date_time = datetime(int(anslist[4]), int(anslist[3]),
                                          int(anslist[2]),
                                          int(anslist[1][0:2]),
                                          int(anslist[1][2:4]),
                                          int(anslist[1][4:6]))
            except:
                logging.error(" invalid nmea sentence: " + ans)
                return None
        return res
예제 #14
0
def create_bridge_config(spec):
    grapple_points = spec.grapple_points
    arm = spec.initial
    min_lengths = spec.min_lengths
    max_lengths = spec.max_lengths
    #print(min_lengths)
    #print(max_lengths)
    angles = []
    lengths = []
    for i in range(len(arm.lengths)):
        if i == 0:
            angles.append(Angle(math.radians(random.randint(-180, 180))))
        else:
            angles.append(Angle(math.radians(random.randint(-165, 165))))
        lengths.append(random.uniform(min_lengths[i], max_lengths[i]))

    #angles.append(Angle)
    #print(angles)
    #print(lengths)
    #print(arm.points[0][0])
    #print(arm.points[0][1])
    #print(arm.points[1])
    sample = make_robot_config_from_ee1(arm.points[0][0], arm.points[0][1],
                                        angles, lengths, True)
    #for points in sample.points:
    #print(points)
    sample_points = sample.points[-2]
    #print("--------------")
    #print(sample_points)
    delta_y = grapple_points[1][1] - sample_points[1]
    delta_x = grapple_points[1][0] - sample_points[0]
    new_angle = delta_y / delta_x
    last_angle = Angle.tan(new_angle)
    sum_angles = 0
    for angle in range(len(angles) - 1):
        if angle == 0:
            sum_angles = angles[angle].in_degrees()
        else:
            sum_angles = 180 + angles[angle].in_degrees()
    second_last_angle = 360 - sum_angles - last_angle
    angles[-1] = Angle(math.radians(360 + second_last_angle))
    lengths[-1] = math.sqrt(delta_x**2 + delta_y**2)

    bridge_2_config = make_robot_config_from_ee1(arm.points[0][0],
                                                 arm.points[0][1], angles,
                                                 lengths, True, False)
    while (not individual_config_collision_checking(spec, bridge_2_config)):
        bridge_2_config = create_bridge_config(spec)
    return bridge_2_config
예제 #15
0
    def __init__(self):
        super().__init__()
        # this decides which side of the screen to spawn at.
        self.start = random.randint(1, 4)

        # uses the function from point to find the x and y
        self.center.x = self.center.generate_asteroid_x(self.start)
        self.center.y = self.center.generate_asteroid_y(self.start)

        # uses angle object and its methods
        # to find the direction it should go
        angle = Angle()
        self.direction = angle.generate_angle(self.start)

        # uses the direction to get the correct speed
        self.velocity.dx = math.cos(math.radians(
            self.direction)) * BIG_ROCK_SPEED
        self.velocity.dy = math.sin(math.radians(
            self.direction)) * BIG_ROCK_SPEED

        self.radius = BIG_ROCK_RADIUS

        # starts at 0, but this will increase as the astroids advance
        self.rotation = 0

        self.dr = 1

        self.texture = arcade.load_texture("images/meteorGrey_big1.png")
        self.width = 50
        self.height = 50
예제 #16
0
def generate_sample(spec, config, index):
    angles = []
    lengths = []
    for i in range(spec.num_segments):
        angles.append(Angle(random.uniform(-165, 165)))
        if spec.min_lengths != spec.max_lengths:
            lengths.append(
                random.uniform(spec.min_lengths[i], spec.max_lengths[i]))
        else:
            lengths = config.lengths
    if index % 2 == 0:
        next_config = make_robot_config_from_ee1(spec.grapple_points[index][0],
                                                 spec.grapple_points[index][1],
                                                 angles,
                                                 lengths,
                                                 ee1_grappled=True,
                                                 ee2_grappled=False)
    else:
        next_config = make_robot_config_from_ee2(spec.grapple_points[index][0],
                                                 spec.grapple_points[index][1],
                                                 angles,
                                                 lengths,
                                                 ee1_grappled=False,
                                                 ee2_grappled=True)
    if detect_collision(spec, next_config):
        node = GraphNode(spec, next_config)
        return node
    else:
        return generate_sample(spec, config, index)
예제 #17
0
def process_gyro(gyro_data, timestamp):
    """
    Computes the change in rotation angle, based on gyroscope measurements.
    It accepts gyro_data, an rs2_vector containing measurements retrieved from gyroscope,
    and timestamp, the timestamp of the current frame from gyroscope stream.
    """
    global first
    global last_timestamp_gyro

    # On the first iteration use only data from accelerometer
    # to set the camera's initial position
    if first:
        last_timestamp_gyro = timestamp
        return

    # Initialize gyro angle with data from gyro
    # gyro_data.x : Pitch
    # gyro_data.y : Yaw
    # gyro_data.z : Roll
    gyro_angle = Angle(gyro_data.x, gyro_data.y, gyro_data.z)
    # Compute the difference between arrival times of previous and current gyro frames
    dt_gyro = (timestamp - last_timestamp_gyro) / 1000.0
    last_timestamp_gyro = timestamp
    # Change in angle equals gyro measurements * time passed since last measurement
    gyro_angle = gyro_angle * dt_gyro

    # Apply the calculated change of angle to the current angle (theta)
    global mutex
    global theta
    mutex.acquire()
    theta.add(-gyro_angle.z, -gyro_angle.y, gyro_angle.x)
    mutex.release()
    return theta
예제 #18
0
파일: correct.py 프로젝트: jzg0028/CSSE
 def correctedAzimuth(self):
     return Angle(
         math.degrees(
             math.acos((math.sin(math.radians(self.getLatitude())) -
                        math.sin(math.radians(self.getAssumedLatitude())) *
                        self.intermediateDistance()) /
                       (math.cos(math.radians(self.getAssumedLatitude())) *
                        math.cos(math.asin(self.intermediateDistance()))))))
예제 #19
0
    def Result(self, msg, ans):
        """ process the answer from GNSS

            :param msg: MNEA message to get
            :param ans: NMEA message from GNSS unit
            :returns: processed message or None if msg and ans do not match
        """
        res = {}
        if ans[3:len(msg) + 3] != msg:
            return None
        # check checksum
        data, cksum = re.split('\*', ans)
        cksum1 = 0
        for s in data[1:]:
            cksum1 ^= ord(s)
        if ('0x' + cksum).lower() != hex(cksum1).lower():
            logging.error(' Checksum error')
            return None
        anslist = ans.split(',')
        if msg == 'GGA':
            # no fix
            if int(anslist[6]) == 0:
                return None
            try:
                hour = int(anslist[1][0:2])
                minute = int(anslist[1][2:4])
                second = int(anslist[1][4:6])
                if len(anslist[1]) > 6:
                    ms = int(float(anslist[1][6:]) * 1000)
                else:
                    ms = 0
                d = date.today()
                res['datetime'] = datetime(d.year, d.month, d.day, hour,
                                           minute, second, ms)
                mul = 1 if anslist[3] == 'N' else -1
                res['latitude'] = Angle(mul * float(anslist[2]), 'NMEA')
                mul = 1 if anslist[5] == 'E' else -1
                res['longitude'] = Angle(mul * float(anslist[4]), 'NMEA')
                res['quality'] = int(anslist[6])
                res['nsat'] = int(anslist[7])
                res['altitude'] = float(anslist[9])
                res['hdop'] = float(anslist[8])
            except:
                logging.error(" invalid nmea sentence: " + ans)
                return None
        return res
예제 #20
0
 def setup_sensors(self, angle, origin):
     self.origin = origin
     offset = -62
     for line in self.lines:
         self.detected[line].update_vector(
             calculate_vector(origin, -Angle(angle.degree + offset).radians,
                              self.detected[line].sensor_size))
         offset += 31
예제 #21
0
 def get_minute_hour_angle(self):
     self.set_second_angle()
     self.set_minute_angle()
     self.set_hour_angle()
     minute_hour_angle = Angle(self.minute_angle.angle -
                               self.hour_angle.angle)
     minute_hour_angle.convert_to_normal_angle()
     return minute_hour_angle
예제 #22
0
 def set_hour_angle(self):
     if self.time.hour > 12:
         hour = self.time.hour - 12
     else:
         hour = self.time.hour
     self.hour_angle = Angle(hour / 12 * 360 + self.time.minute /
                             (60 * 12) * 360 + self.time.second /
                             (60 * 60 * 12) * 360)
예제 #23
0
def get_all_transit_intervals(target,
                              ephemeris,
                              start_date,
                              end_date,
                              onepersite=False,
                              verbose=False,
                              vverbose=False,
                              exptime=0):

    intervals = []
    titles = []
    sitenames = []
    telescopes = file_to_dicts(
        '/home/jeastman/lcogt/scheduler/transits/rise_set-0.2.10/telescopes.dat'
    )
    for telescope in telescopes:
        if telescope['status'] == 'online':
            site = {
                'name': telescope['name'].split(".")[2],
                'latitude': Angle(degrees=telescope['latitude']),
                'longitude': Angle(degrees=telescope['longitude']),
                'horizon': telescope['horizon'],
                'ha_limit_neg': telescope['ha_limit_neg'],
                'ha_limit_pos': telescope['ha_limit_pos'],
            }
            if not site['name'] in sitenames or not onepersite:
                sitenames.append(site['name'])

                site_intervals, site_titles = get_transit_intervals(
                    target,
                    ephemeris,
                    site,
                    start_date,
                    end_date,
                    verbose=verbose,
                    vverbose=vverbose,
                    exptime=exptime)

                #                print site_intervals, site_titles, start_date, end_date, target
                for start, stop in site_intervals:
                    intervals.append((start, stop))
                for title in site_titles:
                    titles.append(title)

    return intervals, titles
예제 #24
0
    def PicMes(self, photoName, targetType=None):
        '''Measure angles between the target and the optical axis
            :param photoName: name of the photo
            :param targetType: type of the target
            :returns: horizontal (hz) and vertical (v) correction angle in dictionary
        '''

        ok = False
        while not ok:
            print(photoName)
            file = open(photoName, 'w+b')
            print((int(self._affinParams[0, 3]), int(self._affinParams[1, 3])))

            ang = self.GetAngles()
            self.TakePhoto(
                file,
                (int(self._affinParams[0, 3]), int(self._affinParams[1, 3])))

            file.close()

            try:

                img = cv2.imread(photoName, 1)
                picCoord = rec.recogChessPattern(img)
                print(picCoord)
                ok = True
            except:
                pass

        img[int(picCoord[1]), :] = [0, 255, 255]
        img[:, int(picCoord[0])] = [0, 255, 255]

        cv2.imwrite(photoName, img)
        angles = {}
        angles['hz'] = Angle(1 / math.sin(ang['v'].GetAngle('RAD')) *
                             (self._affinParams[0, 1] *
                              (picCoord[0] - round(self._affinParams[0, 0])) +
                              self._affinParams[0, 2] *
                              (picCoord[1] - round(self._affinParams[1, 0]))))
        angles['v'] = Angle(self._affinParams[1, 1] *
                            (picCoord[0] - round(self._affinParams[0, 0])) +
                            self._affinParams[1, 2] *
                            (picCoord[1] - round(self._affinParams[1, 0])))

        return angles
예제 #25
0
    def orientation(self):
        res = super(SenseHat, self).get_orientation_radians()
        res2 = {}
        for key, val in res.items():
            res2['ori_' + key] = Angle(val)
        res2['time'] = time.time()
        self.write(res2)

        return res2
예제 #26
0
파일: robotplus.py 프로젝트: GRSEB9S/ulyxes
def avg_obs(obs):
    """ Calculate average observations in faces

        :param obs: list of observations
        :returns: average observations
    """
    res = []  # output list
    # copy station record to output
    if 'station' in obs[0]:
        res.append(obs[0])
    ids = list(set([o['id'] for o in obs if 'id' in o]))
    for k in ids:
        # separate face left/right
        hz1 = [o['hz'].GetAngle() for o in obs \
            if 'id' in o and o['id'] == k and o['v'].GetAngle() < math.pi]
        hz2 = [o['hz'].GetAngle() for o in obs \
            if 'id' in o and o['id'] == k and o['v'].GetAngle() > math.pi]
        # check angles around 0
        for i in range(len(hz1)):
            if hz1[i] - hz1[0] > math.pi:
                hz1[i] -= math.pi * 2.0
            if hz1[i] - hz1[0] < math.pi:
                hz1[i] += math.pi * 2.0
        for i in range(len(hz2)):
            if hz2[i] - hz2[0] > math.pi:
                hz2[i] -= math.pi * 2.0
            if hz2[i] - hz2[0] < math.pi:
                hz2[i] += math.pi * 2.0
        if hz1[0] > hz2[0]:
            hz2 = [h + math.pi for h in hz2]
        else:
            hz2 = [h - math.pi for h in hz2]
        hz = sum(hz1 + hz2) / (len(hz1) + len(hz2))

        v1 = [o['v'].GetAngle() for o in obs \
            if 'id' in o and o['id'] == k and o['v'].GetAngle() < math.pi]
        v2 = [math.pi * 2.0 - o['v'].GetAngle() for o in obs \
            if 'id' in o and o['id'] == k and o['v'].GetAngle() > math.pi]
        v = sum(v1 + v2) / (len(v1) + len(v2))
        sd12 = [o['distance'] for o in obs \
            if 'id' in o and o['id'] == k]
        sd = sum(sd12) / len(sd12)
        res.append({'id': k, 'hz': Angle(hz), 'v': Angle(v), 'distance': sd})
    return res
예제 #27
0
def least_angular_separation(coords1, coords2, precision):
    """Compute the least angular separation between two celestial objects
    using iteration.
    @param coords1 List of 3 SphCoords for object 1 (equidistant times).
    @param coords2 List of 3 SphCoords for object 2 (equidistant times).
    @param precision The precision at which to terminate the iteration.
    @return The least angular separation as an Angle object
    """
    assert isinstance(coords1, list) and isinstance(coords2, list), \
           'coords must be lists'
    # CAUTION: Pythonism below!
    assert len(coords1) == 3 == len(coords2), \
           'coords must be 3 element lists'
    for sph1, sph2 in zip(coords1, coords2):
        assert isinstance(sph1, SphCoord) and isinstance(sph2, SphCoord), \
               'Elements of coords must be SphCoords'
    assert precision != 0, 'precision should not be 0'

    u_list = []
    v_list = []
    for idx in range(len(coords1)):
        sph1, sph2 = coords1[idx], coords2[idx]
        alpha1, delta1 = sph1.a.rads, sph1.b.rads
        alpha2, delta2 = sph2.a.rads, sph2.b.rads
        dalpha = alpha2 - alpha1
        ddelta = delta2 - delta1
        K = (degrees(1)*3600) / \
            (1 + (sin(delta1)**2)*tan(dalpha)*tan(dalpha/2))
        u = -K * (1 - tan(delta1) * sin(ddelta)) * cos(delta1) * tan(dalpha)
        v = K * (sin(ddelta) +
                 sin(delta1) * cos(delta1) * tan(dalpha) * tan(dalpha / 2))
        u_list.append(u)
        v_list.append(v)

    # For interpolation, treat the u_list as the values of y corresponding to
    # x = -1,0,1. Ditto for v_list
    u_ipol = Inter3polate(zip([-1, 0, 1], u_list))
    v_ipol = Inter3polate(zip([-1, 0, 1], v_list))
    n = 0.0  # Interpolating factor around the central value
    while (True):
        # Interpolate for u and v around the central value of x=0
        u = u_ipol.compute(0 + n)
        v = v_ipol.compute(0 + n)
        # Determine variations in u, v
        u_ = (u_list[2] - u_list[0]) / 2.0 + n * u_ipol.c
        v_ = (v_list[2] - v_list[0]) / 2.0 + n * v_ipol.c
        # Correction to n
        n_ = -(u * u_ + v * v_) / float(u_**2 + v_**2)
        n += n_
        if fabs(n_) <= fabs(precision):
            break
    # Compute the final values of u and v
    u = u_ipol.compute(0 + n)
    v = v_ipol.compute(0 + n)
    #@todo return final 'n' as well
    return Angle(radians(sqrt(u**2 + v**2) / 3600))
예제 #28
0
def distribute(interval,
               target,
               minoverlap=-1440,
               maxoverlap=1440,
               onepersite=True):

    sitenames = []
    intervals = []
    titles = []
    telescopes = file_to_dicts(
        '/home/jeastman/lcogt/scheduler/trunk/test/telescopes.dat')
    for telescope in telescopes:
        if telescope['status'] == 'online':
            site = {
                'name': telescope['name'].split(".")[2],
                'latitude': Angle(degrees=telescope['latitude']),
                'longitude': Angle(degrees=telescope['longitude']),
                'horizon': telescope['horizon'],
                'ha_limit_neg': telescope['ha_limit_neg'],
                'ha_limit_pos': telescope['ha_limit_pos'],
            }

            if not site['name'] in sitenames or not onepersite:
                sitenames.append(site['name'])
                print(site['name'])
                for obs_start, obs_end in interval:
                    observability = Visibility(
                        site=site,
                        start_date=obs_start,
                        end_date=obs_end,
                        horizon=site['horizon'],
                        twilight='nautical',
                        ha_limit_neg=site['ha_limit_neg'],
                        ha_limit_pos=site['ha_limit_pos'],
                    )
                    site_intervals = observability.get_observable_intervals(
                        target, moon_distance=Angle(degrees=0))
                    for start, stop in site_intervals:
                        intervals.append((start, stop))
                        titles.append(target['name'] + ' (' + site['name'] +
                                      ')')

    return intervals, titles
예제 #29
0
 def __init__(self, ts, wrt, elev=None, hz_start=None,
              stepinterval=Angle(45, "DEG"), maxa=PI2, maxiter=10, tol=0.02):
     """ initialize """
     self.ts = ts
     self.wrt = wrt
     self.elev = elev
     self.hz_start = hz_start
     self.stepinterval = stepinterval
     self.maxa = maxa
     self.maxiter = maxiter
     self.tol = tol
예제 #30
0
    def __init__(self):

        cof = Joint(None, None, "COF")
        pelvis = Joint(None, None, "pelvis")
        c7 = Joint(None, None, "c7")
        com = Joint(None, None, "COM")
        ankle_l = Joint(None, None, "ankle_l")
        ankle_r = Joint(None, None, "ankle_r")
        angle_lower = Angle(None, None, "angle_lower")
        angle_trunk = Angle(None, None, "angle_trunk")
        phase = OLD_PHASE_OUT_PHASE()
        Move.__init__(self,
                      cof=cof,
                      pelvis=pelvis,
                      c7=c7,
                      com=com,
                      ankle_l=ankle_l,
                      ankle_r=ankle_r,
                      angle_l=angle_lower,
                      angle_t=angle_trunk,
                      phase=phase)