def _get_state(body, time): """ Computes the position of a body for a given time. """ solar_system_bodies = [ Sun, Mercury, Venus, Earth, Moon, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, ] # We check if body belongs to poliastro.bodies if body in solar_system_bodies: rr, vv = coord.get_body_barycentric_posvel(body.name, time) else: rr, vv = body.propagate(time).rv() rr = coord.CartesianRepresentation(rr) vv = coord.CartesianRepresentation(vv) return rr, vv
def from_R(cls, R, inverse=False): """Compute the great circle frame from a rotation matrix that specifies the transformation from ICRS to the new frame. Parameters ---------- R : array_like The transformation matrix. inverse : bool (optional) If True, the input rotation matrix is assumed to go from the new frame to the ICRS frame.. """ if inverse: Rinv = R else: Rinv = np.linalg.inv(R) pole = coord.CartesianRepresentation([0, 0, 1.]).transform(Rinv) ra0 = coord.CartesianRepresentation([1, 0, 0.]).transform(Rinv) pole = coord.SkyCoord(pole, frame='icrs') ra0 = ra0.represent_as(coord.SphericalRepresentation) return cls(pole=pole, ra0=ra0.lon)
def test_infer_derivative_type(): """Test ``_infer_derivative_type``.""" # ---------------------------- # Test when rep is a differential rep = coord.CartesianDifferential(d_x=1, d_y=2, d_z=3) dif = icoord._infer_derivative_type(rep, u.s) assert dif.__name__ == "GenericCartesian2ndDifferential" assert dif is gcoord.GenericCartesian2ndDifferential # ---------------------------- # Test when non-time dif unit rep = coord.CartesianRepresentation(x=1, y=2, z=3) dif = icoord._infer_derivative_type(rep, u.deg) assert dif.__name__ == "GenericCartesianDifferential" assert dif is gcoord.GenericCartesianDifferential # ---------------------------- # Test when Rep & time rep = coord.CartesianRepresentation(x=1, y=2, z=3) dif = icoord._infer_derivative_type(rep, u.s) assert dif is coord.CartesianDifferential
def test_sanity(): rep1 = coord.CartesianRepresentation(x=[0, 1.], y=0, z=0, unit=u.pc) rep2 = coord.CartesianRepresentation(x=0, y=[0, 1.], z=0, unit=u.pc) rep3 = coord.CartesianRepresentation(x=0, y=0, z=[0, 1.], unit=u.pc) # Try for many origins: rnd = np.random.RandomState(seed=42) for _ in range(128): origin = coord.ICRS(ra=rnd.uniform(0, 360) * u.deg, dec=rnd.uniform(-90, 90) * u.deg, distance=rnd.uniform(10, 100) * u.pc) ref_c = ReferencePlaneFrame(rep1, origin=origin) icrs = ref_c.transform_to(coord.ICRS) assert icrs.dec[1] > icrs.dec[0] assert quantity_allclose(icrs.ra[0], icrs.ra[1]) ref_c = ReferencePlaneFrame(rep2, origin=origin) icrs = ref_c.transform_to(coord.ICRS) assert icrs.ra[1] > icrs.ra[0] ref_c = ReferencePlaneFrame(rep3, origin=origin) icrs = ref_c.transform_to(coord.ICRS) assert icrs.distance[0] > icrs.distance[1] assert quantity_allclose(icrs.ra[0], icrs.ra[1]) assert quantity_allclose(icrs.dec[0], icrs.dec[1])
def reference_plane(self, time): """Compute the orbit at specified times in the two-body barycentric frame aligned with the reference plane coordinate system (XYZ). Parameters ---------- time : array_like, `astropy.time.Time` Array of times as barycentric MJD values, or an Astropy `~astropy.time.Time` object containing the times to evaluate at. """ xyz = self.orbital_plane(time) vxyz = xyz.differentials['s'] xyz = xyz.without_differentials() # Construct rotation matrix to take the orbit from the orbital plane # system (xyz) to the reference plane system (XYZ): R1 = rotation_matrix(-self.omega, axis='z') R2 = rotation_matrix(self.i, axis='x') R3 = rotation_matrix(self.Omega, axis='z') Rot = matrix_product(R3, R2, R1) # Rotate to the reference plane system XYZ = coord.CartesianRepresentation(matrix_product(Rot, xyz.xyz)) VXYZ = coord.CartesianDifferential(matrix_product(Rot, vxyz.d_xyz)) XYZ = XYZ.with_differentials(VXYZ) kw = dict() if self.barycenter is not None: kw['origin'] = self.barycenter.origin return ReferencePlaneFrame(XYZ, **kw)
def represent_as(self, Representation): """ Represent the position and velocity of the orbit in an alternate coordinate system. Supports any of the Astropy coordinates representation classes. Parameters ---------- Representation : :class:`~astropy.coordinates.BaseRepresentation` The class for the desired representation. Returns ------- pos : `~astropy.coordinates.BaseRepresentation` vel : `~astropy.units.Quantity` The velocity in the new representation. All components have units of velocity -- e.g., to get an angular velocity in spherical representations, you'll need to divide by the radius. """ if self.ndim != 3: raise ValueError("Representation changes require a 3D (ndim=3) " "position and velocity.") # get the name of the desired representation rep_name = Representation.get_name() # transform the position car_pos = coord.CartesianRepresentation(self.pos) new_pos = car_pos.represent_as(Representation) # transform the velocity vfunc = getattr(vtrans, "cartesian_to_{}".format(rep_name)) new_vel = vfunc(car_pos, self.vel) return new_pos, new_vel
def test_run(self): """Test method ``run``.""" # ------------------- # defaults resid = self.inst.run(fit_potential=self.original_potential, original_potential=None, observable=None, representation_type=None, batch=True, **self.kwargs) assert resid == coord.CartesianRepresentation((0, 0, 0)) # ------------------- # passing in values resid = self.inst.run( fit_potential=self.original_potential, original_potential=self.original_potential, observable=self.observable, representation_type="spherical", batch=True, ) assert resid == coord.SphericalRepresentation(0 * u.rad, 0 * u.rad, 0)
def setup_class(cls): """Setup fixtures for testing.""" super().setup_class() nx = ny = nz = 76 # must be int and even nxr0 = nyr0 = nzr0 = 2.3 * 2 X, Y, Z = (np.array( np.meshgrid( np.linspace(-nxr0 / 2, nxr0 / 2, nx), np.linspace(-nyr0 / 2, nyr0 / 2, ny), np.linspace(-nzr0 / 2, nzr0 / 2, nz), indexing="ij", ), ) * 1) XYZ = coord.CartesianRepresentation(X, Y, Z, unit=u.kpc) # THIRD PARTY import galpy.potential as gpot cls.potential = gpot.HernquistPotential() cls.meshgrid = XYZ cls.inst = cls.obj( PotentialWrapper(cls.potential), cls.meshgrid, total_mass=10 * u.solMass, )
def test__infer_representation(self): """Test method ``_infer_representation``.""" # ---------------- # None -> own frame assert (self.inst._infer_representation(None) == self.inst.potential.representation_type) # ---------------- # still None old_representation_type = self.inst.representation_type self.inst.potential._representation_type = None assert (self.inst._infer_representation(None) == self.inst.frame.default_representation) self.inst.potential._representation_type = old_representation_type # ---------------- assert (self.inst._infer_representation(coord.CartesianRepresentation) is coord.CartesianRepresentation) assert (self.inst._infer_representation( coord.CartesianRepresentation( (1, 2, 3)), ) == coord.CartesianRepresentation) assert (self.inst._infer_representation("cartesian") == coord.CartesianRepresentation)
def EarthLocation(self, jd): """ Returns positions as an EarthLocation object, which can be feed directly into :func:`astropy.time.Time.light_travel_time`. Parameters: jd (ndarray): Time in Julian Days where position of TESS should be calculated. Returns: :class:`astropy.coordinates.EarthLocation`: EarthLocation object that can be passed directly into :py:class:`astropy.time.Time`. .. codeauthor:: Rasmus Handberg <*****@*****.**> """ # Get positions as 2D array: positions = self.position(jd, relative_to='EARTH') # Transform into appropiate Geocentric frame: obstimes = Time(jd, format='jd', scale='tdb') cartrep = coord.CartesianRepresentation(positions, xyz_axis=1, unit=u.km) gcrs = coord.GCRS(cartrep, obstime=obstimes) itrs = gcrs.transform_to(coord.ITRS(obstime=obstimes)) # Create EarthLocation object return coord.EarthLocation.from_geocentric(*itrs.cartesian.xyz, unit=u.km)
def setup_class(cls): """Setup fixtures for testing.""" cls.num = 40 cls.affine = np.linspace(0, 10, num=cls.num) * u.Myr cls.rep = coord.CartesianRepresentation( x=np.linspace(0, 1, num=cls.num) * u.kpc, y=np.linspace(1, 2, num=cls.num) * u.kpc, z=np.linspace(2, 3, num=cls.num) * u.kpc, differentials=coord.CartesianDifferential( d_x=np.linspace(3, 4, num=cls.num) * u.km / u.s, d_y=np.linspace(4, 5, num=cls.num) * u.km / u.s, d_z=np.linspace(5, 6, num=cls.num) * u.km / u.s, ), ) if cls.klass is icoord.InterpolatedRepresentationOrDifferential: class SubClass(cls.klass): pass # so not abstract & can instantiate cls.inst = SubClass(cls.rep, affine=cls.affine) else: cls.inst = cls.klass(cls.rep, affine=cls.affine)
def setup_class(cls): """Setup fixtures for testing.""" cls.num = 40 cls.affine = np.linspace(0, 10, num=cls.num) * u.Myr cls.frame = coord.Galactocentric cls.rep = coord.CartesianRepresentation( x=np.linspace(0, 1, num=cls.num) * u.kpc, y=np.linspace(1, 2, num=cls.num) * u.kpc, z=np.linspace(2, 3, num=cls.num) * u.kpc, differentials=coord.CartesianDifferential( d_x=np.linspace(3, 4, num=cls.num) * u.km / u.s, d_y=np.linspace(4, 5, num=cls.num) * u.km / u.s, d_z=np.linspace(5, 6, num=cls.num) * u.km / u.s, ), ) cls.irep = icoord.InterpolatedRepresentation( cls.rep, affine=cls.affine, ) cls.coord = cls.frame(cls.irep) cls.icoord = icoord.InterpolatedCoordinateFrame(cls.coord) cls.inst = cls.klass(cls.icoord)
def satellite_position(): """not used""" # Hardcoded for one satellite satellite_name = "ODIN" satellite_line1 = '1 26702U 01007A 19291.79098765 -.00000023 00000-0 25505-5 0 9996' satellite_line2 = '2 26702 97.5699 307.6930 0011485 26.4207 333.7604 15.07886437 19647' current_time = datetime.datetime.now() satellite = twoline2rv(satellite_line1, satellite_line2, wgs72) position, velocity = satellite.propagate( current_time.year, current_time.month, current_time.day, current_time.hour, current_time.minute, current_time.second) now = Time.now() # position of satellite in GCRS or J20000 ECI: cartrep = coord.CartesianRepresentation(x=position[0], y=position[1], z=position[2], unit=u.m) gcrs = coord.GCRS(cartrep, obstime=now) itrs = gcrs.transform_to(coord.ITRS(obstime=now)) loc = coord.EarthLocation(*itrs.cartesian.xyz) return jsonify({ 'eci': {'x': position[0], 'y': position[1], 'z': position[2]}, 'geodetic': {'latitude': loc.lat.deg, 'longitude': loc.lon.deg, 'height': loc.height.to(u.m).value} })
def evaluate( x: u.kpc, y: u.kpc, z: u.kpc, v_x: u.km / u.s, v_y: u.km / u.s, v_z: u.km / u.s, ): # TODO using actual mechanics of transformation d_xyz = coord.CartesianDifferential(d_x=v_x, d_y=v_y, d_z=v_z) xyz = coord.CartesianRepresentation(x=x, y=y, z=z, differentials=d_xyz) sph = xyz.represent_as( coord.SphericalRepresentation, differential_class=coord.SphericalDifferential, ) d_sph = sph.differentials["s"] return ( sph.lon, sph.lat, sph.distance, d_sph.d_lon, d_sph.d_lat, d_sph.d_distance, )
def test_evaluate_potential(self): """Test method ``evaluate_potential``.""" # evaluate_potential assert (self.inst.evaluate_potential( self.original_potential, ) == coord.CartesianRepresentation(x=1, y=2, z=3))
def __init__(self, pqr_to_itrs_matrix, observing_location_itrs, sources=None): r''' sources: dict Name: ICRS SkyCoord. ''' if sources is None: source_names = [ 'Cas A', 'Cyg A', 'Vir A', 'Her A', 'Tau A', 'Per A', '3C 353', '3C 123', '3C 295', '3C 196', 'DR 4', 'DR 23', 'DR 21' ] source_icrs = [ get_icrs_coordinates(source) for source in source_names ] self.sources = { name: icrs for name, icrs in zip(source_names, source_icrs) } else: self.sources = sources self.pqr_to_itrs_matrix = pqr_to_itrs_matrix xyz = observing_location_itrs self.obsgeoloc = acc.CartesianRepresentation(x=xyz[0], y=xyz[1], z=xyz[2], unit='m')
def _pos_to_repr(pos): if hasattr(pos, 'xyz'): # Representation-like pos_repr = coord.CartesianRepresentation(pos.xyz) elif hasattr(pos, 'cartesian') or hasattr(pos, 'to_cartesian'): # Frame-like pos_repr = pos.represent_as(coord.CartesianRepresentation) elif hasattr(pos, 'unit'): # Quantity-like pos_repr = coord.CartesianRepresentation(pos) else: raise TypeError("Unsupported position type '{0}'. Position must be " "an Astropy Representation or Frame, or a " "Quantity instance".format(type(pos))) return pos_repr
def test_transform(): rep = coord.CartesianRepresentation(x=1, y=2, z=3, unit=u.pc) ref_c1 = ReferencePlaneFrame(rep) with pytest.raises(ValueError): ref_c1.transform_to(coord.ICRS) with pytest.raises(ValueError): ref_c2 = ReferencePlaneFrame(rep, origin=coord.Galactic())
def test_find_first_best_compatible_differential(): """Test ``_find_first_best_compatible_differential``.""" # ---------------------------- # Test when rep has compatible differentials rep = coord.CartesianRepresentation(x=1, y=2, z=3) # find differential dif = icoord._find_first_best_compatible_differential(rep) assert dif is coord.CartesianDifferential
def hee_to_gse(hee_coord, gse_frame): ''' Convert from HEE to GSE coordinates. ''' obstime = hee_coord.obstime r_earth_sun = ephem.get_sunearth_distance(time=obstime) # Rotate 180deg around the z-axis R = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) # Offset so centre is at Earth offset = coords.CartesianRepresentation(r_earth_sun, 0 * u.m, 0 * u.m) return R, offset
def test_rms(): """:func:`~discO.core.statistic.rms`""" x = np.linspace(0, 1, num=49) * u.kpc vf_x = np.ones(len(x)) * u.km / u.s points = coord.CartesianRepresentation((x, x, x)) vf = CartesianVectorField(points, vf_x=vf_x, vf_y=vf_x, vf_z=vf_x) got = statistic.rms(vf) assert got == np.sqrt(3) * u.km / u.s
def get_coord_in_ecef(xyz): from astropy import coordinates as coord from astropy import units as u from astropy.time import Time now = Time(TIME) # position of satellite in GCRS or J20000 ECI: cartrep = coord.CartesianRepresentation(*xyz, unit=u.m) gcrs = coord.GCRS(cartrep, obstime=now) itrs = gcrs.transform_to(coord.ITRS(obstime=now)) loc = coord.EarthLocation(*itrs.cartesian.xyz) return [loc.lat, loc.lon, loc.height]
def __call__(self, time): """ Determine instrument antenna positions in ICRS. Parameters ---------- time : :py:class:`~astropy.time.Time` Moment at which the coordinates are wanted. Returns ------- :py:class:`~pypeline.phased_array.instrument.InstrumentGeometry` (N_antenna, 3) ICRS instrument geometry. Examples -------- .. testsetup:: from pypeline.phased_array.instrument import LofarBlock import astropy.time as atime import astropy.units as u .. doctest:: >>> instr = LofarBlock() >>> time = atime.Time('J2000') >>> xyz = instr(time) >>> np.around(xyz.data[:5], 2) array([[ 1148711.63, -3679538.21, 5064569. ], [ 1148716.62, -3679538.41, 5064567.74], [ 1148705.76, -3679542.23, 5064567.43], [ 1148710.75, -3679542.42, 5064566.16], [ 1148715.74, -3679542.61, 5064564.9 ]]) >>> xyz = instr(time + 30 * u.min) >>> np.around(xyz.data[:5], 2) array([[ 1620400.85, -3497579.41, 5064547.21], [ 1620405.82, -3497578.94, 5064545.95], [ 1620395.56, -3497584.15, 5064545.63], [ 1620400.53, -3497583.69, 5064544.37], [ 1620405.5 , -3497583.23, 5064543.11]]) """ layout = self._layout.loc[:, ['X', 'Y', 'Z']].values.T r = linalg.norm(layout, axis=0) itrs_layout = coord.CartesianRepresentation(layout) itrs_position = coord.SkyCoord(itrs_layout, obstime=time, frame='itrs') icrs_position = r * (itrs_position.transform_to('icrs').cartesian.xyz) icrs_layout = pd.DataFrame(data=icrs_position.T, index=self._layout.index, columns=('X', 'Y', 'Z')) return _as_InstrumentGeometry(icrs_layout)
def cart2pol(x, y, z): """ Cartesian coordinates to Polar coordinates. Parameters ---------- x : float or :py:class:`~numpy.ndarray` X coordinate. y : float or :py:class:`~numpy.ndarray` Y coordinate. z : float or :py:class:`~numpy.ndarray` Z coordinate. Returns ------- r : :py:class:`~numpy.ndarray` Radius. colat : :py:class:`~numpy.ndarray` Polar/Zenith angle [rad]. lon : :py:class:`~numpy.ndarray` Longitude angle [rad]. Examples -------- .. testsetup:: import numpy as np from imot_tools.math.sphere.transform import cart2pol .. doctest:: >>> r, colat, lon = cart2pol(0, 1 / np.sqrt(2), 1 / np.sqrt(2)) >>> np.around(r, 2) 1.0 >>> np.around(np.rad2deg(colat), 2) 45.0 >>> np.around(np.rad2deg(lon), 2) 90.0 """ cart = coord.CartesianRepresentation(x, y, z) sph = coord.SphericalRepresentation.from_cartesian(cart) r = sph.distance.to_value(u.dimensionless_unscaled) colat = u.Quantity(90 * u.deg - sph.lat).to_value(u.rad) lon = u.Quantity(sph.lon).to_value(u.rad) return r, colat, lon
def test___init__(self): """Test method ``__init__``.""" # -------------------------- # default self.obj( rvs=self.rvs, c_err=self.c_err, method="Gaussian", representation_type="cartesian", ) # -------------------------- # explicitly None obj = self.obj( rvs=self.rvs, c_err=self.c_err, method="Gaussian", frame=None, representation_type="cartesian", ) assert isinstance(obj.frame, UnFrame) assert obj.representation_type is coord.CartesianRepresentation assert "method" not in obj.params # -------------------------- # iter for frame, rep_type in ( # instance ( coord.Galactocentric(), coord.CartesianRepresentation((1, 2, 3)), ), # class (coord.Galactocentric, coord.CartesianRepresentation), # str ("galactocentric", "cartesian"), ): obj = self.obj( rvs=self.rvs, c_err=self.c_err, method="Gaussian", frame=frame, representation_type=rep_type, ) assert obj.frame == coord.Galactocentric(), frame assert (obj.representation_type == coord.CartesianRepresentation ), rep_type assert "method" not in obj.params
def test_representation_representation(): """ Test that Representations are represented correctly. """ # With no unit we get "None" in the unit row c = coordinates.CartesianRepresentation([0], [1], [0], unit=u.one) t = Table([c]) assert t.pformat() == [' col0 ', '------------', '(0., 1., 0.)'] c = coordinates.CartesianRepresentation([0], [1], [0], unit='m') t = Table([c]) assert t.pformat() == [' col0 ', ' m ', '------------', '(0., 1., 0.)'] c = coordinates.SphericalRepresentation([10]*u.deg, [20]*u.deg, [1]*u.pc) t = Table([c]) assert t.pformat() == [' col0 ', ' deg, deg, pc ', '--------------', '(10., 20., 1.)'] c = coordinates.UnitSphericalRepresentation([10]*u.deg, [20]*u.deg) t = Table([c]) assert t.pformat() == [' col0 ', ' deg ', '----------', '(10., 20.)'] c = coordinates.SphericalCosLatDifferential( [10]*u.mas/u.yr, [2]*u.mas/u.yr, [10]*u.km/u.s) t = Table([c]) assert t.pformat() == [' col0 ', 'mas / yr, mas / yr, km / s', '--------------------------', ' (10., 2., 10.)']
def test_evaluate_potential(self): """Test method ``evaluate_potential``.""" with pytest.raises( NotImplementedError, match="ppropriate subpackage.", ): self.obj.evaluate_potential(self.inst, self.original_potential) # evaluate_potential assert (self.inst.evaluate_potential( self.original_potential, ) == coord.CartesianRepresentation(x=1, y=2, z=3))
def __call__(self, n: int = 1, representation_type: TH.OptRepresentationLikeType = None, random: RandomLike = None, **kwargs) -> TH.SkyCoordType: """Sample. Parameters ---------- n : int number of samples frame : frame-like or None output frame of samples **kwargs: ignored. Returns ------- SkyCoord """ # Get preferred frame and representation frame = self.frame representation_type = self._infer_representation(representation_type) # TODO accepts a potential parameter. what does this do? # TODO confirm random seed. with self._random_context(random): pos, masses = self._potential.sample(n=n) # process the position and mass if np.shape(pos)[1] == 6: pos, vel = pos[:, :3], pos[:, 3:] # TODO: vel differentials = dict(s=coord.CartesianDifferential(*vel.T * u.km / u.s), ) else: differentials = None rep = coord.CartesianRepresentation(*pos.T * u.kpc, differentials=differentials) if representation_type is None: representation_type = rep.__class__ samples = SkyCoord( frame.realize_frame(rep, representation_type=representation_type), copy=False, ) samples.cache["mass"] = masses * u.solMass samples.cache["potential"] = self.potential return samples
def _make_samples_in_even_sized_voxels( self, indices: np.ndarray, centers: coord.CartesianRepresentation, dims: u.Quantity, rng=None, ): rng = np.random.default_rng() if rng is None else rng offset = rng.uniform(-1, 1, size=(len(indices), 3)) / 2 * dims # TODO! vectorize mids = centers.xyz.T c = u.Quantity([mids[tuple(i)] for i in indices]) return coord.CartesianRepresentation((c + offset).T)
def fast_to_galcen(gal, galcen_frame): rep = gal.cartesian if 's' in rep.differentials: dif = rep.differentials['s'] else: dif = None new_rep = (rep.without_differentials() + coord.CartesianRepresentation( [-1, 0, 0] * galcen_frame.galcen_distance)) if dif is not None: new_dif = dif + galcen_frame.galcen_v_sun new_rep = new_rep.with_differentials({'s': new_dif}) return new_rep