repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
galactics/beyond
beyond/frames/stations.py
create_station
def create_station(name, latlonalt, parent_frame=WGS84, orientation='N', mask=None): """Create a ground station instance Args: name (str): Name of the station latlonalt (tuple of float): coordinates of the station, as follow: * Latitude in degrees * Longitude in degrees * Altitude to sea level in meters parent_frame (Frame): Planetocentric rotating frame of reference of coordinates. orientation (str or float): Heading of the station Acceptable values are 'N', 'S', 'E', 'W' or any angle in radians mask: (2D array of float): First dimension is azimuth counterclockwise strictly increasing. Second dimension is elevation. Both in radians Return: TopocentricFrame """ if isinstance(orientation, str): orient = {'N': np.pi, 'S': 0., 'E': np.pi / 2., 'W': 3 * np.pi / 2.} heading = orient[orientation] else: heading = orientation latlonalt = list(latlonalt) latlonalt[:2] = np.radians(latlonalt[:2]) coordinates = TopocentricFrame._geodetic_to_cartesian(*latlonalt) mtd = '_to_%s' % parent_frame.__name__ dct = { mtd: TopocentricFrame._to_parent_frame, 'latlonalt': latlonalt, 'coordinates': coordinates, 'parent_frame': parent_frame, 'heading': heading, 'orientation': orientation, 'mask': np.array(mask) if mask else None, } cls = _MetaFrame(name, (TopocentricFrame,), dct) cls + parent_frame return cls
python
def create_station(name, latlonalt, parent_frame=WGS84, orientation='N', mask=None): """Create a ground station instance Args: name (str): Name of the station latlonalt (tuple of float): coordinates of the station, as follow: * Latitude in degrees * Longitude in degrees * Altitude to sea level in meters parent_frame (Frame): Planetocentric rotating frame of reference of coordinates. orientation (str or float): Heading of the station Acceptable values are 'N', 'S', 'E', 'W' or any angle in radians mask: (2D array of float): First dimension is azimuth counterclockwise strictly increasing. Second dimension is elevation. Both in radians Return: TopocentricFrame """ if isinstance(orientation, str): orient = {'N': np.pi, 'S': 0., 'E': np.pi / 2., 'W': 3 * np.pi / 2.} heading = orient[orientation] else: heading = orientation latlonalt = list(latlonalt) latlonalt[:2] = np.radians(latlonalt[:2]) coordinates = TopocentricFrame._geodetic_to_cartesian(*latlonalt) mtd = '_to_%s' % parent_frame.__name__ dct = { mtd: TopocentricFrame._to_parent_frame, 'latlonalt': latlonalt, 'coordinates': coordinates, 'parent_frame': parent_frame, 'heading': heading, 'orientation': orientation, 'mask': np.array(mask) if mask else None, } cls = _MetaFrame(name, (TopocentricFrame,), dct) cls + parent_frame return cls
[ "def", "create_station", "(", "name", ",", "latlonalt", ",", "parent_frame", "=", "WGS84", ",", "orientation", "=", "'N'", ",", "mask", "=", "None", ")", ":", "if", "isinstance", "(", "orientation", ",", "str", ")", ":", "orient", "=", "{", "'N'", ":",...
Create a ground station instance Args: name (str): Name of the station latlonalt (tuple of float): coordinates of the station, as follow: * Latitude in degrees * Longitude in degrees * Altitude to sea level in meters parent_frame (Frame): Planetocentric rotating frame of reference of coordinates. orientation (str or float): Heading of the station Acceptable values are 'N', 'S', 'E', 'W' or any angle in radians mask: (2D array of float): First dimension is azimuth counterclockwise strictly increasing. Second dimension is elevation. Both in radians Return: TopocentricFrame
[ "Create", "a", "ground", "station", "instance" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/stations.py#L135-L181
train
33,800
galactics/beyond
beyond/frames/stations.py
TopocentricFrame.visibility
def visibility(cls, orb, **kwargs): """Visibility from a topocentric frame see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>` for description of arguments handling. Args: orb (Orbit): Orbit to compute visibility from the station with Keyword Args: start (Date): starting date of the visibility search stop (Date or datetime.timedelta) end of the visibility search step (datetime.timedelta): step of the computation events (bool, Listener or list): If evaluate to True, compute AOS, LOS and MAX elevation for each pass on this station. If 'events' is a Listener or an iterable of Listeners, they will be added to the computation Any other keyword arguments are passed to the propagator. Yield: Orbit: In-visibility point of the orbit. This Orbit is already in the frame of the station and in spherical form. """ from ..orbits.listeners import stations_listeners, Listener listeners = kwargs.setdefault('listeners', []) events = kwargs.pop('events', None) event_classes = tuple() if events: # Handling of the listeners passed in the 'events' kwarg # and merging them with the `listeners` kwarg if isinstance(events, Listener): listeners.append(events) elif isinstance(events, (list, tuple)): listeners.extend(events) sta_list = stations_listeners(cls) listeners.extend(sta_list) # Only the events present in the `event_classes` list will be yielded # outside of visibility. This list was created in order to force # the yield of AOS and LOS. event_classes = tuple(listener.event for listener in sta_list) for point in orb.iter(**kwargs): point.frame = cls point.form = 'spherical' # Not very clean ! if point.phi < 0 and not isinstance(point.event, event_classes): continue yield point
python
def visibility(cls, orb, **kwargs): """Visibility from a topocentric frame see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>` for description of arguments handling. Args: orb (Orbit): Orbit to compute visibility from the station with Keyword Args: start (Date): starting date of the visibility search stop (Date or datetime.timedelta) end of the visibility search step (datetime.timedelta): step of the computation events (bool, Listener or list): If evaluate to True, compute AOS, LOS and MAX elevation for each pass on this station. If 'events' is a Listener or an iterable of Listeners, they will be added to the computation Any other keyword arguments are passed to the propagator. Yield: Orbit: In-visibility point of the orbit. This Orbit is already in the frame of the station and in spherical form. """ from ..orbits.listeners import stations_listeners, Listener listeners = kwargs.setdefault('listeners', []) events = kwargs.pop('events', None) event_classes = tuple() if events: # Handling of the listeners passed in the 'events' kwarg # and merging them with the `listeners` kwarg if isinstance(events, Listener): listeners.append(events) elif isinstance(events, (list, tuple)): listeners.extend(events) sta_list = stations_listeners(cls) listeners.extend(sta_list) # Only the events present in the `event_classes` list will be yielded # outside of visibility. This list was created in order to force # the yield of AOS and LOS. event_classes = tuple(listener.event for listener in sta_list) for point in orb.iter(**kwargs): point.frame = cls point.form = 'spherical' # Not very clean ! if point.phi < 0 and not isinstance(point.event, event_classes): continue yield point
[ "def", "visibility", "(", "cls", ",", "orb", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "orbits", ".", "listeners", "import", "stations_listeners", ",", "Listener", "listeners", "=", "kwargs", ".", "setdefault", "(", "'listeners'", ",", "[", "]...
Visibility from a topocentric frame see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>` for description of arguments handling. Args: orb (Orbit): Orbit to compute visibility from the station with Keyword Args: start (Date): starting date of the visibility search stop (Date or datetime.timedelta) end of the visibility search step (datetime.timedelta): step of the computation events (bool, Listener or list): If evaluate to True, compute AOS, LOS and MAX elevation for each pass on this station. If 'events' is a Listener or an iterable of Listeners, they will be added to the computation Any other keyword arguments are passed to the propagator. Yield: Orbit: In-visibility point of the orbit. This Orbit is already in the frame of the station and in spherical form.
[ "Visibility", "from", "a", "topocentric", "frame" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/stations.py#L15-L71
train
33,801
galactics/beyond
beyond/frames/stations.py
TopocentricFrame._to_parent_frame
def _to_parent_frame(self, *args, **kwargs): """Conversion from Topocentric Frame to parent frame """ lat, lon, _ = self.latlonalt m = rot3(-lon) @ rot2(lat - np.pi / 2.) @ rot3(self.heading) offset = np.zeros(6) offset[:3] = self.coordinates return self._convert(m, m), offset
python
def _to_parent_frame(self, *args, **kwargs): """Conversion from Topocentric Frame to parent frame """ lat, lon, _ = self.latlonalt m = rot3(-lon) @ rot2(lat - np.pi / 2.) @ rot3(self.heading) offset = np.zeros(6) offset[:3] = self.coordinates return self._convert(m, m), offset
[ "def", "_to_parent_frame", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lat", ",", "lon", ",", "_", "=", "self", ".", "latlonalt", "m", "=", "rot3", "(", "-", "lon", ")", "@", "rot2", "(", "lat", "-", "np", ".", "pi", "/...
Conversion from Topocentric Frame to parent frame
[ "Conversion", "from", "Topocentric", "Frame", "to", "parent", "frame" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/stations.py#L73-L80
train
33,802
galactics/beyond
beyond/frames/stations.py
TopocentricFrame._geodetic_to_cartesian
def _geodetic_to_cartesian(cls, lat, lon, alt): """Conversion from latitude, longitude and altitude coordinates to cartesian with respect to an ellipsoid Args: lat (float): Latitude in radians lon (float): Longitude in radians alt (float): Altitude to sea level in meters Return: numpy.array: 3D element (in meters) """ C = Earth.r / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2) S = Earth.r * (1 - Earth.e ** 2) / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2) r_d = (C + alt) * np.cos(lat) r_k = (S + alt) * np.sin(lat) norm = np.sqrt(r_d ** 2 + r_k ** 2) return norm * np.array([ np.cos(lat) * np.cos(lon), np.cos(lat) * np.sin(lon), np.sin(lat) ])
python
def _geodetic_to_cartesian(cls, lat, lon, alt): """Conversion from latitude, longitude and altitude coordinates to cartesian with respect to an ellipsoid Args: lat (float): Latitude in radians lon (float): Longitude in radians alt (float): Altitude to sea level in meters Return: numpy.array: 3D element (in meters) """ C = Earth.r / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2) S = Earth.r * (1 - Earth.e ** 2) / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2) r_d = (C + alt) * np.cos(lat) r_k = (S + alt) * np.sin(lat) norm = np.sqrt(r_d ** 2 + r_k ** 2) return norm * np.array([ np.cos(lat) * np.cos(lon), np.cos(lat) * np.sin(lon), np.sin(lat) ])
[ "def", "_geodetic_to_cartesian", "(", "cls", ",", "lat", ",", "lon", ",", "alt", ")", ":", "C", "=", "Earth", ".", "r", "/", "np", ".", "sqrt", "(", "1", "-", "(", "Earth", ".", "e", "*", "np", ".", "sin", "(", "lat", ")", ")", "**", "2", "...
Conversion from latitude, longitude and altitude coordinates to cartesian with respect to an ellipsoid Args: lat (float): Latitude in radians lon (float): Longitude in radians alt (float): Altitude to sea level in meters Return: numpy.array: 3D element (in meters)
[ "Conversion", "from", "latitude", "longitude", "and", "altitude", "coordinates", "to", "cartesian", "with", "respect", "to", "an", "ellipsoid" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/stations.py#L83-L105
train
33,803
galactics/beyond
beyond/frames/stations.py
TopocentricFrame.get_mask
def get_mask(cls, azim): """Linear interpolation between two points of the mask """ if cls.mask is None: raise ValueError("No mask defined for the station {}".format(cls.name)) azim %= 2 * np.pi if azim in cls.mask[0, :]: return cls.mask[1, np.where(azim == cls.mask[0, :])[0][0]] for next_i, mask_azim in enumerate(cls.mask[0, :]): if mask_azim > azim: break else: next_i = 0 x0, y0 = cls.mask[:, next_i - 1] x1, y1 = cls.mask[:, next_i] if next_i - 1 == -1: x0 = 0 return y0 + (y1 - y0) * (azim - x0) / (x1 - x0)
python
def get_mask(cls, azim): """Linear interpolation between two points of the mask """ if cls.mask is None: raise ValueError("No mask defined for the station {}".format(cls.name)) azim %= 2 * np.pi if azim in cls.mask[0, :]: return cls.mask[1, np.where(azim == cls.mask[0, :])[0][0]] for next_i, mask_azim in enumerate(cls.mask[0, :]): if mask_azim > azim: break else: next_i = 0 x0, y0 = cls.mask[:, next_i - 1] x1, y1 = cls.mask[:, next_i] if next_i - 1 == -1: x0 = 0 return y0 + (y1 - y0) * (azim - x0) / (x1 - x0)
[ "def", "get_mask", "(", "cls", ",", "azim", ")", ":", "if", "cls", ".", "mask", "is", "None", ":", "raise", "ValueError", "(", "\"No mask defined for the station {}\"", ".", "format", "(", "cls", ".", "name", ")", ")", "azim", "%=", "2", "*", "np", "."...
Linear interpolation between two points of the mask
[ "Linear", "interpolation", "between", "two", "points", "of", "the", "mask" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/stations.py#L108-L132
train
33,804
galactics/beyond
beyond/env/solarsystem.py
get_body
def get_body(name): """Retrieve a given body orbits and parameters Args: name (str): Object name Return: Body: """ try: body, propag = _bodies[name.lower()] # attach a propagator to the object body.propagate = propag.propagate except KeyError as e: raise UnknownBodyError(e.args[0]) return body
python
def get_body(name): """Retrieve a given body orbits and parameters Args: name (str): Object name Return: Body: """ try: body, propag = _bodies[name.lower()] # attach a propagator to the object body.propagate = propag.propagate except KeyError as e: raise UnknownBodyError(e.args[0]) return body
[ "def", "get_body", "(", "name", ")", ":", "try", ":", "body", ",", "propag", "=", "_bodies", "[", "name", ".", "lower", "(", ")", "]", "# attach a propagator to the object", "body", ".", "propagate", "=", "propag", ".", "propagate", "except", "KeyError", "...
Retrieve a given body orbits and parameters Args: name (str): Object name Return: Body:
[ "Retrieve", "a", "given", "body", "orbits", "and", "parameters" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/solarsystem.py#L13-L30
train
33,805
galactics/beyond
beyond/env/solarsystem.py
MoonPropagator.propagate
def propagate(cls, date): """Compute the Moon position at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the Moon in EME2000 frame Example: .. code-block:: python from beyond.utils.date import Date MoonPropagator.propagate(Date(1994, 4, 28)) # Orbit = # date = 1994-04-28T00:00:00 UTC # form = Cartesian # frame = EME2000 # propag = MoonPropagator # coord = # x = -134181157.317 # y = -311598171.54 # z = -126699062.437 # vx = 0.0 # vy = 0.0 # vz = 0.0 """ date = date.change_scale('TDB') t_tdb = date.julian_century def cos(angle): """cosine in degrees""" return np.cos(np.radians(angle)) def sin(angle): """sine in degrees""" return np.sin(np.radians(angle)) lambda_el = 218.32 + 481267.8813 * t_tdb + 6.29 * sin(134.9 + 477198.85 * t_tdb) \ - 1.27 * sin(259.2 - 413335.38 * t_tdb) + 0.66 * sin(235.7 + 890534.23 * t_tdb) \ + 0.21 * sin(269.9 + 954397.7 * t_tdb) - 0.19 * sin(357.5 + 35999.05 * t_tdb) \ - 0.11 * sin(186.6 + 966404.05 * t_tdb) phi_el = 5.13 * sin(93.3 + 483202.03 * t_tdb) + 0.28 * sin(228.2 + 960400.87 * t_tdb) \ - 0.28 * sin(318.3 + 6003.18 * t_tdb) - 0.17 * sin(217.6 - 407332.2 * t_tdb) p = 0.9508 + 0.0518 * cos(134.9 + 477198.85 * t_tdb) + 0.0095 * cos(259.2 - 413335.38 * t_tdb) \ + 0.0078 * cos(235.7 + 890534.23 * t_tdb) + 0.0028 * cos(269.9 + 954397.70 * t_tdb) e_bar = 23.439291 - 0.0130042 * t_tdb - 1.64e-7 * t_tdb ** 2 + 5.04e-7 * t_tdb ** 3 r_moon = Earth.r / sin(p) state_vector = r_moon * np.array([ cos(phi_el) * cos(lambda_el), cos(e_bar) * cos(phi_el) * sin(lambda_el) - sin(e_bar) * sin(phi_el), sin(e_bar) * cos(phi_el) * sin(lambda_el) + cos(e_bar) * sin(phi_el), 0, 0, 0 ]) return Orbit(date, state_vector, 'cartesian', 'EME2000', cls())
python
def propagate(cls, date): """Compute the Moon position at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the Moon in EME2000 frame Example: .. code-block:: python from beyond.utils.date import Date MoonPropagator.propagate(Date(1994, 4, 28)) # Orbit = # date = 1994-04-28T00:00:00 UTC # form = Cartesian # frame = EME2000 # propag = MoonPropagator # coord = # x = -134181157.317 # y = -311598171.54 # z = -126699062.437 # vx = 0.0 # vy = 0.0 # vz = 0.0 """ date = date.change_scale('TDB') t_tdb = date.julian_century def cos(angle): """cosine in degrees""" return np.cos(np.radians(angle)) def sin(angle): """sine in degrees""" return np.sin(np.radians(angle)) lambda_el = 218.32 + 481267.8813 * t_tdb + 6.29 * sin(134.9 + 477198.85 * t_tdb) \ - 1.27 * sin(259.2 - 413335.38 * t_tdb) + 0.66 * sin(235.7 + 890534.23 * t_tdb) \ + 0.21 * sin(269.9 + 954397.7 * t_tdb) - 0.19 * sin(357.5 + 35999.05 * t_tdb) \ - 0.11 * sin(186.6 + 966404.05 * t_tdb) phi_el = 5.13 * sin(93.3 + 483202.03 * t_tdb) + 0.28 * sin(228.2 + 960400.87 * t_tdb) \ - 0.28 * sin(318.3 + 6003.18 * t_tdb) - 0.17 * sin(217.6 - 407332.2 * t_tdb) p = 0.9508 + 0.0518 * cos(134.9 + 477198.85 * t_tdb) + 0.0095 * cos(259.2 - 413335.38 * t_tdb) \ + 0.0078 * cos(235.7 + 890534.23 * t_tdb) + 0.0028 * cos(269.9 + 954397.70 * t_tdb) e_bar = 23.439291 - 0.0130042 * t_tdb - 1.64e-7 * t_tdb ** 2 + 5.04e-7 * t_tdb ** 3 r_moon = Earth.r / sin(p) state_vector = r_moon * np.array([ cos(phi_el) * cos(lambda_el), cos(e_bar) * cos(phi_el) * sin(lambda_el) - sin(e_bar) * sin(phi_el), sin(e_bar) * cos(phi_el) * sin(lambda_el) + cos(e_bar) * sin(phi_el), 0, 0, 0 ]) return Orbit(date, state_vector, 'cartesian', 'EME2000', cls())
[ "def", "propagate", "(", "cls", ",", "date", ")", ":", "date", "=", "date", ".", "change_scale", "(", "'TDB'", ")", "t_tdb", "=", "date", ".", "julian_century", "def", "cos", "(", "angle", ")", ":", "\"\"\"cosine in degrees\"\"\"", "return", "np", ".", "...
Compute the Moon position at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the Moon in EME2000 frame Example: .. code-block:: python from beyond.utils.date import Date MoonPropagator.propagate(Date(1994, 4, 28)) # Orbit = # date = 1994-04-28T00:00:00 UTC # form = Cartesian # frame = EME2000 # propag = MoonPropagator # coord = # x = -134181157.317 # y = -311598171.54 # z = -126699062.437 # vx = 0.0 # vy = 0.0 # vz = 0.0
[ "Compute", "the", "Moon", "position", "at", "a", "given", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/solarsystem.py#L49-L109
train
33,806
galactics/beyond
beyond/env/solarsystem.py
SunPropagator.propagate
def propagate(cls, date): """Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python from beyond.utils.date import Date SunPropagator.propagate(Date(2006, 4, 2)) # Orbit = # date = 2006-04-02T00:00:00 UTC # form = Cartesian # frame = MOD # propag = SunPropagator # coord = # x = 146186235644.0 # y = 28789144480.5 # z = 12481136552.3 # vx = 0.0 # vy = 0.0 # vz = 0.0 """ date = date.change_scale('UT1') t_ut1 = date.julian_century lambda_M = 280.460 + 36000.771 * t_ut1 M = np.radians(357.5291092 + 35999.05034 * t_ut1) lambda_el = np.radians(lambda_M + 1.914666471 * np.sin(M) + 0.019994643 * np.sin(2 * M)) r = 1.000140612 - 0.016708617 * np.cos(M) - 0.000139589 * np.cos(2 * M) eps = np.radians(23.439291 - 0.0130042 * t_ut1) pv = r * np.array([ np.cos(lambda_el), np.cos(eps) * np.sin(lambda_el), np.sin(eps) * np.sin(lambda_el), 0, 0, 0 ]) * AU return Orbit(date, pv, 'cartesian', 'MOD', cls())
python
def propagate(cls, date): """Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python from beyond.utils.date import Date SunPropagator.propagate(Date(2006, 4, 2)) # Orbit = # date = 2006-04-02T00:00:00 UTC # form = Cartesian # frame = MOD # propag = SunPropagator # coord = # x = 146186235644.0 # y = 28789144480.5 # z = 12481136552.3 # vx = 0.0 # vy = 0.0 # vz = 0.0 """ date = date.change_scale('UT1') t_ut1 = date.julian_century lambda_M = 280.460 + 36000.771 * t_ut1 M = np.radians(357.5291092 + 35999.05034 * t_ut1) lambda_el = np.radians(lambda_M + 1.914666471 * np.sin(M) + 0.019994643 * np.sin(2 * M)) r = 1.000140612 - 0.016708617 * np.cos(M) - 0.000139589 * np.cos(2 * M) eps = np.radians(23.439291 - 0.0130042 * t_ut1) pv = r * np.array([ np.cos(lambda_el), np.cos(eps) * np.sin(lambda_el), np.sin(eps) * np.sin(lambda_el), 0, 0, 0 ]) * AU return Orbit(date, pv, 'cartesian', 'MOD', cls())
[ "def", "propagate", "(", "cls", ",", "date", ")", ":", "date", "=", "date", ".", "change_scale", "(", "'UT1'", ")", "t_ut1", "=", "date", ".", "julian_century", "lambda_M", "=", "280.460", "+", "36000.771", "*", "t_ut1", "M", "=", "np", ".", "radians",...
Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python from beyond.utils.date import Date SunPropagator.propagate(Date(2006, 4, 2)) # Orbit = # date = 2006-04-02T00:00:00 UTC # form = Cartesian # frame = MOD # propag = SunPropagator # coord = # x = 146186235644.0 # y = 28789144480.5 # z = 12481136552.3 # vx = 0.0 # vy = 0.0 # vz = 0.0
[ "Compute", "the", "position", "of", "the", "sun", "at", "a", "given", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/solarsystem.py#L119-L167
train
33,807
galactics/beyond
beyond/propagators/base.py
Propagator.iter
def iter(self, **kwargs): """Compute a range of orbits between two dates Keyword Arguments: dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over start (Date or None): Date of the first point stop (Date, timedelta or None): Date of the last point step (timedelta or None): Step to use during the computation. Use the same step as `self` if `None` listeners (list of:py:class:`~beyond.orbits.listeners.Listener`): Yield: :py:class:`Orbit`: There is two ways to use the iter() method. If *dates* is defined, it should be an iterable of dates. This could be a generator as per :py:meth:`Date.range <beyond.dates.date.Date.range>`, or a list. .. code-block:: python # Create two successive ranges of dates, with different steps dates = list(Date.range(Date(2019, 3, 23), Date(2019, 3, 24), timedelta(minutes=3))) dates.extend(Date.range(Date(2019, 3, 24), Date(2019, 3, 25), timedelta(minutes=10), inclusive=True)) propag.iter(dates=dates) The alternative, is the use of *start*, *stop* and *step* keyword arguments which work exactly as :code:`Date.range(start, stop, step, inclusive=True)` If one of *start*, *stop* or *step* arguments is set to ``None`` it will keep the same property as the generating ephemeris. .. code-block:: python propag.iter(stop=stop) # If the iterator has a default step (e.g. numerical propagators) propag.iter(stop=stop, step=step) propag.iter(start=start, stop=stop, step=step) """ if 'dates' not in kwargs: start = kwargs.setdefault('start', self.orbit.date) stop = kwargs.get('stop') step = kwargs.setdefault('step', getattr(self, 'step', None)) if 'stop' is None: raise ValueError("The end of the propagation should be defined") start = self.orbit.date if start is None else start step = self.step if step is None else step if isinstance(kwargs['stop'], timedelta): kwargs['stop'] = start + kwargs['stop'] if start > kwargs['stop'] and step.total_seconds() > 0: kwargs['step'] = -step listeners = kwargs.pop('listeners', []) for orb in self._iter(**kwargs): for listen_orb in self.listen(orb, listeners): yield listen_orb yield orb
python
def iter(self, **kwargs): """Compute a range of orbits between two dates Keyword Arguments: dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over start (Date or None): Date of the first point stop (Date, timedelta or None): Date of the last point step (timedelta or None): Step to use during the computation. Use the same step as `self` if `None` listeners (list of:py:class:`~beyond.orbits.listeners.Listener`): Yield: :py:class:`Orbit`: There is two ways to use the iter() method. If *dates* is defined, it should be an iterable of dates. This could be a generator as per :py:meth:`Date.range <beyond.dates.date.Date.range>`, or a list. .. code-block:: python # Create two successive ranges of dates, with different steps dates = list(Date.range(Date(2019, 3, 23), Date(2019, 3, 24), timedelta(minutes=3))) dates.extend(Date.range(Date(2019, 3, 24), Date(2019, 3, 25), timedelta(minutes=10), inclusive=True)) propag.iter(dates=dates) The alternative, is the use of *start*, *stop* and *step* keyword arguments which work exactly as :code:`Date.range(start, stop, step, inclusive=True)` If one of *start*, *stop* or *step* arguments is set to ``None`` it will keep the same property as the generating ephemeris. .. code-block:: python propag.iter(stop=stop) # If the iterator has a default step (e.g. numerical propagators) propag.iter(stop=stop, step=step) propag.iter(start=start, stop=stop, step=step) """ if 'dates' not in kwargs: start = kwargs.setdefault('start', self.orbit.date) stop = kwargs.get('stop') step = kwargs.setdefault('step', getattr(self, 'step', None)) if 'stop' is None: raise ValueError("The end of the propagation should be defined") start = self.orbit.date if start is None else start step = self.step if step is None else step if isinstance(kwargs['stop'], timedelta): kwargs['stop'] = start + kwargs['stop'] if start > kwargs['stop'] and step.total_seconds() > 0: kwargs['step'] = -step listeners = kwargs.pop('listeners', []) for orb in self._iter(**kwargs): for listen_orb in self.listen(orb, listeners): yield listen_orb yield orb
[ "def", "iter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'dates'", "not", "in", "kwargs", ":", "start", "=", "kwargs", ".", "setdefault", "(", "'start'", ",", "self", ".", "orbit", ".", "date", ")", "stop", "=", "kwargs", ".", "get", ...
Compute a range of orbits between two dates Keyword Arguments: dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over start (Date or None): Date of the first point stop (Date, timedelta or None): Date of the last point step (timedelta or None): Step to use during the computation. Use the same step as `self` if `None` listeners (list of:py:class:`~beyond.orbits.listeners.Listener`): Yield: :py:class:`Orbit`: There is two ways to use the iter() method. If *dates* is defined, it should be an iterable of dates. This could be a generator as per :py:meth:`Date.range <beyond.dates.date.Date.range>`, or a list. .. code-block:: python # Create two successive ranges of dates, with different steps dates = list(Date.range(Date(2019, 3, 23), Date(2019, 3, 24), timedelta(minutes=3))) dates.extend(Date.range(Date(2019, 3, 24), Date(2019, 3, 25), timedelta(minutes=10), inclusive=True)) propag.iter(dates=dates) The alternative, is the use of *start*, *stop* and *step* keyword arguments which work exactly as :code:`Date.range(start, stop, step, inclusive=True)` If one of *start*, *stop* or *step* arguments is set to ``None`` it will keep the same property as the generating ephemeris. .. code-block:: python propag.iter(stop=stop) # If the iterator has a default step (e.g. numerical propagators) propag.iter(stop=stop, step=step) propag.iter(start=start, stop=stop, step=step)
[ "Compute", "a", "range", "of", "orbits", "between", "two", "dates" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/base.py#L33-L92
train
33,808
galactics/beyond
beyond/env/jpl.py
get_orbit
def get_orbit(name, date): """Retrieve the orbit of a solar system object Args: name (str): The name of the body desired. For exact nomenclature, see :py:func:`available_planets` date (Date): Date at which the state vector will be extracted Return: Orbit: Orbit of the desired object, in the reference frame in which it is declared in the .bsp file """ # On-demand Propagator and Frame generation if name not in [x.name for x in Bsp().top.list]: raise UnknownBodyError(name) for a, b in Bsp().top.steps(name): if b.name not in _propagator_cache: # Creation of the specific propagator class propagator = type( "%sBspPropagator" % b.name, (GenericBspPropagator,), {'src': a, 'dst': b} ) # Retrieve informations for the central body. If unavailable, create a virtual body with # dummy values center = Pck()[b.full_name.title()] # Register the Orbit as a frame propagator.propagate(date).as_frame(b.name, center=center) _propagator_cache[b.name] = propagator if Bsp().top not in _propagator_cache: _propagator_cache[Bsp().top.name] = EarthPropagator() return _propagator_cache[name].propagate(date)
python
def get_orbit(name, date): """Retrieve the orbit of a solar system object Args: name (str): The name of the body desired. For exact nomenclature, see :py:func:`available_planets` date (Date): Date at which the state vector will be extracted Return: Orbit: Orbit of the desired object, in the reference frame in which it is declared in the .bsp file """ # On-demand Propagator and Frame generation if name not in [x.name for x in Bsp().top.list]: raise UnknownBodyError(name) for a, b in Bsp().top.steps(name): if b.name not in _propagator_cache: # Creation of the specific propagator class propagator = type( "%sBspPropagator" % b.name, (GenericBspPropagator,), {'src': a, 'dst': b} ) # Retrieve informations for the central body. If unavailable, create a virtual body with # dummy values center = Pck()[b.full_name.title()] # Register the Orbit as a frame propagator.propagate(date).as_frame(b.name, center=center) _propagator_cache[b.name] = propagator if Bsp().top not in _propagator_cache: _propagator_cache[Bsp().top.name] = EarthPropagator() return _propagator_cache[name].propagate(date)
[ "def", "get_orbit", "(", "name", ",", "date", ")", ":", "# On-demand Propagator and Frame generation", "if", "name", "not", "in", "[", "x", ".", "name", "for", "x", "in", "Bsp", "(", ")", ".", "top", ".", "list", "]", ":", "raise", "UnknownBodyError", "(...
Retrieve the orbit of a solar system object Args: name (str): The name of the body desired. For exact nomenclature, see :py:func:`available_planets` date (Date): Date at which the state vector will be extracted Return: Orbit: Orbit of the desired object, in the reference frame in which it is declared in the .bsp file
[ "Retrieve", "the", "orbit", "of", "a", "solar", "system", "object" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/jpl.py#L341-L379
train
33,809
galactics/beyond
beyond/env/jpl.py
create_frames
def create_frames(until=None): """Create frames available in the JPL files Args: until (str): Name of the body you want to create the frame of, and all frames in between. If ``None`` all the frames available in the .bsp files will be created Example: .. code-block:: python # All frames between Earth and Mars are created (Earth, EarthBarycenter, # SolarSystemBarycenter, MarsBarycenter and Mars) create_frames(until='Mars') # All frames between Earth and Phobos are created (Earth, EarthBarycenter, # SolarSystemBarycenter, MarsBarycenter and Phobos) create_frames(until='Phobos') # All frames available in the .bsp files are created create_frames() """ now = Date.now() if until: get_orbit(until, now) else: for body in list_bodies(): get_orbit(body.name, now)
python
def create_frames(until=None): """Create frames available in the JPL files Args: until (str): Name of the body you want to create the frame of, and all frames in between. If ``None`` all the frames available in the .bsp files will be created Example: .. code-block:: python # All frames between Earth and Mars are created (Earth, EarthBarycenter, # SolarSystemBarycenter, MarsBarycenter and Mars) create_frames(until='Mars') # All frames between Earth and Phobos are created (Earth, EarthBarycenter, # SolarSystemBarycenter, MarsBarycenter and Phobos) create_frames(until='Phobos') # All frames available in the .bsp files are created create_frames() """ now = Date.now() if until: get_orbit(until, now) else: for body in list_bodies(): get_orbit(body.name, now)
[ "def", "create_frames", "(", "until", "=", "None", ")", ":", "now", "=", "Date", ".", "now", "(", ")", "if", "until", ":", "get_orbit", "(", "until", ",", "now", ")", "else", ":", "for", "body", "in", "list_bodies", "(", ")", ":", "get_orbit", "(",...
Create frames available in the JPL files Args: until (str): Name of the body you want to create the frame of, and all frames in between. If ``None`` all the frames available in the .bsp files will be created Example: .. code-block:: python # All frames between Earth and Mars are created (Earth, EarthBarycenter, # SolarSystemBarycenter, MarsBarycenter and Mars) create_frames(until='Mars') # All frames between Earth and Phobos are created (Earth, EarthBarycenter, # SolarSystemBarycenter, MarsBarycenter and Phobos) create_frames(until='Phobos') # All frames available in the .bsp files are created create_frames()
[ "Create", "frames", "available", "in", "the", "JPL", "files" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/jpl.py#L392-L422
train
33,810
galactics/beyond
beyond/env/jpl.py
get_body
def get_body(name): """Retrieve the Body structure of a JPL .bsp file object Args: name (str) Return: :py:class:`~beyond.constants.Body` """ body = Pck()[name] body.propagate = lambda date: get_orbit(name, date) return body
python
def get_body(name): """Retrieve the Body structure of a JPL .bsp file object Args: name (str) Return: :py:class:`~beyond.constants.Body` """ body = Pck()[name] body.propagate = lambda date: get_orbit(name, date) return body
[ "def", "get_body", "(", "name", ")", ":", "body", "=", "Pck", "(", ")", "[", "name", "]", "body", ".", "propagate", "=", "lambda", "date", ":", "get_orbit", "(", "name", ",", "date", ")", "return", "body" ]
Retrieve the Body structure of a JPL .bsp file object Args: name (str) Return: :py:class:`~beyond.constants.Body`
[ "Retrieve", "the", "Body", "structure", "of", "a", "JPL", ".", "bsp", "file", "object" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/jpl.py#L425-L436
train
33,811
galactics/beyond
beyond/env/jpl.py
Bsp.open
def open(self): """Open the files """ segments = [] files = config.get('env', 'jpl', fallback=[]) if not files: raise JplConfigError("No JPL file defined") # Extraction of segments from each .bsp file for filepath in files: filepath = Path(filepath) if filepath.suffix.lower() != ".bsp": continue segments.extend(SPK.open(str(filepath)).segments) if not segments: raise JplError("No segment loaded") # list of available segments self.segments = dict(((s.center, s.target), s) for s in segments) # This variable will contain the Target of reference from which # all relations between frames are linked targets = {} for center_id, target_id in self.segments.keys(): center_name = target_names.get(center_id, 'Unknown') target_name = target_names.get(target_id, 'Unknown') # Retrieval of the Target object representing the center if it exists # or creation of said object if it doesn't. center = targets.setdefault(center_id, Target(center_name, center_id)) target = targets.setdefault(target_id, Target(target_name, target_id)) # Link between the Target objects (see Node2) center + target # We take the Earth target and make it the top of the structure. # That way, it is easy to link it to the already declared earth-centered reference frames # from the `frames.frame` module. self.top = targets[399]
python
def open(self): """Open the files """ segments = [] files = config.get('env', 'jpl', fallback=[]) if not files: raise JplConfigError("No JPL file defined") # Extraction of segments from each .bsp file for filepath in files: filepath = Path(filepath) if filepath.suffix.lower() != ".bsp": continue segments.extend(SPK.open(str(filepath)).segments) if not segments: raise JplError("No segment loaded") # list of available segments self.segments = dict(((s.center, s.target), s) for s in segments) # This variable will contain the Target of reference from which # all relations between frames are linked targets = {} for center_id, target_id in self.segments.keys(): center_name = target_names.get(center_id, 'Unknown') target_name = target_names.get(target_id, 'Unknown') # Retrieval of the Target object representing the center if it exists # or creation of said object if it doesn't. center = targets.setdefault(center_id, Target(center_name, center_id)) target = targets.setdefault(target_id, Target(target_name, target_id)) # Link between the Target objects (see Node2) center + target # We take the Earth target and make it the top of the structure. # That way, it is easy to link it to the already declared earth-centered reference frames # from the `frames.frame` module. self.top = targets[399]
[ "def", "open", "(", "self", ")", ":", "segments", "=", "[", "]", "files", "=", "config", ".", "get", "(", "'env'", ",", "'jpl'", ",", "fallback", "=", "[", "]", ")", "if", "not", "files", ":", "raise", "JplConfigError", "(", "\"No JPL file defined\"", ...
Open the files
[ "Open", "the", "files" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/jpl.py#L131-L177
train
33,812
galactics/beyond
beyond/env/jpl.py
Bsp.get
def get(self, center, target, date): """Retrieve the position and velocity of a target with respect to a center Args: center (Target): target (Target): date (Date): Return: numpy.array: length-6 array position and velocity (in m and m/s) of the target, with respect to the center """ if (center.index, target.index) in self.segments: pos, vel = self.segments[center.index, target.index].compute_and_differentiate(date.jd) sign = 1 else: # When we wish to get a segment that is not available in the files (such as # EarthBarycenter with respect to the Moon, for example), we take the segment # representing the inverse vector if available and reverse it pos, vel = self.segments[target.index, center.index].compute_and_differentiate(date.jd) sign = -1 # In some cases, the pos vector contains both position and velocity if len(pos) == 3: # The velocity is given in km/days, so we convert to km/s # see: https://github.com/brandon-rhodes/python-jplephem/issues/19 for clarifications pv = np.concatenate((pos, vel / S_PER_DAY)) elif len(pos) == 6: pv = np.array(pos) else: raise JplError("Unknown state vector format") return sign * pv * 1000
python
def get(self, center, target, date): """Retrieve the position and velocity of a target with respect to a center Args: center (Target): target (Target): date (Date): Return: numpy.array: length-6 array position and velocity (in m and m/s) of the target, with respect to the center """ if (center.index, target.index) in self.segments: pos, vel = self.segments[center.index, target.index].compute_and_differentiate(date.jd) sign = 1 else: # When we wish to get a segment that is not available in the files (such as # EarthBarycenter with respect to the Moon, for example), we take the segment # representing the inverse vector if available and reverse it pos, vel = self.segments[target.index, center.index].compute_and_differentiate(date.jd) sign = -1 # In some cases, the pos vector contains both position and velocity if len(pos) == 3: # The velocity is given in km/days, so we convert to km/s # see: https://github.com/brandon-rhodes/python-jplephem/issues/19 for clarifications pv = np.concatenate((pos, vel / S_PER_DAY)) elif len(pos) == 6: pv = np.array(pos) else: raise JplError("Unknown state vector format") return sign * pv * 1000
[ "def", "get", "(", "self", ",", "center", ",", "target", ",", "date", ")", ":", "if", "(", "center", ".", "index", ",", "target", ".", "index", ")", "in", "self", ".", "segments", ":", "pos", ",", "vel", "=", "self", ".", "segments", "[", "center...
Retrieve the position and velocity of a target with respect to a center Args: center (Target): target (Target): date (Date): Return: numpy.array: length-6 array position and velocity (in m and m/s) of the target, with respect to the center
[ "Retrieve", "the", "position", "and", "velocity", "of", "a", "target", "with", "respect", "to", "a", "center" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/env/jpl.py#L179-L211
train
33,813
galactics/beyond
beyond/propagators/__init__.py
get_propagator
def get_propagator(name): """Retrieve a named propagator Args: name (str): Name of the desired propagator Return: Propagator class """ from .sgp4 import Sgp4 from .sgp4beta import Sgp4Beta scope = locals().copy() scope.update(globals()) if name not in scope: raise UnknownPropagatorError(name) return scope[name]
python
def get_propagator(name): """Retrieve a named propagator Args: name (str): Name of the desired propagator Return: Propagator class """ from .sgp4 import Sgp4 from .sgp4beta import Sgp4Beta scope = locals().copy() scope.update(globals()) if name not in scope: raise UnknownPropagatorError(name) return scope[name]
[ "def", "get_propagator", "(", "name", ")", ":", "from", ".", "sgp4", "import", "Sgp4", "from", ".", "sgp4beta", "import", "Sgp4Beta", "scope", "=", "locals", "(", ")", ".", "copy", "(", ")", "scope", ".", "update", "(", "globals", "(", ")", ")", "if"...
Retrieve a named propagator Args: name (str): Name of the desired propagator Return: Propagator class
[ "Retrieve", "a", "named", "propagator" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/__init__.py#L7-L25
train
33,814
galactics/beyond
beyond/orbits/listeners.py
stations_listeners
def stations_listeners(stations): """Function for creating listeners for a a list of station Args: stations (iterable): List of TopocentricFrame Return: list of Listener """ stations = stations if isinstance(stations, (list, tuple)) else [stations] listeners = [] for sta in stations: listeners.append(StationSignalListener(sta)) listeners.append(StationMaxListener(sta)) if sta.mask is not None: listeners.append(StationMaskListener(sta)) return listeners
python
def stations_listeners(stations): """Function for creating listeners for a a list of station Args: stations (iterable): List of TopocentricFrame Return: list of Listener """ stations = stations if isinstance(stations, (list, tuple)) else [stations] listeners = [] for sta in stations: listeners.append(StationSignalListener(sta)) listeners.append(StationMaxListener(sta)) if sta.mask is not None: listeners.append(StationMaskListener(sta)) return listeners
[ "def", "stations_listeners", "(", "stations", ")", ":", "stations", "=", "stations", "if", "isinstance", "(", "stations", ",", "(", "list", ",", "tuple", ")", ")", "else", "[", "stations", "]", "listeners", "=", "[", "]", "for", "sta", "in", "stations", ...
Function for creating listeners for a a list of station Args: stations (iterable): List of TopocentricFrame Return: list of Listener
[ "Function", "for", "creating", "listeners", "for", "a", "a", "list", "of", "station" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/listeners.py#L479-L497
train
33,815
galactics/beyond
beyond/orbits/listeners.py
Speaker._bisect
def _bisect(self, begin, end, listener): """This method search for the zero-crossing of the watched parameter Args: begin (Orbit): end (Orbit) listener (Listener) Return Return """ step = (end.date - begin.date) / 2 while abs(step) >= self._eps_bisect: date = begin.date + step if self.SPEAKER_MODE == "global": orb = self.propagate(date) else: orb = begin.propagate(date) if listener(begin) * listener(orb) > 0: begin = orb else: end = orb step = (end.date - begin.date) / 2 else: end.event = listener.info(end) return end
python
def _bisect(self, begin, end, listener): """This method search for the zero-crossing of the watched parameter Args: begin (Orbit): end (Orbit) listener (Listener) Return Return """ step = (end.date - begin.date) / 2 while abs(step) >= self._eps_bisect: date = begin.date + step if self.SPEAKER_MODE == "global": orb = self.propagate(date) else: orb = begin.propagate(date) if listener(begin) * listener(orb) > 0: begin = orb else: end = orb step = (end.date - begin.date) / 2 else: end.event = listener.info(end) return end
[ "def", "_bisect", "(", "self", ",", "begin", ",", "end", ",", "listener", ")", ":", "step", "=", "(", "end", ".", "date", "-", "begin", ".", "date", ")", "/", "2", "while", "abs", "(", "step", ")", ">=", "self", ".", "_eps_bisect", ":", "date", ...
This method search for the zero-crossing of the watched parameter Args: begin (Orbit): end (Orbit) listener (Listener) Return Return
[ "This", "method", "search", "for", "the", "zero", "-", "crossing", "of", "the", "watched", "parameter" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/listeners.py#L49-L75
train
33,816
galactics/beyond
beyond/orbits/listeners.py
Listener.check
def check(self, orb): """Method that check whether or not the listener is triggered Args: orb (Orbit): Return: bool: True if there is a zero-crossing for the parameter watched by the listener """ return self.prev is not None and np.sign(self(orb)) != np.sign(self(self.prev))
python
def check(self, orb): """Method that check whether or not the listener is triggered Args: orb (Orbit): Return: bool: True if there is a zero-crossing for the parameter watched by the listener """ return self.prev is not None and np.sign(self(orb)) != np.sign(self(self.prev))
[ "def", "check", "(", "self", ",", "orb", ")", ":", "return", "self", ".", "prev", "is", "not", "None", "and", "np", ".", "sign", "(", "self", "(", "orb", ")", ")", "!=", "np", ".", "sign", "(", "self", "(", "self", ".", "prev", ")", ")" ]
Method that check whether or not the listener is triggered Args: orb (Orbit): Return: bool: True if there is a zero-crossing for the parameter watched by the listener
[ "Method", "that", "check", "whether", "or", "not", "the", "listener", "is", "triggered" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/listeners.py#L84-L94
train
33,817
galactics/beyond
beyond/orbits/forms.py
Form._m_to_e
def _m_to_e(cls, e, M): """Conversion from Mean Anomaly to Eccentric anomaly Procedures for solving Kepler's Equation, A. W. Odell and R. H. Gooding, Celestial Mechanics 38 (1986) 307-334 """ k1 = 3 * np.pi + 2 k2 = np.pi - 1 k3 = 6 * np.pi - 1 A = 3 * k2 ** 2 / k1 B = k3 ** 2 / (6 * k1) m1 = float(M) if abs(m1) < 1 / 6: E = m1 + e * (6 * m1) ** (1 / 3) - m1 elif m1 < 0: w = np.pi + m1 E = m1 + e * (A * w / (B - w) - np.pi - m1) else: w = np.pi - m1 E = m1 + e * (np.pi - A * w / (B - w) - m1) e1 = 1 - e risk_disabler = (e1 + E ** 2 / 6) >= 0.1 for i in range(2): fdd = e * sin(E) fddd = e * cos(E) if risk_disabler: f = (E - fdd) - m1 fd = 1 - fddd else: f = cls._e_e_sin_e(e, E) - m1 s = sin(E / 2) fd = e1 + 2 * e * s ** 2 dee = f * fd / (0.5 * f * fdd - fd ** 2) w = fd + 0.5 * dee * (fdd + dee * fddd / 3) fd += dee * (fdd + 0.5 * dee * fddd) E -= (f - dee * (fd - w)) / fd E += M - m1 return E
python
def _m_to_e(cls, e, M): """Conversion from Mean Anomaly to Eccentric anomaly Procedures for solving Kepler's Equation, A. W. Odell and R. H. Gooding, Celestial Mechanics 38 (1986) 307-334 """ k1 = 3 * np.pi + 2 k2 = np.pi - 1 k3 = 6 * np.pi - 1 A = 3 * k2 ** 2 / k1 B = k3 ** 2 / (6 * k1) m1 = float(M) if abs(m1) < 1 / 6: E = m1 + e * (6 * m1) ** (1 / 3) - m1 elif m1 < 0: w = np.pi + m1 E = m1 + e * (A * w / (B - w) - np.pi - m1) else: w = np.pi - m1 E = m1 + e * (np.pi - A * w / (B - w) - m1) e1 = 1 - e risk_disabler = (e1 + E ** 2 / 6) >= 0.1 for i in range(2): fdd = e * sin(E) fddd = e * cos(E) if risk_disabler: f = (E - fdd) - m1 fd = 1 - fddd else: f = cls._e_e_sin_e(e, E) - m1 s = sin(E / 2) fd = e1 + 2 * e * s ** 2 dee = f * fd / (0.5 * f * fdd - fd ** 2) w = fd + 0.5 * dee * (fdd + dee * fddd / 3) fd += dee * (fdd + 0.5 * dee * fddd) E -= (f - dee * (fd - w)) / fd E += M - m1 return E
[ "def", "_m_to_e", "(", "cls", ",", "e", ",", "M", ")", ":", "k1", "=", "3", "*", "np", ".", "pi", "+", "2", "k2", "=", "np", ".", "pi", "-", "1", "k3", "=", "6", "*", "np", ".", "pi", "-", "1", "A", "=", "3", "*", "k2", "**", "2", "...
Conversion from Mean Anomaly to Eccentric anomaly Procedures for solving Kepler's Equation, A. W. Odell and R. H. Gooding, Celestial Mechanics 38 (1986) 307-334
[ "Conversion", "from", "Mean", "Anomaly", "to", "Eccentric", "anomaly" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/forms.py#L146-L191
train
33,818
galactics/beyond
beyond/orbits/forms.py
Form._cartesian_to_spherical
def _cartesian_to_spherical(cls, coord, center): """Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal """ x, y, z, vx, vy, vz = coord r = np.linalg.norm(coord[:3]) phi = arcsin(z / r) theta = arctan2(y, x) r_dot = (x * vx + y * vy + z * vz) / r phi_dot = (vz * (x ** 2 + y ** 2) - z * (x * vx + y * vy)) / (r ** 2 * sqrt(x ** 2 + y ** 2)) theta_dot = (x * vy - y * vx) / (x ** 2 + y ** 2) return np.array([r, theta, phi, r_dot, theta_dot, phi_dot], dtype=float)
python
def _cartesian_to_spherical(cls, coord, center): """Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal """ x, y, z, vx, vy, vz = coord r = np.linalg.norm(coord[:3]) phi = arcsin(z / r) theta = arctan2(y, x) r_dot = (x * vx + y * vy + z * vz) / r phi_dot = (vz * (x ** 2 + y ** 2) - z * (x * vx + y * vy)) / (r ** 2 * sqrt(x ** 2 + y ** 2)) theta_dot = (x * vy - y * vx) / (x ** 2 + y ** 2) return np.array([r, theta, phi, r_dot, theta_dot, phi_dot], dtype=float)
[ "def", "_cartesian_to_spherical", "(", "cls", ",", "coord", ",", "center", ")", ":", "x", ",", "y", ",", "z", ",", "vx", ",", "vy", ",", "vz", "=", "coord", "r", "=", "np", ".", "linalg", ".", "norm", "(", "coord", "[", ":", "3", "]", ")", "p...
Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal
[ "Cartesian", "to", "Spherical", "conversion" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/forms.py#L251-L265
train
33,819
galactics/beyond
beyond/orbits/forms.py
Form._spherical_to_cartesian
def _spherical_to_cartesian(cls, coord, center): """Spherical to cartesian conversion """ r, theta, phi, r_dot, theta_dot, phi_dot = coord x = r * cos(phi) * cos(theta) y = r * cos(phi) * sin(theta) z = r * sin(phi) vx = r_dot * x / r - y * theta_dot - z * phi_dot * cos(theta) vy = r_dot * y / r + x * theta_dot - z * phi_dot * sin(theta) vz = r_dot * z / r + r * phi_dot * cos(phi) return np.array([x, y, z, vx, vy, vz], dtype=float)
python
def _spherical_to_cartesian(cls, coord, center): """Spherical to cartesian conversion """ r, theta, phi, r_dot, theta_dot, phi_dot = coord x = r * cos(phi) * cos(theta) y = r * cos(phi) * sin(theta) z = r * sin(phi) vx = r_dot * x / r - y * theta_dot - z * phi_dot * cos(theta) vy = r_dot * y / r + x * theta_dot - z * phi_dot * sin(theta) vz = r_dot * z / r + r * phi_dot * cos(phi) return np.array([x, y, z, vx, vy, vz], dtype=float)
[ "def", "_spherical_to_cartesian", "(", "cls", ",", "coord", ",", "center", ")", ":", "r", ",", "theta", ",", "phi", ",", "r_dot", ",", "theta_dot", ",", "phi_dot", "=", "coord", "x", "=", "r", "*", "cos", "(", "phi", ")", "*", "cos", "(", "theta", ...
Spherical to cartesian conversion
[ "Spherical", "to", "cartesian", "conversion" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/forms.py#L268-L280
train
33,820
galactics/beyond
beyond/orbits/ephem.py
Ephem.interpolate
def interpolate(self, date, method=None, order=None): """Interpolate data at a given date Args: date (Date): method (str): Method of interpolation to use order (int): In case of ``LAGRANGE`` method is used Return: Orbit: """ if not self.start <= date <= self.stop: raise ValueError("Date '%s' not in range" % date) prev_idx = 0 ephem = self # Binary search of the orbit step just before the desired date while True: idx = len(ephem) if idx == 1: break k = idx // 2 if date > ephem[k].date: prev_idx += k ephem = ephem[k:] else: ephem = ephem[:k] method = method if method is not None else self.method order = order if order is not None else self.order if method == self.LINEAR: y0 = self[prev_idx] y1 = self[prev_idx + 1] result = y0[:] + (y1[:] - y0[:]) * (date.mjd - y0.date.mjd) / (y1.date.mjd - y0.date.mjd) elif method == self.LAGRANGE: stop = prev_idx + 1 + order // 2 + order % 2 start = prev_idx - order // 2 + 1 if stop >= len(self): start -= stop - len(self) elif start < 0: stop -= start start = 0 # selection of the subset of data, of length 'order' around the desired value subset = self[start:stop] date_subset = np.array([x.date.mjd for x in subset]) result = np.zeros(6) # Everything is on wikipedia # k # L(x) = Σ y_j * l_j(x) # j=0 # # l_j(x) = Π (x - x_m) / (x_j - x_m) # 0 <= m <= k # m != j for j in range(order): # This mask is here to enforce the m != j in the lagrange polynomials mask = date_subset != date_subset[j] l_j = (date.mjd - date_subset[mask]) / (date_subset[j] - date_subset[mask]) result = result + l_j.prod() * subset[j] else: raise ValueError("Unkown interpolation method", method) orb = ephem[0] return orb.__class__(date, result, orb.form, orb.frame, orb.propagator)
python
def interpolate(self, date, method=None, order=None): """Interpolate data at a given date Args: date (Date): method (str): Method of interpolation to use order (int): In case of ``LAGRANGE`` method is used Return: Orbit: """ if not self.start <= date <= self.stop: raise ValueError("Date '%s' not in range" % date) prev_idx = 0 ephem = self # Binary search of the orbit step just before the desired date while True: idx = len(ephem) if idx == 1: break k = idx // 2 if date > ephem[k].date: prev_idx += k ephem = ephem[k:] else: ephem = ephem[:k] method = method if method is not None else self.method order = order if order is not None else self.order if method == self.LINEAR: y0 = self[prev_idx] y1 = self[prev_idx + 1] result = y0[:] + (y1[:] - y0[:]) * (date.mjd - y0.date.mjd) / (y1.date.mjd - y0.date.mjd) elif method == self.LAGRANGE: stop = prev_idx + 1 + order // 2 + order % 2 start = prev_idx - order // 2 + 1 if stop >= len(self): start -= stop - len(self) elif start < 0: stop -= start start = 0 # selection of the subset of data, of length 'order' around the desired value subset = self[start:stop] date_subset = np.array([x.date.mjd for x in subset]) result = np.zeros(6) # Everything is on wikipedia # k # L(x) = Σ y_j * l_j(x) # j=0 # # l_j(x) = Π (x - x_m) / (x_j - x_m) # 0 <= m <= k # m != j for j in range(order): # This mask is here to enforce the m != j in the lagrange polynomials mask = date_subset != date_subset[j] l_j = (date.mjd - date_subset[mask]) / (date_subset[j] - date_subset[mask]) result = result + l_j.prod() * subset[j] else: raise ValueError("Unkown interpolation method", method) orb = ephem[0] return orb.__class__(date, result, orb.form, orb.frame, orb.propagator)
[ "def", "interpolate", "(", "self", ",", "date", ",", "method", "=", "None", ",", "order", "=", "None", ")", ":", "if", "not", "self", ".", "start", "<=", "date", "<=", "self", ".", "stop", ":", "raise", "ValueError", "(", "\"Date '%s' not in range\"", ...
Interpolate data at a given date Args: date (Date): method (str): Method of interpolation to use order (int): In case of ``LAGRANGE`` method is used Return: Orbit:
[ "Interpolate", "data", "at", "a", "given", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/ephem.py#L102-L177
train
33,821
galactics/beyond
beyond/orbits/ephem.py
Ephem.iter
def iter(self, *, dates=None, start=None, stop=None, step=None, strict=True, **kwargs): """Ephemeris generator based on the data of this one, but with different dates Keyword Arguments: dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over start (Date or None): Date of the first point stop (Date, timedelta or None): Date of the last point step (timedelta or None): Step to use during the computation. Use the same step as `self` if `None` listeners (list of:py:class:`~beyond.orbits.listeners.Listener`): strict (bool): If True, the method will return a ValueError if ``start`` or ``stop`` is not in the range of the ephemeris. If False, it will take the closest point in each case. Yield: :py:class:`Orbit`: There is two ways to use the iter() method. If *dates* is defined, it should be an iterable of dates. This could be a generator as per :py:meth:`Date.range <beyond.dates.date.Date.range>`, or a list. .. code-block:: python # Create two successive ranges of dates, with different steps dates = list(Date.range(Date(2019, 3, 23), Date(2019, 3, 24), timedelta(minutes=3))) dates.extend(Date.range(Date(2019, 3, 24), Date(2019, 3, 25), timedelta(minutes=10), inclusive=True)) ephem.iter(dates=dates) The alternative, is the use of *start*, *stop* and *step* keyword arguments which work exactly as :code:`Date.range(start, stop, step, inclusive=True)` If one of *start*, *stop* or *step* arguments is set to ``None`` it will keep the same property as the generating ephemeris. .. code-block:: python # In the examples below, we consider the 'ephem' object to be an ephemeris starting on # 2017-01-01 00:00:00 UTC and ending and 2017-01-02 00:00:00 UTC (included) with a fixed # step of 3 minutes. # These two calls will generate exactly the same points starting at 00:00 and ending at # 12:00, as 12:02 does not fall on a date included in the original 'ephem' object. ephem.iter(stop=Date(2017, 1, 1, 12)) ephem.iter(stop=Date(2017, 1, 1, 12, 2)) # Similarly, these calls will generate the same points starting at 12:00 and ending at # 00:00, as 11:58 does not fall on date included in the 'ephem' object. ephem.iter(start=Date(2017, 1, 1, 11, 58)) ephem.iter(start=Date(2017, 1, 1, 12)) # This call will generate an ephemeris, wich is a subpart of the initial one ephem.iter(start=Date(2017, 1, 1, 8), stop=Date(2017, 1, 1, 16)) """ # To allow for a loose control of the dates we have to compute # the real starting date of the iterator listeners = kwargs.get('listeners', []) if dates: for date in dates: orb = self.propagate(date) # Listeners for listen_orb in self.listen(orb, listeners): yield listen_orb yield orb else: real_start = None if start is None: start = self.start elif start < self.start: if strict: raise ValueError("Start date not in range") else: real_start = self.start if stop is None: stop = self.stop else: if isinstance(stop, timedelta): stop = start + stop if stop > self.stop: if strict: raise ValueError("Stop date not in range") else: stop = self.stop if real_start is not None: start = real_start if step is None: # The step stays the same as the original ephemeris for orb in self: if orb.date < start: continue if orb.date > stop: break # Listeners for listen_orb in self.listen(orb, listeners): yield listen_orb # yield a copy of the recorded orbit to avoid later modification # which could have dire consequences yield orb.copy() else: # create as ephemeris with a different step than the original date = start while date <= stop: orb = self.propagate(date) # Listeners for listen_orb in self.listen(orb, listeners): yield listen_orb yield orb date += step
python
def iter(self, *, dates=None, start=None, stop=None, step=None, strict=True, **kwargs): """Ephemeris generator based on the data of this one, but with different dates Keyword Arguments: dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over start (Date or None): Date of the first point stop (Date, timedelta or None): Date of the last point step (timedelta or None): Step to use during the computation. Use the same step as `self` if `None` listeners (list of:py:class:`~beyond.orbits.listeners.Listener`): strict (bool): If True, the method will return a ValueError if ``start`` or ``stop`` is not in the range of the ephemeris. If False, it will take the closest point in each case. Yield: :py:class:`Orbit`: There is two ways to use the iter() method. If *dates* is defined, it should be an iterable of dates. This could be a generator as per :py:meth:`Date.range <beyond.dates.date.Date.range>`, or a list. .. code-block:: python # Create two successive ranges of dates, with different steps dates = list(Date.range(Date(2019, 3, 23), Date(2019, 3, 24), timedelta(minutes=3))) dates.extend(Date.range(Date(2019, 3, 24), Date(2019, 3, 25), timedelta(minutes=10), inclusive=True)) ephem.iter(dates=dates) The alternative, is the use of *start*, *stop* and *step* keyword arguments which work exactly as :code:`Date.range(start, stop, step, inclusive=True)` If one of *start*, *stop* or *step* arguments is set to ``None`` it will keep the same property as the generating ephemeris. .. code-block:: python # In the examples below, we consider the 'ephem' object to be an ephemeris starting on # 2017-01-01 00:00:00 UTC and ending and 2017-01-02 00:00:00 UTC (included) with a fixed # step of 3 minutes. # These two calls will generate exactly the same points starting at 00:00 and ending at # 12:00, as 12:02 does not fall on a date included in the original 'ephem' object. ephem.iter(stop=Date(2017, 1, 1, 12)) ephem.iter(stop=Date(2017, 1, 1, 12, 2)) # Similarly, these calls will generate the same points starting at 12:00 and ending at # 00:00, as 11:58 does not fall on date included in the 'ephem' object. ephem.iter(start=Date(2017, 1, 1, 11, 58)) ephem.iter(start=Date(2017, 1, 1, 12)) # This call will generate an ephemeris, wich is a subpart of the initial one ephem.iter(start=Date(2017, 1, 1, 8), stop=Date(2017, 1, 1, 16)) """ # To allow for a loose control of the dates we have to compute # the real starting date of the iterator listeners = kwargs.get('listeners', []) if dates: for date in dates: orb = self.propagate(date) # Listeners for listen_orb in self.listen(orb, listeners): yield listen_orb yield orb else: real_start = None if start is None: start = self.start elif start < self.start: if strict: raise ValueError("Start date not in range") else: real_start = self.start if stop is None: stop = self.stop else: if isinstance(stop, timedelta): stop = start + stop if stop > self.stop: if strict: raise ValueError("Stop date not in range") else: stop = self.stop if real_start is not None: start = real_start if step is None: # The step stays the same as the original ephemeris for orb in self: if orb.date < start: continue if orb.date > stop: break # Listeners for listen_orb in self.listen(orb, listeners): yield listen_orb # yield a copy of the recorded orbit to avoid later modification # which could have dire consequences yield orb.copy() else: # create as ephemeris with a different step than the original date = start while date <= stop: orb = self.propagate(date) # Listeners for listen_orb in self.listen(orb, listeners): yield listen_orb yield orb date += step
[ "def", "iter", "(", "self", ",", "*", ",", "dates", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# To allow for a loose control of the dates ...
Ephemeris generator based on the data of this one, but with different dates Keyword Arguments: dates (list of :py:class:`~beyond.dates.date.Date`): Dates from which iterate over start (Date or None): Date of the first point stop (Date, timedelta or None): Date of the last point step (timedelta or None): Step to use during the computation. Use the same step as `self` if `None` listeners (list of:py:class:`~beyond.orbits.listeners.Listener`): strict (bool): If True, the method will return a ValueError if ``start`` or ``stop`` is not in the range of the ephemeris. If False, it will take the closest point in each case. Yield: :py:class:`Orbit`: There is two ways to use the iter() method. If *dates* is defined, it should be an iterable of dates. This could be a generator as per :py:meth:`Date.range <beyond.dates.date.Date.range>`, or a list. .. code-block:: python # Create two successive ranges of dates, with different steps dates = list(Date.range(Date(2019, 3, 23), Date(2019, 3, 24), timedelta(minutes=3))) dates.extend(Date.range(Date(2019, 3, 24), Date(2019, 3, 25), timedelta(minutes=10), inclusive=True)) ephem.iter(dates=dates) The alternative, is the use of *start*, *stop* and *step* keyword arguments which work exactly as :code:`Date.range(start, stop, step, inclusive=True)` If one of *start*, *stop* or *step* arguments is set to ``None`` it will keep the same property as the generating ephemeris. .. code-block:: python # In the examples below, we consider the 'ephem' object to be an ephemeris starting on # 2017-01-01 00:00:00 UTC and ending and 2017-01-02 00:00:00 UTC (included) with a fixed # step of 3 minutes. # These two calls will generate exactly the same points starting at 00:00 and ending at # 12:00, as 12:02 does not fall on a date included in the original 'ephem' object. ephem.iter(stop=Date(2017, 1, 1, 12)) ephem.iter(stop=Date(2017, 1, 1, 12, 2)) # Similarly, these calls will generate the same points starting at 12:00 and ending at # 00:00, as 11:58 does not fall on date included in the 'ephem' object. ephem.iter(start=Date(2017, 1, 1, 11, 58)) ephem.iter(start=Date(2017, 1, 1, 12)) # This call will generate an ephemeris, wich is a subpart of the initial one ephem.iter(start=Date(2017, 1, 1, 8), stop=Date(2017, 1, 1, 16))
[ "Ephemeris", "generator", "based", "on", "the", "data", "of", "this", "one", "but", "with", "different", "dates" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/ephem.py#L184-L307
train
33,822
galactics/beyond
beyond/orbits/ephem.py
Ephem.ephem
def ephem(self, *args, **kwargs): """Create an Ephem object which is a subset of this one Take the same keyword arguments as :py:meth:`ephemeris` Return: Ephem: """ return self.__class__(self.ephemeris(*args, **kwargs))
python
def ephem(self, *args, **kwargs): """Create an Ephem object which is a subset of this one Take the same keyword arguments as :py:meth:`ephemeris` Return: Ephem: """ return self.__class__(self.ephemeris(*args, **kwargs))
[ "def", "ephem", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "ephemeris", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
Create an Ephem object which is a subset of this one Take the same keyword arguments as :py:meth:`ephemeris` Return: Ephem:
[ "Create", "an", "Ephem", "object", "which", "is", "a", "subset", "of", "this", "one" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/ephem.py#L316-L325
train
33,823
galactics/beyond
beyond/orbits/ephem.py
Ephem.copy
def copy(self, *, form=None, frame=None): # pragma: no cover """Create a deep copy of the ephemeris, and allow frame and form changing """ new = self.ephem() if frame: new.frame = frame if form: new.form = form return new
python
def copy(self, *, form=None, frame=None): # pragma: no cover """Create a deep copy of the ephemeris, and allow frame and form changing """ new = self.ephem() if frame: new.frame = frame if form: new.form = form return new
[ "def", "copy", "(", "self", ",", "*", ",", "form", "=", "None", ",", "frame", "=", "None", ")", ":", "# pragma: no cover", "new", "=", "self", ".", "ephem", "(", ")", "if", "frame", ":", "new", ".", "frame", "=", "frame", "if", "form", ":", "new"...
Create a deep copy of the ephemeris, and allow frame and form changing
[ "Create", "a", "deep", "copy", "of", "the", "ephemeris", "and", "allow", "frame", "and", "form", "changing" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/ephem.py#L327-L336
train
33,824
galactics/beyond
beyond/utils/ccsds.py
loads
def loads(text): """Read CCSDS from a string, and provide the beyond class corresponding; Orbit or list of Orbit if it's an OPM, Ephem if it's an OEM. Args: text (str): Return: Orbit or Ephem Raise: ValueError: when the text is not a recognizable CCSDS format """ if text.startswith("CCSDS_OEM_VERS"): func = _read_oem elif text.startswith("CCSDS_OPM_VERS"): func = _read_opm else: raise ValueError("Unknown CCSDS type") return func(text)
python
def loads(text): """Read CCSDS from a string, and provide the beyond class corresponding; Orbit or list of Orbit if it's an OPM, Ephem if it's an OEM. Args: text (str): Return: Orbit or Ephem Raise: ValueError: when the text is not a recognizable CCSDS format """ if text.startswith("CCSDS_OEM_VERS"): func = _read_oem elif text.startswith("CCSDS_OPM_VERS"): func = _read_opm else: raise ValueError("Unknown CCSDS type") return func(text)
[ "def", "loads", "(", "text", ")", ":", "if", "text", ".", "startswith", "(", "\"CCSDS_OEM_VERS\"", ")", ":", "func", "=", "_read_oem", "elif", "text", ".", "startswith", "(", "\"CCSDS_OPM_VERS\"", ")", ":", "func", "=", "_read_opm", "else", ":", "raise", ...
Read CCSDS from a string, and provide the beyond class corresponding; Orbit or list of Orbit if it's an OPM, Ephem if it's an OEM. Args: text (str): Return: Orbit or Ephem Raise: ValueError: when the text is not a recognizable CCSDS format
[ "Read", "CCSDS", "from", "a", "string", "and", "provide", "the", "beyond", "class", "corresponding", ";", "Orbit", "or", "list", "of", "Orbit", "if", "it", "s", "an", "OPM", "Ephem", "if", "it", "s", "an", "OEM", "." ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/utils/ccsds.py#L31-L48
train
33,825
galactics/beyond
beyond/utils/ccsds.py
dumps
def dumps(data, **kwargs): """Create a string CCSDS representation of the object Same arguments and behaviour as :py:func:`dump` """ if isinstance(data, Ephem) or (isinstance(data, Iterable) and all(isinstance(x, Ephem) for x in data)): content = _dump_oem(data, **kwargs) elif isinstance(data, Orbit): content = _dump_opm(data, **kwargs) else: raise TypeError("Unknown object type") return content
python
def dumps(data, **kwargs): """Create a string CCSDS representation of the object Same arguments and behaviour as :py:func:`dump` """ if isinstance(data, Ephem) or (isinstance(data, Iterable) and all(isinstance(x, Ephem) for x in data)): content = _dump_oem(data, **kwargs) elif isinstance(data, Orbit): content = _dump_opm(data, **kwargs) else: raise TypeError("Unknown object type") return content
[ "def", "dumps", "(", "data", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "data", ",", "Ephem", ")", "or", "(", "isinstance", "(", "data", ",", "Iterable", ")", "and", "all", "(", "isinstance", "(", "x", ",", "Ephem", ")", "for", "...
Create a string CCSDS representation of the object Same arguments and behaviour as :py:func:`dump`
[ "Create", "a", "string", "CCSDS", "representation", "of", "the", "object" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/utils/ccsds.py#L66-L78
train
33,826
galactics/beyond
beyond/utils/ccsds.py
_float
def _float(value): """Conversion of state vector field, with automatic unit handling """ if "[" in value: # There is a unit field value, sep, unit = value.partition("[") unit = sep + unit # As defined in the CCSDS Orbital Data Message Blue Book, the unit should # be the same as defined in table 3-3 which are for km and km/s for position and # velocity respectively. Thus, there should be no other conversion to make if unit in ("[km]", "[km/s]"): multiplier = 1000 elif unit == "[s]": multiplier = 1 else: raise ValueError("Unknown unit for this field", unit) else: # if no unit is provided, the default is km, and km/s multiplier = 1000 return float(value) * multiplier
python
def _float(value): """Conversion of state vector field, with automatic unit handling """ if "[" in value: # There is a unit field value, sep, unit = value.partition("[") unit = sep + unit # As defined in the CCSDS Orbital Data Message Blue Book, the unit should # be the same as defined in table 3-3 which are for km and km/s for position and # velocity respectively. Thus, there should be no other conversion to make if unit in ("[km]", "[km/s]"): multiplier = 1000 elif unit == "[s]": multiplier = 1 else: raise ValueError("Unknown unit for this field", unit) else: # if no unit is provided, the default is km, and km/s multiplier = 1000 return float(value) * multiplier
[ "def", "_float", "(", "value", ")", ":", "if", "\"[\"", "in", "value", ":", "# There is a unit field", "value", ",", "sep", ",", "unit", "=", "value", ".", "partition", "(", "\"[\"", ")", "unit", "=", "sep", "+", "unit", "# As defined in the CCSDS Orbital Da...
Conversion of state vector field, with automatic unit handling
[ "Conversion", "of", "state", "vector", "field", "with", "automatic", "unit", "handling" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/utils/ccsds.py#L81-L102
train
33,827
galactics/beyond
beyond/frames/iau2010.py
_tab
def _tab(element): """Extraction and caching of IAU2000 nutation coefficients """ elements = { 'x': 'tab5.2a.txt', 'y': 'tab5.2b.txt', 's': 'tab5.2d.txt' } if element.lower() not in elements.keys(): raise ValueError('Unknown element \'%s\'' % element) filepath = Path(__file__).parent / "data" / elements[element.lower()] total = [] with filepath.open() as fhd: for line in fhd.read().splitlines(): line = line.strip() if line.startswith("#") or not line.strip(): continue if line.startswith('j = '): result = [] total.append(result) continue # The first field is only an index fields = line.split()[1:] fields[:2] = [float(x) for x in fields[:2]] fields[2:] = [int(x) for x in fields[2:]] result.append(fields) return total
python
def _tab(element): """Extraction and caching of IAU2000 nutation coefficients """ elements = { 'x': 'tab5.2a.txt', 'y': 'tab5.2b.txt', 's': 'tab5.2d.txt' } if element.lower() not in elements.keys(): raise ValueError('Unknown element \'%s\'' % element) filepath = Path(__file__).parent / "data" / elements[element.lower()] total = [] with filepath.open() as fhd: for line in fhd.read().splitlines(): line = line.strip() if line.startswith("#") or not line.strip(): continue if line.startswith('j = '): result = [] total.append(result) continue # The first field is only an index fields = line.split()[1:] fields[:2] = [float(x) for x in fields[:2]] fields[2:] = [int(x) for x in fields[2:]] result.append(fields) return total
[ "def", "_tab", "(", "element", ")", ":", "elements", "=", "{", "'x'", ":", "'tab5.2a.txt'", ",", "'y'", ":", "'tab5.2b.txt'", ",", "'s'", ":", "'tab5.2d.txt'", "}", "if", "element", ".", "lower", "(", ")", "not", "in", "elements", ".", "keys", "(", "...
Extraction and caching of IAU2000 nutation coefficients
[ "Extraction", "and", "caching", "of", "IAU2000", "nutation", "coefficients" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau2010.py#L15-L51
train
33,828
galactics/beyond
beyond/frames/iau2010.py
_earth_orientation
def _earth_orientation(date): """Earth orientation parameters in degrees """ ttt = date.change_scale('TT').julian_century # a_a = 0.12 # a_c = 0.26 # s_prime = -0.0015 * (a_c ** 2 / 1.2 + a_a ** 2) * ttt s_prime = - 0.000047 * ttt return date.eop.x / 3600., date.eop.y / 3600., s_prime / 3600
python
def _earth_orientation(date): """Earth orientation parameters in degrees """ ttt = date.change_scale('TT').julian_century # a_a = 0.12 # a_c = 0.26 # s_prime = -0.0015 * (a_c ** 2 / 1.2 + a_a ** 2) * ttt s_prime = - 0.000047 * ttt return date.eop.x / 3600., date.eop.y / 3600., s_prime / 3600
[ "def", "_earth_orientation", "(", "date", ")", ":", "ttt", "=", "date", ".", "change_scale", "(", "'TT'", ")", ".", "julian_century", "# a_a = 0.12", "# a_c = 0.26", "# s_prime = -0.0015 * (a_c ** 2 / 1.2 + a_a ** 2) * ttt", "s_prime", "=", "-", "0.000047", "*", "ttt"...
Earth orientation parameters in degrees
[ "Earth", "orientation", "parameters", "in", "degrees" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau2010.py#L54-L64
train
33,829
galactics/beyond
beyond/frames/iau2010.py
earth_orientation
def earth_orientation(date): """Earth orientation as a rotating matrix """ x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date)) return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)
python
def earth_orientation(date): """Earth orientation as a rotating matrix """ x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date)) return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)
[ "def", "earth_orientation", "(", "date", ")", ":", "x_p", ",", "y_p", ",", "s_prime", "=", "np", ".", "deg2rad", "(", "_earth_orientation", "(", "date", ")", ")", "return", "rot3", "(", "-", "s_prime", ")", "@", "rot2", "(", "x_p", ")", "@", "rot1", ...
Earth orientation as a rotating matrix
[ "Earth", "orientation", "as", "a", "rotating", "matrix" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau2010.py#L67-L72
train
33,830
galactics/beyond
beyond/frames/iau2010.py
_xys
def _xys(date): """Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians """ X, Y, s_xy2 = _xysxy2(date) # convert milli-arcsecond to arcsecond dX, dY = date.eop.dx / 1000., date.eop.dy / 1000. # Convert arcsecond to degrees then to radians X = np.radians((X + dX) / 3600.) Y = np.radians((Y + dY) / 3600.) s = np.radians(s_xy2 / 3600.) - (X * Y / 2) return X, Y, s
python
def _xys(date): """Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians """ X, Y, s_xy2 = _xysxy2(date) # convert milli-arcsecond to arcsecond dX, dY = date.eop.dx / 1000., date.eop.dy / 1000. # Convert arcsecond to degrees then to radians X = np.radians((X + dX) / 3600.) Y = np.radians((Y + dY) / 3600.) s = np.radians(s_xy2 / 3600.) - (X * Y / 2) return X, Y, s
[ "def", "_xys", "(", "date", ")", ":", "X", ",", "Y", ",", "s_xy2", "=", "_xysxy2", "(", "date", ")", "# convert milli-arcsecond to arcsecond", "dX", ",", "dY", "=", "date", ".", "eop", ".", "dx", "/", "1000.", ",", "date", ".", "eop", ".", "dy", "/...
Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians
[ "Get", "The", "X", "Y", "and", "s", "coordinates" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau2010.py#L188-L207
train
33,831
galactics/beyond
beyond/propagators/sgp4.py
Sgp4.orbit
def orbit(self, orbit): """Initialize the propagator Args: orbit (Orbit) """ self._orbit = orbit tle = Tle.from_orbit(orbit) lines = tle.text.splitlines() if len(lines) == 3: _, line1, line2 = lines else: line1, line2 = lines self.tle = twoline2rv(line1, line2, wgs72)
python
def orbit(self, orbit): """Initialize the propagator Args: orbit (Orbit) """ self._orbit = orbit tle = Tle.from_orbit(orbit) lines = tle.text.splitlines() if len(lines) == 3: _, line1, line2 = lines else: line1, line2 = lines self.tle = twoline2rv(line1, line2, wgs72)
[ "def", "orbit", "(", "self", ",", "orbit", ")", ":", "self", ".", "_orbit", "=", "orbit", "tle", "=", "Tle", ".", "from_orbit", "(", "orbit", ")", "lines", "=", "tle", ".", "text", ".", "splitlines", "(", ")", "if", "len", "(", "lines", ")", "=="...
Initialize the propagator Args: orbit (Orbit)
[ "Initialize", "the", "propagator" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/sgp4.py#L21-L37
train
33,832
galactics/beyond
beyond/propagators/sgp4.py
Sgp4.propagate
def propagate(self, date): """Propagate the initialized orbit Args: date (Date or datetime.timedelta) Return: Orbit """ if type(date) is timedelta: date = self.orbit.date + date # Convert the date to a tuple usable by the sgp4 library _date = [float(x) for x in "{:%Y %m %d %H %M %S.%f}".format(date).split()] p, v = self.tle.propagate(*_date) # Convert from km to meters result = [x * 1000 for x in p + v] return self.orbit.__class__( date, result, 'cartesian', 'TEME', self.__class__(), **self.orbit.complements )
python
def propagate(self, date): """Propagate the initialized orbit Args: date (Date or datetime.timedelta) Return: Orbit """ if type(date) is timedelta: date = self.orbit.date + date # Convert the date to a tuple usable by the sgp4 library _date = [float(x) for x in "{:%Y %m %d %H %M %S.%f}".format(date).split()] p, v = self.tle.propagate(*_date) # Convert from km to meters result = [x * 1000 for x in p + v] return self.orbit.__class__( date, result, 'cartesian', 'TEME', self.__class__(), **self.orbit.complements )
[ "def", "propagate", "(", "self", ",", "date", ")", ":", "if", "type", "(", "date", ")", "is", "timedelta", ":", "date", "=", "self", ".", "orbit", ".", "date", "+", "date", "# Convert the date to a tuple usable by the sgp4 library", "_date", "=", "[", "float...
Propagate the initialized orbit Args: date (Date or datetime.timedelta) Return: Orbit
[ "Propagate", "the", "initialized", "orbit" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/sgp4.py#L39-L65
train
33,833
galactics/beyond
beyond/frames/local.py
to_tnw
def to_tnw(orbit): """In the TNW Local Orbital Reference Frame, x is oriented along the velocity vector, z along the angular momentum, and y complete the frame. Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to TNW. >>> delta_tnw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_tnw(pv).T >>> delta_inert = mat @ delta_tnw >>> all(delta_inert == v / norm(v)) True """ pos, vel = _split(orbit) t = vel / norm(vel) w = np.cross(pos, vel) / (norm(pos) * norm(vel)) n = np.cross(w, t) return np.array([t, n, w])
python
def to_tnw(orbit): """In the TNW Local Orbital Reference Frame, x is oriented along the velocity vector, z along the angular momentum, and y complete the frame. Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to TNW. >>> delta_tnw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_tnw(pv).T >>> delta_inert = mat @ delta_tnw >>> all(delta_inert == v / norm(v)) True """ pos, vel = _split(orbit) t = vel / norm(vel) w = np.cross(pos, vel) / (norm(pos) * norm(vel)) n = np.cross(w, t) return np.array([t, n, w])
[ "def", "to_tnw", "(", "orbit", ")", ":", "pos", ",", "vel", "=", "_split", "(", "orbit", ")", "t", "=", "vel", "/", "norm", "(", "vel", ")", "w", "=", "np", ".", "cross", "(", "pos", ",", "vel", ")", "/", "(", "norm", "(", "pos", ")", "*", ...
In the TNW Local Orbital Reference Frame, x is oriented along the velocity vector, z along the angular momentum, and y complete the frame. Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to TNW. >>> delta_tnw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_tnw(pv).T >>> delta_inert = mat @ delta_tnw >>> all(delta_inert == v / norm(v)) True
[ "In", "the", "TNW", "Local", "Orbital", "Reference", "Frame", "x", "is", "oriented", "along", "the", "velocity", "vector", "z", "along", "the", "angular", "momentum", "and", "y", "complete", "the", "frame", "." ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/local.py#L13-L38
train
33,834
galactics/beyond
beyond/frames/local.py
to_qsw
def to_qsw(orbit): """In the QSW Local Orbital Reference Frame, x is oriented along the position vector, z along the angular momentum, and y complete the frame. The frame is sometimes also called RSW (where R stands for radial) or LVLH (Local Vertical Local Horizontal). Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to QSW >>> delta_qsw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_qsw(pv).T >>> delta_inert = mat @ delta_qsw >>> all(delta_inert == p / norm(p)) True """ pos, vel = _split(orbit) q = pos / norm(pos) w = np.cross(pos, vel) / (norm(pos) * norm(vel)) s = np.cross(w, q) return np.array([q, s, w])
python
def to_qsw(orbit): """In the QSW Local Orbital Reference Frame, x is oriented along the position vector, z along the angular momentum, and y complete the frame. The frame is sometimes also called RSW (where R stands for radial) or LVLH (Local Vertical Local Horizontal). Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to QSW >>> delta_qsw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_qsw(pv).T >>> delta_inert = mat @ delta_qsw >>> all(delta_inert == p / norm(p)) True """ pos, vel = _split(orbit) q = pos / norm(pos) w = np.cross(pos, vel) / (norm(pos) * norm(vel)) s = np.cross(w, q) return np.array([q, s, w])
[ "def", "to_qsw", "(", "orbit", ")", ":", "pos", ",", "vel", "=", "_split", "(", "orbit", ")", "q", "=", "pos", "/", "norm", "(", "pos", ")", "w", "=", "np", ".", "cross", "(", "pos", ",", "vel", ")", "/", "(", "norm", "(", "pos", ")", "*", ...
In the QSW Local Orbital Reference Frame, x is oriented along the position vector, z along the angular momentum, and y complete the frame. The frame is sometimes also called RSW (where R stands for radial) or LVLH (Local Vertical Local Horizontal). Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to QSW >>> delta_qsw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_qsw(pv).T >>> delta_inert = mat @ delta_qsw >>> all(delta_inert == p / norm(p)) True
[ "In", "the", "QSW", "Local", "Orbital", "Reference", "Frame", "x", "is", "oriented", "along", "the", "position", "vector", "z", "along", "the", "angular", "momentum", "and", "y", "complete", "the", "frame", "." ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/local.py#L41-L69
train
33,835
galactics/beyond
beyond/orbits/tle.py
_float
def _float(text): """Fonction to convert the 'decimal point assumed' format of TLE to actual float >>> _float('0000+0') 0.0 >>> _float('+0000+0') 0.0 >>> _float('34473-3') 0.00034473 >>> _float('-60129-4') -6.0129e-05 >>> _float('+45871-4') 4.5871e-05 """ text = text.strip() if text[0] in ('-', '+'): text = "%s.%s" % (text[0], text[1:]) else: text = "+.%s" % text if "+" in text[1:] or "-" in text[1:]: value, exp_sign, expo = text.rpartition('+') if '+' in text[1:] else text.rpartition('-') v = float('{value}e{exp_sign}{expo}'.format(value=value, exp_sign=exp_sign, expo=expo)) else: v = float(text) return v
python
def _float(text): """Fonction to convert the 'decimal point assumed' format of TLE to actual float >>> _float('0000+0') 0.0 >>> _float('+0000+0') 0.0 >>> _float('34473-3') 0.00034473 >>> _float('-60129-4') -6.0129e-05 >>> _float('+45871-4') 4.5871e-05 """ text = text.strip() if text[0] in ('-', '+'): text = "%s.%s" % (text[0], text[1:]) else: text = "+.%s" % text if "+" in text[1:] or "-" in text[1:]: value, exp_sign, expo = text.rpartition('+') if '+' in text[1:] else text.rpartition('-') v = float('{value}e{exp_sign}{expo}'.format(value=value, exp_sign=exp_sign, expo=expo)) else: v = float(text) return v
[ "def", "_float", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "text", "[", "0", "]", "in", "(", "'-'", ",", "'+'", ")", ":", "text", "=", "\"%s.%s\"", "%", "(", "text", "[", "0", "]", ",", "text", "[", "1", ":",...
Fonction to convert the 'decimal point assumed' format of TLE to actual float >>> _float('0000+0') 0.0 >>> _float('+0000+0') 0.0 >>> _float('34473-3') 0.00034473 >>> _float('-60129-4') -6.0129e-05 >>> _float('+45871-4') 4.5871e-05
[ "Fonction", "to", "convert", "the", "decimal", "point", "assumed", "format", "of", "TLE", "to", "actual", "float" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L49-L79
train
33,836
galactics/beyond
beyond/orbits/tle.py
_unfloat
def _unfloat(flt, precision=5): """Function to convert float to 'decimal point assumed' format >>> _unfloat(0) '00000-0' >>> _unfloat(3.4473e-4) '34473-3' >>> _unfloat(-6.0129e-05) '-60129-4' >>> _unfloat(4.5871e-05) '45871-4' """ if flt == 0.: return "{}-0".format("0" * precision) num, _, exp = "{:.{}e}".format(flt, precision - 1).partition('e') exp = int(exp) num = num.replace('.', '') return "%s%d" % (num, exp + 1)
python
def _unfloat(flt, precision=5): """Function to convert float to 'decimal point assumed' format >>> _unfloat(0) '00000-0' >>> _unfloat(3.4473e-4) '34473-3' >>> _unfloat(-6.0129e-05) '-60129-4' >>> _unfloat(4.5871e-05) '45871-4' """ if flt == 0.: return "{}-0".format("0" * precision) num, _, exp = "{:.{}e}".format(flt, precision - 1).partition('e') exp = int(exp) num = num.replace('.', '') return "%s%d" % (num, exp + 1)
[ "def", "_unfloat", "(", "flt", ",", "precision", "=", "5", ")", ":", "if", "flt", "==", "0.", ":", "return", "\"{}-0\"", ".", "format", "(", "\"0\"", "*", "precision", ")", "num", ",", "_", ",", "exp", "=", "\"{:.{}e}\"", ".", "format", "(", "flt",...
Function to convert float to 'decimal point assumed' format >>> _unfloat(0) '00000-0' >>> _unfloat(3.4473e-4) '34473-3' >>> _unfloat(-6.0129e-05) '-60129-4' >>> _unfloat(4.5871e-05) '45871-4'
[ "Function", "to", "convert", "float", "to", "decimal", "point", "assumed", "format" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L82-L102
train
33,837
galactics/beyond
beyond/orbits/tle.py
Tle._check_validity
def _check_validity(cls, text): """Check the validity of a TLE Args: text (tuple of str) Raise: ValueError """ if not text[0].lstrip().startswith('1 ') or not text[1].lstrip().startswith('2 '): raise ValueError("Line number check failed") for line in text: line = line.strip() if str(cls._checksum(line)) != line[-1]: raise ValueError("Checksum validation failed")
python
def _check_validity(cls, text): """Check the validity of a TLE Args: text (tuple of str) Raise: ValueError """ if not text[0].lstrip().startswith('1 ') or not text[1].lstrip().startswith('2 '): raise ValueError("Line number check failed") for line in text: line = line.strip() if str(cls._checksum(line)) != line[-1]: raise ValueError("Checksum validation failed")
[ "def", "_check_validity", "(", "cls", ",", "text", ")", ":", "if", "not", "text", "[", "0", "]", ".", "lstrip", "(", ")", ".", "startswith", "(", "'1 '", ")", "or", "not", "text", "[", "1", "]", ".", "lstrip", "(", ")", ".", "startswith", "(", ...
Check the validity of a TLE Args: text (tuple of str) Raise: ValueError
[ "Check", "the", "validity", "of", "a", "TLE" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L163-L178
train
33,838
galactics/beyond
beyond/orbits/tle.py
Tle._checksum
def _checksum(cls, line): """Compute the checksum of a full line Args: line (str): Line to compute the checksum from Return: int: Checksum (modulo 10) """ tr_table = str.maketrans({c: None for c in ascii_uppercase + "+ ."}) no_letters = line[:68].translate(tr_table).replace("-", "1") return sum([int(l) for l in no_letters]) % 10
python
def _checksum(cls, line): """Compute the checksum of a full line Args: line (str): Line to compute the checksum from Return: int: Checksum (modulo 10) """ tr_table = str.maketrans({c: None for c in ascii_uppercase + "+ ."}) no_letters = line[:68].translate(tr_table).replace("-", "1") return sum([int(l) for l in no_letters]) % 10
[ "def", "_checksum", "(", "cls", ",", "line", ")", ":", "tr_table", "=", "str", ".", "maketrans", "(", "{", "c", ":", "None", "for", "c", "in", "ascii_uppercase", "+", "\"+ .\"", "}", ")", "no_letters", "=", "line", "[", ":", "68", "]", ".", "transl...
Compute the checksum of a full line Args: line (str): Line to compute the checksum from Return: int: Checksum (modulo 10)
[ "Compute", "the", "checksum", "of", "a", "full", "line" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L181-L191
train
33,839
galactics/beyond
beyond/orbits/tle.py
Tle.orbit
def orbit(self): """Convert TLE to Orbit object, in order to make computations on it Return: ~beyond.orbits.orbit.Orbit: """ data = { 'bstar': self.bstar, 'ndot': self.ndot, 'ndotdot': self.ndotdot, 'tle': self.text } return Orbit(self.epoch, self.to_list(), "TLE", "TEME", 'Sgp4', **data)
python
def orbit(self): """Convert TLE to Orbit object, in order to make computations on it Return: ~beyond.orbits.orbit.Orbit: """ data = { 'bstar': self.bstar, 'ndot': self.ndot, 'ndotdot': self.ndotdot, 'tle': self.text } return Orbit(self.epoch, self.to_list(), "TLE", "TEME", 'Sgp4', **data)
[ "def", "orbit", "(", "self", ")", ":", "data", "=", "{", "'bstar'", ":", "self", ".", "bstar", ",", "'ndot'", ":", "self", ".", "ndot", ",", "'ndotdot'", ":", "self", ".", "ndotdot", ",", "'tle'", ":", "self", ".", "text", "}", "return", "Orbit", ...
Convert TLE to Orbit object, in order to make computations on it Return: ~beyond.orbits.orbit.Orbit:
[ "Convert", "TLE", "to", "Orbit", "object", "in", "order", "to", "make", "computations", "on", "it" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L199-L211
train
33,840
galactics/beyond
beyond/orbits/tle.py
Tle.from_string
def from_string(cls, text, comments="#", error="warn"): """Generator of TLEs from a string Args: text (str): A text containing many TLEs comments (str): If a line starts with this character, it is ignored error (str): How to handle errors while parsing the text. Could be 'raise', 'warn' or 'ignore'. Yields: Tle: """ cache = [] for line in text.splitlines(): # If the line is empty or begins with a comment mark, we skip it. if not line.strip() or line.startswith(comments): continue # The startswith conditions include a blank space in order to not take into account # lines containing only a COSPAR ID, which happens when an object is detected but the # JSpOc doesn't know what is the source yet. if line.startswith('1 '): cache.append(line) elif line.startswith('2 '): cache.append(line) try: yield cls("\n".join(cache)) except ValueError as e: if error in ('raise', 'warn'): if error == "raise": raise else: log.warning(str(e)) cache = [] else: # In the 3LE format, the first line (numbered 0, or unnumbered) contains the name # of the satellite # In the TLE format, this line doesn't exists. cache = [line]
python
def from_string(cls, text, comments="#", error="warn"): """Generator of TLEs from a string Args: text (str): A text containing many TLEs comments (str): If a line starts with this character, it is ignored error (str): How to handle errors while parsing the text. Could be 'raise', 'warn' or 'ignore'. Yields: Tle: """ cache = [] for line in text.splitlines(): # If the line is empty or begins with a comment mark, we skip it. if not line.strip() or line.startswith(comments): continue # The startswith conditions include a blank space in order to not take into account # lines containing only a COSPAR ID, which happens when an object is detected but the # JSpOc doesn't know what is the source yet. if line.startswith('1 '): cache.append(line) elif line.startswith('2 '): cache.append(line) try: yield cls("\n".join(cache)) except ValueError as e: if error in ('raise', 'warn'): if error == "raise": raise else: log.warning(str(e)) cache = [] else: # In the 3LE format, the first line (numbered 0, or unnumbered) contains the name # of the satellite # In the TLE format, this line doesn't exists. cache = [line]
[ "def", "from_string", "(", "cls", ",", "text", ",", "comments", "=", "\"#\"", ",", "error", "=", "\"warn\"", ")", ":", "cache", "=", "[", "]", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "# If the line is empty or begins with a comment mar...
Generator of TLEs from a string Args: text (str): A text containing many TLEs comments (str): If a line starts with this character, it is ignored error (str): How to handle errors while parsing the text. Could be 'raise', 'warn' or 'ignore'. Yields: Tle:
[ "Generator", "of", "TLEs", "from", "a", "string" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L264-L304
train
33,841
galactics/beyond
beyond/frames/frames.py
orbit2frame
def orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False): """Create a frame based on a Orbit or Ephem object. Args: name (str): Name to give the created frame ref_orbit (Orbit or Ephem): orientation (str): Orientation of the created frame bypass (bool): By-pass the warning when creating a frame with an already taken name Return: Frame: If orientation is ``None``, the new frame will keep the orientation of the reference frame of the Orbit and move along with the orbit. Other acceptable values are ``"QSW"`` (and its aliases "LVLH" and "RSW") or ``"TNW"``. See :py:func:`~beyond.frames.local.to_qsw` and :py:func:`~beyond.frames.local.to_tnw` for informations regarding these orientations. """ if orientation is None: orientation = ref_orbit.frame.orientation elif orientation.upper() in ("RSW", "LVLH"): orientation = "QSW" elif orientation.upper() not in ("QSW", "TNW"): raise ValueError("Unknown orientation '%s'" % orientation) if center is None: center = Earth def _to_parent_frame(self): """Conversion from orbit frame to parent frame """ offset = ref_orbit.propagate(self.date).base.copy() if orientation.upper() in ("QSW", "TNW"): # propagation of the reference orbit to the date of the # converted orbit orb = ref_orbit.propagate(self.date) m = to_qsw(orb) if orientation.upper() == "QSW" else to_tnw(orb) # we transpose the matrix because it represents the conversion # from inertial to local frame, and we'd like the other way around rotation = Frame._convert(m, m).T else: # The orientation is the same as the parent reference frame rotation = np.identity(6) return rotation, offset # define the name of the method of conversion mtd = '_to_%s' % ref_orbit.frame.__name__ # dictionary which defines attributes of the created class dct = { mtd: _to_parent_frame, "orientation": orientation, "center": center, "bypass": bypass, } # Creation of the class cls = _MetaFrame(name, (Frame,), dct) # Link to the parent cls + ref_orbit.frame return cls
python
def orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False): """Create a frame based on a Orbit or Ephem object. Args: name (str): Name to give the created frame ref_orbit (Orbit or Ephem): orientation (str): Orientation of the created frame bypass (bool): By-pass the warning when creating a frame with an already taken name Return: Frame: If orientation is ``None``, the new frame will keep the orientation of the reference frame of the Orbit and move along with the orbit. Other acceptable values are ``"QSW"`` (and its aliases "LVLH" and "RSW") or ``"TNW"``. See :py:func:`~beyond.frames.local.to_qsw` and :py:func:`~beyond.frames.local.to_tnw` for informations regarding these orientations. """ if orientation is None: orientation = ref_orbit.frame.orientation elif orientation.upper() in ("RSW", "LVLH"): orientation = "QSW" elif orientation.upper() not in ("QSW", "TNW"): raise ValueError("Unknown orientation '%s'" % orientation) if center is None: center = Earth def _to_parent_frame(self): """Conversion from orbit frame to parent frame """ offset = ref_orbit.propagate(self.date).base.copy() if orientation.upper() in ("QSW", "TNW"): # propagation of the reference orbit to the date of the # converted orbit orb = ref_orbit.propagate(self.date) m = to_qsw(orb) if orientation.upper() == "QSW" else to_tnw(orb) # we transpose the matrix because it represents the conversion # from inertial to local frame, and we'd like the other way around rotation = Frame._convert(m, m).T else: # The orientation is the same as the parent reference frame rotation = np.identity(6) return rotation, offset # define the name of the method of conversion mtd = '_to_%s' % ref_orbit.frame.__name__ # dictionary which defines attributes of the created class dct = { mtd: _to_parent_frame, "orientation": orientation, "center": center, "bypass": bypass, } # Creation of the class cls = _MetaFrame(name, (Frame,), dct) # Link to the parent cls + ref_orbit.frame return cls
[ "def", "orbit2frame", "(", "name", ",", "ref_orbit", ",", "orientation", "=", "None", ",", "center", "=", "None", ",", "bypass", "=", "False", ")", ":", "if", "orientation", "is", "None", ":", "orientation", "=", "ref_orbit", ".", "frame", ".", "orientat...
Create a frame based on a Orbit or Ephem object. Args: name (str): Name to give the created frame ref_orbit (Orbit or Ephem): orientation (str): Orientation of the created frame bypass (bool): By-pass the warning when creating a frame with an already taken name Return: Frame: If orientation is ``None``, the new frame will keep the orientation of the reference frame of the Orbit and move along with the orbit. Other acceptable values are ``"QSW"`` (and its aliases "LVLH" and "RSW") or ``"TNW"``. See :py:func:`~beyond.frames.local.to_qsw` and :py:func:`~beyond.frames.local.to_tnw` for informations regarding these orientations.
[ "Create", "a", "frame", "based", "on", "a", "Orbit", "or", "Ephem", "object", "." ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/frames.py#L296-L364
train
33,842
galactics/beyond
beyond/frames/frames.py
Frame.transform
def transform(self, new_frame): """Change the frame of the orbit Args: new_frame (str) Return: numpy.ndarray """ steps = self.__class__.steps(new_frame) orbit = self.orbit for _from, _to in steps: from_obj = _from(self.date, orbit) direct = "_to_%s" % _to if hasattr(from_obj, direct): rotation, offset = getattr(from_obj, direct)() else: to_obj = _to(self.date, orbit) inverse = "_to_%s" % _from if hasattr(to_obj, inverse): rotation, offset = getattr(to_obj, inverse)() rotation = rotation.T offset = - offset else: raise NotImplementedError("Unknown transformation {} to {}".format(_from, _to)) if getattr(_from, "_rotation_before_translation", False): # In case of topocentric frame, the rotation is done before the translation orbit = offset + (rotation @ orbit) else: orbit = rotation @ (offset + orbit) return orbit
python
def transform(self, new_frame): """Change the frame of the orbit Args: new_frame (str) Return: numpy.ndarray """ steps = self.__class__.steps(new_frame) orbit = self.orbit for _from, _to in steps: from_obj = _from(self.date, orbit) direct = "_to_%s" % _to if hasattr(from_obj, direct): rotation, offset = getattr(from_obj, direct)() else: to_obj = _to(self.date, orbit) inverse = "_to_%s" % _from if hasattr(to_obj, inverse): rotation, offset = getattr(to_obj, inverse)() rotation = rotation.T offset = - offset else: raise NotImplementedError("Unknown transformation {} to {}".format(_from, _to)) if getattr(_from, "_rotation_before_translation", False): # In case of topocentric frame, the rotation is done before the translation orbit = offset + (rotation @ orbit) else: orbit = rotation @ (offset + orbit) return orbit
[ "def", "transform", "(", "self", ",", "new_frame", ")", ":", "steps", "=", "self", ".", "__class__", ".", "steps", "(", "new_frame", ")", "orbit", "=", "self", ".", "orbit", "for", "_from", ",", "_to", "in", "steps", ":", "from_obj", "=", "_from", "(...
Change the frame of the orbit Args: new_frame (str) Return: numpy.ndarray
[ "Change", "the", "frame", "of", "the", "orbit" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/frames.py#L152-L188
train
33,843
galactics/beyond
beyond/dates/date.py
Timescale._scale_tdb_minus_tt
def _scale_tdb_minus_tt(self, mjd, eop): """Definition of the Barycentric Dynamic Time scale relatively to Terrestrial Time """ jd = mjd + Date.JD_MJD jj = Date._julian_century(jd) m = radians(357.5277233 + 35999.05034 * jj) delta_lambda = radians(246.11 + 0.90251792 * (jd - 2451545.)) return 0.001657 * sin(m) + 0.000022 * sin(delta_lambda)
python
def _scale_tdb_minus_tt(self, mjd, eop): """Definition of the Barycentric Dynamic Time scale relatively to Terrestrial Time """ jd = mjd + Date.JD_MJD jj = Date._julian_century(jd) m = radians(357.5277233 + 35999.05034 * jj) delta_lambda = radians(246.11 + 0.90251792 * (jd - 2451545.)) return 0.001657 * sin(m) + 0.000022 * sin(delta_lambda)
[ "def", "_scale_tdb_minus_tt", "(", "self", ",", "mjd", ",", "eop", ")", ":", "jd", "=", "mjd", "+", "Date", ".", "JD_MJD", "jj", "=", "Date", ".", "_julian_century", "(", "jd", ")", "m", "=", "radians", "(", "357.5277233", "+", "35999.05034", "*", "j...
Definition of the Barycentric Dynamic Time scale relatively to Terrestrial Time
[ "Definition", "of", "the", "Barycentric", "Dynamic", "Time", "scale", "relatively", "to", "Terrestrial", "Time" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/date.py#L46-L53
train
33,844
galactics/beyond
beyond/dates/date.py
Timescale.offset
def offset(self, mjd, new_scale, eop): """Compute the offset necessary in order to convert from one time-scale to another Args: mjd (float): new_scale (str): Name of the desired scale Return: float: offset to apply in seconds """ delta = 0 for one, two in self.steps(new_scale): one = one.name.lower() two = two.name.lower() # find the operation oper = "_scale_{}_minus_{}".format(two, one) # find the reverse operation roper = "_scale_{}_minus_{}".format(one, two) if hasattr(self, oper): delta += getattr(self, oper)(mjd, eop) elif hasattr(self, roper): delta -= getattr(self, roper)(mjd, eop) else: # pragma: no cover raise DateError("Unknown convertion {} => {}".format(one, two)) return delta
python
def offset(self, mjd, new_scale, eop): """Compute the offset necessary in order to convert from one time-scale to another Args: mjd (float): new_scale (str): Name of the desired scale Return: float: offset to apply in seconds """ delta = 0 for one, two in self.steps(new_scale): one = one.name.lower() two = two.name.lower() # find the operation oper = "_scale_{}_minus_{}".format(two, one) # find the reverse operation roper = "_scale_{}_minus_{}".format(one, two) if hasattr(self, oper): delta += getattr(self, oper)(mjd, eop) elif hasattr(self, roper): delta -= getattr(self, roper)(mjd, eop) else: # pragma: no cover raise DateError("Unknown convertion {} => {}".format(one, two)) return delta
[ "def", "offset", "(", "self", ",", "mjd", ",", "new_scale", ",", "eop", ")", ":", "delta", "=", "0", "for", "one", ",", "two", "in", "self", ".", "steps", "(", "new_scale", ")", ":", "one", "=", "one", ".", "name", ".", "lower", "(", ")", "two"...
Compute the offset necessary in order to convert from one time-scale to another Args: mjd (float): new_scale (str): Name of the desired scale Return: float: offset to apply in seconds
[ "Compute", "the", "offset", "necessary", "in", "order", "to", "convert", "from", "one", "time", "-", "scale", "to", "another" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/date.py#L55-L80
train
33,845
galactics/beyond
beyond/dates/date.py
Date.datetime
def datetime(self): """Conversion of the Date object into a ``datetime.datetime`` The resulting object is a timezone-naive instance with the same scale as the originating Date object. """ if 'dt_scale' not in self._cache.keys(): self._cache['dt_scale'] = self._datetime - timedelta(seconds=self._offset) return self._cache['dt_scale']
python
def datetime(self): """Conversion of the Date object into a ``datetime.datetime`` The resulting object is a timezone-naive instance with the same scale as the originating Date object. """ if 'dt_scale' not in self._cache.keys(): self._cache['dt_scale'] = self._datetime - timedelta(seconds=self._offset) return self._cache['dt_scale']
[ "def", "datetime", "(", "self", ")", ":", "if", "'dt_scale'", "not", "in", "self", ".", "_cache", ".", "keys", "(", ")", ":", "self", ".", "_cache", "[", "'dt_scale'", "]", "=", "self", ".", "_datetime", "-", "timedelta", "(", "seconds", "=", "self",...
Conversion of the Date object into a ``datetime.datetime`` The resulting object is a timezone-naive instance with the same scale as the originating Date object.
[ "Conversion", "of", "the", "Date", "object", "into", "a", "datetime", ".", "datetime" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/date.py#L326-L334
train
33,846
galactics/beyond
beyond/dates/date.py
Date.strptime
def strptime(cls, data, format, scale=DEFAULT_SCALE): # pragma: no cover """Convert a string representation of a date to a Date object """ return cls(datetime.strptime(data, format), scale=scale)
python
def strptime(cls, data, format, scale=DEFAULT_SCALE): # pragma: no cover """Convert a string representation of a date to a Date object """ return cls(datetime.strptime(data, format), scale=scale)
[ "def", "strptime", "(", "cls", ",", "data", ",", "format", ",", "scale", "=", "DEFAULT_SCALE", ")", ":", "# pragma: no cover", "return", "cls", "(", "datetime", ".", "strptime", "(", "data", ",", "format", ")", ",", "scale", "=", "scale", ")" ]
Convert a string representation of a date to a Date object
[ "Convert", "a", "string", "representation", "of", "a", "date", "to", "a", "Date", "object" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/date.py#L347-L350
train
33,847
galactics/beyond
beyond/dates/date.py
Date.range
def range(cls, start=None, stop=None, step=None, inclusive=False): """Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not included. This is the same behavior as the built-in :py:func:`range`. Yield: Date: """ def sign(x): """Inner function for determining the sign of a float """ return (-1, 1)[x >= 0] if not step: raise ValueError("Null step") # Convert stop from timedelta to Date object if isinstance(stop, timedelta): stop = start + stop if sign((stop - start).total_seconds()) != sign(step.total_seconds()): raise ValueError("start/stop order not coherent with step") date = start if step.total_seconds() > 0: oper = "__le__" if inclusive else "__lt__" else: oper = "__ge__" if inclusive else "__gt__" while getattr(date, oper)(stop): yield date date += step
python
def range(cls, start=None, stop=None, step=None, inclusive=False): """Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not included. This is the same behavior as the built-in :py:func:`range`. Yield: Date: """ def sign(x): """Inner function for determining the sign of a float """ return (-1, 1)[x >= 0] if not step: raise ValueError("Null step") # Convert stop from timedelta to Date object if isinstance(stop, timedelta): stop = start + stop if sign((stop - start).total_seconds()) != sign(step.total_seconds()): raise ValueError("start/stop order not coherent with step") date = start if step.total_seconds() > 0: oper = "__le__" if inclusive else "__lt__" else: oper = "__ge__" if inclusive else "__gt__" while getattr(date, oper)(stop): yield date date += step
[ "def", "range", "(", "cls", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ",", "inclusive", "=", "False", ")", ":", "def", "sign", "(", "x", ")", ":", "\"\"\"Inner function for determining the sign of a float\n \"\"\...
Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not included. This is the same behavior as the built-in :py:func:`range`. Yield: Date:
[ "Generator", "of", "a", "date", "range" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/date.py#L421-L459
train
33,848
galactics/beyond
beyond/propagators/kepler.py
Kepler._newton
def _newton(self, orb, step): """Newton's Law of Universal Gravitation """ date = orb.date + step new_body = zeros(6) new_body[:3] = orb[3:] for body in self.bodies: # retrieve the position of the body at the given date orb_body = body.propagate(date) orb_body.frame = orb.frame # Compute induced attraction to the object of interest diff = orb_body[:3] - orb[:3] norm = sqrt(sum(diff ** 2)) ** 3 new_body[3:] += G * body.mass * diff / norm return new_body
python
def _newton(self, orb, step): """Newton's Law of Universal Gravitation """ date = orb.date + step new_body = zeros(6) new_body[:3] = orb[3:] for body in self.bodies: # retrieve the position of the body at the given date orb_body = body.propagate(date) orb_body.frame = orb.frame # Compute induced attraction to the object of interest diff = orb_body[:3] - orb[:3] norm = sqrt(sum(diff ** 2)) ** 3 new_body[3:] += G * body.mass * diff / norm return new_body
[ "def", "_newton", "(", "self", ",", "orb", ",", "step", ")", ":", "date", "=", "orb", ".", "date", "+", "step", "new_body", "=", "zeros", "(", "6", ")", "new_body", "[", ":", "3", "]", "=", "orb", "[", "3", ":", "]", "for", "body", "in", "sel...
Newton's Law of Universal Gravitation
[ "Newton", "s", "Law", "of", "Universal", "Gravitation" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/kepler.py#L95-L114
train
33,849
galactics/beyond
beyond/propagators/kepler.py
Kepler._make_step
def _make_step(self, orb, step): """Compute the next step with the selected method """ method = self.BUTCHER[self.method] a, b, c = method['a'], method['b'], method['c'] y_n = orb.copy() ks = [self._newton(y_n, timedelta(0))] for a, c in zip(a[1:], c[1:]): k_plus1 = self._newton(y_n + a @ ks * step.total_seconds(), step * c) ks.append(k_plus1) y_n_1 = y_n + step.total_seconds() * b @ ks y_n_1.date = y_n.date + step # Error estimation, in cases where adaptively methods are used # if 'b_star' in method: # error = step.total_seconds() * (b - method['b_star']) @ ks for man in self.orbit.maneuvers: if man.check(orb, step): log.debug("Applying maneuver at {} ({})".format(man.date, man.comment)) y_n_1[3:] += man.dv(y_n_1) return y_n_1
python
def _make_step(self, orb, step): """Compute the next step with the selected method """ method = self.BUTCHER[self.method] a, b, c = method['a'], method['b'], method['c'] y_n = orb.copy() ks = [self._newton(y_n, timedelta(0))] for a, c in zip(a[1:], c[1:]): k_plus1 = self._newton(y_n + a @ ks * step.total_seconds(), step * c) ks.append(k_plus1) y_n_1 = y_n + step.total_seconds() * b @ ks y_n_1.date = y_n.date + step # Error estimation, in cases where adaptively methods are used # if 'b_star' in method: # error = step.total_seconds() * (b - method['b_star']) @ ks for man in self.orbit.maneuvers: if man.check(orb, step): log.debug("Applying maneuver at {} ({})".format(man.date, man.comment)) y_n_1[3:] += man.dv(y_n_1) return y_n_1
[ "def", "_make_step", "(", "self", ",", "orb", ",", "step", ")", ":", "method", "=", "self", ".", "BUTCHER", "[", "self", ".", "method", "]", "a", ",", "b", ",", "c", "=", "method", "[", "'a'", "]", ",", "method", "[", "'b'", "]", ",", "method",...
Compute the next step with the selected method
[ "Compute", "the", "next", "step", "with", "the", "selected", "method" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/kepler.py#L116-L142
train
33,850
galactics/beyond
beyond/propagators/kepler.py
SOIPropagator._soi
def _soi(self, orb): """Evaluate the need for SOI transition, by comparing the radial distance between the considered body and the spacecraft If therer is no body in sight, default to central body. """ for body in self.alt: soi = self.SOI[body.name] sph = orb.copy(frame=soi.frame, form='spherical') if sph.r < soi.radius: active = body break else: active = self.central return active
python
def _soi(self, orb): """Evaluate the need for SOI transition, by comparing the radial distance between the considered body and the spacecraft If therer is no body in sight, default to central body. """ for body in self.alt: soi = self.SOI[body.name] sph = orb.copy(frame=soi.frame, form='spherical') if sph.r < soi.radius: active = body break else: active = self.central return active
[ "def", "_soi", "(", "self", ",", "orb", ")", ":", "for", "body", "in", "self", ".", "alt", ":", "soi", "=", "self", ".", "SOI", "[", "body", ".", "name", "]", "sph", "=", "orb", ".", "copy", "(", "frame", "=", "soi", ".", "frame", ",", "form"...
Evaluate the need for SOI transition, by comparing the radial distance between the considered body and the spacecraft If therer is no body in sight, default to central body.
[ "Evaluate", "the", "need", "for", "SOI", "transition", "by", "comparing", "the", "radial", "distance", "between", "the", "considered", "body", "and", "the", "spacecraft" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/kepler.py#L232-L248
train
33,851
galactics/beyond
beyond/propagators/kepler.py
SOIPropagator._change_soi
def _change_soi(self, body): """Modify the inner parameters of the Kepler propagator in order to place the spacecraft in the right Sphere of Influence """ if body == self.central: self.bodies = [self.central] self.step = self.central_step self.active = self.central.name self.frame = self.central.name else: soi = self.SOI[body.name] self.bodies = [body] self.step = self.alt_step self.active = body.name self.frame = soi.frame
python
def _change_soi(self, body): """Modify the inner parameters of the Kepler propagator in order to place the spacecraft in the right Sphere of Influence """ if body == self.central: self.bodies = [self.central] self.step = self.central_step self.active = self.central.name self.frame = self.central.name else: soi = self.SOI[body.name] self.bodies = [body] self.step = self.alt_step self.active = body.name self.frame = soi.frame
[ "def", "_change_soi", "(", "self", ",", "body", ")", ":", "if", "body", "==", "self", ".", "central", ":", "self", ".", "bodies", "=", "[", "self", ".", "central", "]", "self", ".", "step", "=", "self", ".", "central_step", "self", ".", "active", "...
Modify the inner parameters of the Kepler propagator in order to place the spacecraft in the right Sphere of Influence
[ "Modify", "the", "inner", "parameters", "of", "the", "Kepler", "propagator", "in", "order", "to", "place", "the", "spacecraft", "in", "the", "right", "Sphere", "of", "Influence" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/propagators/kepler.py#L250-L265
train
33,852
galactics/beyond
beyond/dates/eop.py
register
def register(name=EopDb.DEFAULT_DBNAME): """Decorator for registering an Eop Database Example: .. code-block:: python @register class SqliteEnvDatabase: # sqlite implementation # this database will be known as 'default' @register('json') class JsonEnvDatabase: # JSON implementation EopDb.get(58090.2) # get Eop from SqliteEnvDatabase EopDb.get(58090.2, dbname='default') # same as above EopDb.get(58090.2, dbname='json') # get Eop from JsonEnvDatabase """ # I had a little trouble setting this function up, due to the fact that # I wanted it to be usable both as a simple decorator (``@register``) # and a decorator with arguments (``@register('mydatabase')``). # The current implementation allows this dual-use, but it's a bit hacky. # In the simple decorator mode, when the @register decorator is called # the argument passed is the class to decorate. So it *is* the decorated # function # In the decorator-with-arguments mode, the @register decorator should provide # a callable that will be the decorated function. This callable takes # the class you want to decorate if isinstance(name, str): # decorator with argument def wrapper(klass): EopDb.register(klass, name) return klass return wrapper else: # simple decorator mode klass = name EopDb.register(klass) return klass
python
def register(name=EopDb.DEFAULT_DBNAME): """Decorator for registering an Eop Database Example: .. code-block:: python @register class SqliteEnvDatabase: # sqlite implementation # this database will be known as 'default' @register('json') class JsonEnvDatabase: # JSON implementation EopDb.get(58090.2) # get Eop from SqliteEnvDatabase EopDb.get(58090.2, dbname='default') # same as above EopDb.get(58090.2, dbname='json') # get Eop from JsonEnvDatabase """ # I had a little trouble setting this function up, due to the fact that # I wanted it to be usable both as a simple decorator (``@register``) # and a decorator with arguments (``@register('mydatabase')``). # The current implementation allows this dual-use, but it's a bit hacky. # In the simple decorator mode, when the @register decorator is called # the argument passed is the class to decorate. So it *is* the decorated # function # In the decorator-with-arguments mode, the @register decorator should provide # a callable that will be the decorated function. This callable takes # the class you want to decorate if isinstance(name, str): # decorator with argument def wrapper(klass): EopDb.register(klass, name) return klass return wrapper else: # simple decorator mode klass = name EopDb.register(klass) return klass
[ "def", "register", "(", "name", "=", "EopDb", ".", "DEFAULT_DBNAME", ")", ":", "# I had a little trouble setting this function up, due to the fact that", "# I wanted it to be usable both as a simple decorator (``@register``)", "# and a decorator with arguments (``@register('mydatabase')``)."...
Decorator for registering an Eop Database Example: .. code-block:: python @register class SqliteEnvDatabase: # sqlite implementation # this database will be known as 'default' @register('json') class JsonEnvDatabase: # JSON implementation EopDb.get(58090.2) # get Eop from SqliteEnvDatabase EopDb.get(58090.2, dbname='default') # same as above EopDb.get(58090.2, dbname='json') # get Eop from JsonEnvDatabase
[ "Decorator", "for", "registering", "an", "Eop", "Database" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/eop.py#L296-L343
train
33,853
galactics/beyond
beyond/dates/eop.py
TaiUtc.get_last_next
def get_last_next(self, date): """Provide the last and next leap-second events relative to a date Args: date (float): Date in MJD Return: tuple: """ past, future = (None, None), (None, None) for mjd, value in reversed(self.data): if mjd <= date: past = (mjd, value) break future = (mjd, value) return past, future
python
def get_last_next(self, date): """Provide the last and next leap-second events relative to a date Args: date (float): Date in MJD Return: tuple: """ past, future = (None, None), (None, None) for mjd, value in reversed(self.data): if mjd <= date: past = (mjd, value) break future = (mjd, value) return past, future
[ "def", "get_last_next", "(", "self", ",", "date", ")", ":", "past", ",", "future", "=", "(", "None", ",", "None", ")", ",", "(", "None", ",", "None", ")", "for", "mjd", ",", "value", "in", "reversed", "(", "self", ".", "data", ")", ":", "if", "...
Provide the last and next leap-second events relative to a date Args: date (float): Date in MJD Return: tuple:
[ "Provide", "the", "last", "and", "next", "leap", "-", "second", "events", "relative", "to", "a", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/eop.py#L51-L67
train
33,854
galactics/beyond
beyond/dates/eop.py
EopDb.db
def db(cls, dbname=None): """Retrieve the database Args: dbname: Specify the name of the database to retrieve. If set to `None`, take the name from the configuration (see :ref:`configuration <eop-dbname>`) Return: object """ cls._load_entry_points() dbname = dbname or config.get('eop', 'dbname', fallback=cls.DEFAULT_DBNAME) if dbname not in cls._dbs.keys(): raise EopError("Unknown database '%s'" % dbname) if isclass(cls._dbs[dbname]): # Instanciation try: cls._dbs[dbname] = cls._dbs[dbname]() except Exception as e: # Keep the exception in cache in order to not retry instanciation # every single time EopDb.db() is called, as instanciation # of database is generally a time consumming operation. # If it failed once, it will most probably fail again cls._dbs[dbname] = e if isinstance(cls._dbs[dbname], Exception): raise EopError("Problem at database instanciation") from cls._dbs[dbname] return cls._dbs[dbname]
python
def db(cls, dbname=None): """Retrieve the database Args: dbname: Specify the name of the database to retrieve. If set to `None`, take the name from the configuration (see :ref:`configuration <eop-dbname>`) Return: object """ cls._load_entry_points() dbname = dbname or config.get('eop', 'dbname', fallback=cls.DEFAULT_DBNAME) if dbname not in cls._dbs.keys(): raise EopError("Unknown database '%s'" % dbname) if isclass(cls._dbs[dbname]): # Instanciation try: cls._dbs[dbname] = cls._dbs[dbname]() except Exception as e: # Keep the exception in cache in order to not retry instanciation # every single time EopDb.db() is called, as instanciation # of database is generally a time consumming operation. # If it failed once, it will most probably fail again cls._dbs[dbname] = e if isinstance(cls._dbs[dbname], Exception): raise EopError("Problem at database instanciation") from cls._dbs[dbname] return cls._dbs[dbname]
[ "def", "db", "(", "cls", ",", "dbname", "=", "None", ")", ":", "cls", ".", "_load_entry_points", "(", ")", "dbname", "=", "dbname", "or", "config", ".", "get", "(", "'eop'", ",", "'dbname'", ",", "fallback", "=", "cls", ".", "DEFAULT_DBNAME", ")", "i...
Retrieve the database Args: dbname: Specify the name of the database to retrieve. If set to `None`, take the name from the configuration (see :ref:`configuration <eop-dbname>`) Return: object
[ "Retrieve", "the", "database" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/eop.py#L211-L242
train
33,855
galactics/beyond
beyond/dates/eop.py
EopDb.get
def get(cls, mjd: float, dbname: str = None) -> Eop: """Retrieve Earth Orientation Parameters and timescales differences for a given date Args: mjd: Date expressed as Mean Julian Date dbname: Name of the database to use Return: Eop: Interpolated data for this particuliar MJD """ try: value = cls.db(dbname)[mjd] except (EopError, KeyError) as e: if isinstance(e, KeyError): msg = "Missing EOP data for mjd = '%s'" % e else: msg = str(e) if cls.policy() == cls.WARN: log.warning(msg) elif cls.policy() == cls.ERROR: raise value = Eop(x=0, y=0, dx=0, dy=0, deps=0, dpsi=0, lod=0, ut1_utc=0, tai_utc=0) return value
python
def get(cls, mjd: float, dbname: str = None) -> Eop: """Retrieve Earth Orientation Parameters and timescales differences for a given date Args: mjd: Date expressed as Mean Julian Date dbname: Name of the database to use Return: Eop: Interpolated data for this particuliar MJD """ try: value = cls.db(dbname)[mjd] except (EopError, KeyError) as e: if isinstance(e, KeyError): msg = "Missing EOP data for mjd = '%s'" % e else: msg = str(e) if cls.policy() == cls.WARN: log.warning(msg) elif cls.policy() == cls.ERROR: raise value = Eop(x=0, y=0, dx=0, dy=0, deps=0, dpsi=0, lod=0, ut1_utc=0, tai_utc=0) return value
[ "def", "get", "(", "cls", ",", "mjd", ":", "float", ",", "dbname", ":", "str", "=", "None", ")", "->", "Eop", ":", "try", ":", "value", "=", "cls", ".", "db", "(", "dbname", ")", "[", "mjd", "]", "except", "(", "EopError", ",", "KeyError", ")",...
Retrieve Earth Orientation Parameters and timescales differences for a given date Args: mjd: Date expressed as Mean Julian Date dbname: Name of the database to use Return: Eop: Interpolated data for this particuliar MJD
[ "Retrieve", "Earth", "Orientation", "Parameters", "and", "timescales", "differences", "for", "a", "given", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/eop.py#L245-L271
train
33,856
galactics/beyond
beyond/dates/eop.py
EopDb.register
def register(cls, klass, name=DEFAULT_DBNAME): """Register an Eop Database The only requirement of this database is that it should have ``__getitem__`` method accepting MJD as float. """ if name in cls._dbs: msg = "'{}' is already registered for an Eop database. Skipping".format(name) log.warning(msg) else: cls._dbs[name] = klass
python
def register(cls, klass, name=DEFAULT_DBNAME): """Register an Eop Database The only requirement of this database is that it should have ``__getitem__`` method accepting MJD as float. """ if name in cls._dbs: msg = "'{}' is already registered for an Eop database. Skipping".format(name) log.warning(msg) else: cls._dbs[name] = klass
[ "def", "register", "(", "cls", ",", "klass", ",", "name", "=", "DEFAULT_DBNAME", ")", ":", "if", "name", "in", "cls", ".", "_dbs", ":", "msg", "=", "\"'{}' is already registered for an Eop database. Skipping\"", ".", "format", "(", "name", ")", "log", ".", "...
Register an Eop Database The only requirement of this database is that it should have ``__getitem__`` method accepting MJD as float.
[ "Register", "an", "Eop", "Database" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/dates/eop.py#L282-L293
train
33,857
galactics/beyond
beyond/frames/iau1980.py
_tab
def _tab(max_i=None): """Extraction and caching of IAU1980 nutation coefficients """ filepath = Path(__file__).parent / "data" / "tab5.1.txt" result = [] with filepath.open() as fhd: i = 0 for line in fhd.read().splitlines(): if line.startswith("#") or not line.strip(): continue fields = line.split() result.append(([int(x) for x in fields[:5]], [float(x) for x in fields[6:]])) i += 1 if max_i and i >= max_i: break return result
python
def _tab(max_i=None): """Extraction and caching of IAU1980 nutation coefficients """ filepath = Path(__file__).parent / "data" / "tab5.1.txt" result = [] with filepath.open() as fhd: i = 0 for line in fhd.read().splitlines(): if line.startswith("#") or not line.strip(): continue fields = line.split() result.append(([int(x) for x in fields[:5]], [float(x) for x in fields[6:]])) i += 1 if max_i and i >= max_i: break return result
[ "def", "_tab", "(", "max_i", "=", "None", ")", ":", "filepath", "=", "Path", "(", "__file__", ")", ".", "parent", "/", "\"data\"", "/", "\"tab5.1.txt\"", "result", "=", "[", "]", "with", "filepath", ".", "open", "(", ")", "as", "fhd", ":", "i", "="...
Extraction and caching of IAU1980 nutation coefficients
[ "Extraction", "and", "caching", "of", "IAU1980", "nutation", "coefficients" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L15-L35
train
33,858
galactics/beyond
beyond/frames/iau1980.py
_precesion
def _precesion(date): """Precession in degrees """ t = date.change_scale('TT').julian_century zeta = (2306.2181 * t + 0.30188 * t ** 2 + 0.017998 * t ** 3) / 3600. theta = (2004.3109 * t - 0.42665 * t ** 2 - 0.041833 * t ** 3) / 3600. z = (2306.2181 * t + 1.09468 * t ** 2 + 0.018203 * t ** 3) / 3600. # print("zeta = {}\ntheta = {}\nz = {}\n".format(zeta, theta, z)) return zeta, theta, z
python
def _precesion(date): """Precession in degrees """ t = date.change_scale('TT').julian_century zeta = (2306.2181 * t + 0.30188 * t ** 2 + 0.017998 * t ** 3) / 3600. theta = (2004.3109 * t - 0.42665 * t ** 2 - 0.041833 * t ** 3) / 3600. z = (2306.2181 * t + 1.09468 * t ** 2 + 0.018203 * t ** 3) / 3600. # print("zeta = {}\ntheta = {}\nz = {}\n".format(zeta, theta, z)) return zeta, theta, z
[ "def", "_precesion", "(", "date", ")", ":", "t", "=", "date", ".", "change_scale", "(", "'TT'", ")", ".", "julian_century", "zeta", "=", "(", "2306.2181", "*", "t", "+", "0.30188", "*", "t", "**", "2", "+", "0.017998", "*", "t", "**", "3", ")", "...
Precession in degrees
[ "Precession", "in", "degrees" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L58-L69
train
33,859
galactics/beyond
beyond/frames/iau1980.py
precesion
def precesion(date): # pragma: no cover """Precession as a rotation matrix """ zeta, theta, z = np.deg2rad(_precesion(date)) return rot3(zeta) @ rot2(-theta) @ rot3(z)
python
def precesion(date): # pragma: no cover """Precession as a rotation matrix """ zeta, theta, z = np.deg2rad(_precesion(date)) return rot3(zeta) @ rot2(-theta) @ rot3(z)
[ "def", "precesion", "(", "date", ")", ":", "# pragma: no cover", "zeta", ",", "theta", ",", "z", "=", "np", ".", "deg2rad", "(", "_precesion", "(", "date", ")", ")", "return", "rot3", "(", "zeta", ")", "@", "rot2", "(", "-", "theta", ")", "@", "rot...
Precession as a rotation matrix
[ "Precession", "as", "a", "rotation", "matrix" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L72-L76
train
33,860
galactics/beyond
beyond/frames/iau1980.py
_nutation
def _nutation(date, eop_correction=True, terms=106): """Model 1980 of nutation as described in Vallado p. 224 Args: date (beyond.utils.date.Date) eop_correction (bool): set to ``True`` to include model correction from 'finals' files. terms (int) Return: tuple : 3-elements, all floats in degrees 1. ̄ε 2. Δψ 3. Δε Warning: The good version of the nutation model can be found in the **errata** of the 4th edition of *Fundamentals of Astrodynamics and Applications* by Vallado. """ ttt = date.change_scale('TT').julian_century r = 360. # in arcsecond epsilon_bar = 84381.448 - 46.8150 * ttt - 5.9e-4 * ttt ** 2\ + 1.813e-3 * ttt ** 3 # Conversion to degrees epsilon_bar /= 3600. # mean anomaly of the moon m_m = 134.96298139 + (1325 * r + 198.8673981) * ttt\ + 0.0086972 * ttt ** 2 + 1.78e-5 * ttt ** 3 # mean anomaly of the sun m_s = 357.52772333 + (99 * r + 359.0503400) * ttt\ - 0.0001603 * ttt ** 2 - 3.3e-6 * ttt ** 3 # L - Omega u_m_m = 93.27191028 + (1342 * r + 82.0175381) * ttt\ - 0.0036825 * ttt ** 2 + 3.1e-6 * ttt ** 3 # Mean elongation of the moon from the sun d_s = 297.85036306 + (1236 * r + 307.11148) * ttt\ - 0.0019142 * ttt ** 2 + 5.3e-6 * ttt ** 3 # Mean longitude of the ascending node of the moon om_m = 125.04452222 - (5 * r + 134.1362608) * ttt\ + 0.0020708 * ttt ** 2 + 2.2e-6 * ttt ** 3 delta_psi = 0. delta_eps = 0. for integers, reals in _tab(terms): a1, a2, a3, a4, a5 = integers # Conversion from 0.1 mas to mas A, B, C, D = np.array(list(reals)) / 36000000. a_p = a1 * m_m + a2 * m_s + a3 * u_m_m + a4 * d_s + a5 * om_m # a_p %= 360. delta_psi += (A + B * ttt) * np.sin(np.deg2rad(a_p)) delta_eps += (C + D * ttt) * np.cos(np.deg2rad(a_p)) if eop_correction: delta_eps += date.eop.deps / 3600000. delta_psi += date.eop.dpsi / 3600000. return epsilon_bar, delta_psi, delta_eps
python
def _nutation(date, eop_correction=True, terms=106): """Model 1980 of nutation as described in Vallado p. 224 Args: date (beyond.utils.date.Date) eop_correction (bool): set to ``True`` to include model correction from 'finals' files. terms (int) Return: tuple : 3-elements, all floats in degrees 1. ̄ε 2. Δψ 3. Δε Warning: The good version of the nutation model can be found in the **errata** of the 4th edition of *Fundamentals of Astrodynamics and Applications* by Vallado. """ ttt = date.change_scale('TT').julian_century r = 360. # in arcsecond epsilon_bar = 84381.448 - 46.8150 * ttt - 5.9e-4 * ttt ** 2\ + 1.813e-3 * ttt ** 3 # Conversion to degrees epsilon_bar /= 3600. # mean anomaly of the moon m_m = 134.96298139 + (1325 * r + 198.8673981) * ttt\ + 0.0086972 * ttt ** 2 + 1.78e-5 * ttt ** 3 # mean anomaly of the sun m_s = 357.52772333 + (99 * r + 359.0503400) * ttt\ - 0.0001603 * ttt ** 2 - 3.3e-6 * ttt ** 3 # L - Omega u_m_m = 93.27191028 + (1342 * r + 82.0175381) * ttt\ - 0.0036825 * ttt ** 2 + 3.1e-6 * ttt ** 3 # Mean elongation of the moon from the sun d_s = 297.85036306 + (1236 * r + 307.11148) * ttt\ - 0.0019142 * ttt ** 2 + 5.3e-6 * ttt ** 3 # Mean longitude of the ascending node of the moon om_m = 125.04452222 - (5 * r + 134.1362608) * ttt\ + 0.0020708 * ttt ** 2 + 2.2e-6 * ttt ** 3 delta_psi = 0. delta_eps = 0. for integers, reals in _tab(terms): a1, a2, a3, a4, a5 = integers # Conversion from 0.1 mas to mas A, B, C, D = np.array(list(reals)) / 36000000. a_p = a1 * m_m + a2 * m_s + a3 * u_m_m + a4 * d_s + a5 * om_m # a_p %= 360. delta_psi += (A + B * ttt) * np.sin(np.deg2rad(a_p)) delta_eps += (C + D * ttt) * np.cos(np.deg2rad(a_p)) if eop_correction: delta_eps += date.eop.deps / 3600000. delta_psi += date.eop.dpsi / 3600000. return epsilon_bar, delta_psi, delta_eps
[ "def", "_nutation", "(", "date", ",", "eop_correction", "=", "True", ",", "terms", "=", "106", ")", ":", "ttt", "=", "date", ".", "change_scale", "(", "'TT'", ")", ".", "julian_century", "r", "=", "360.", "# in arcsecond", "epsilon_bar", "=", "84381.448", ...
Model 1980 of nutation as described in Vallado p. 224 Args: date (beyond.utils.date.Date) eop_correction (bool): set to ``True`` to include model correction from 'finals' files. terms (int) Return: tuple : 3-elements, all floats in degrees 1. ̄ε 2. Δψ 3. Δε Warning: The good version of the nutation model can be found in the **errata** of the 4th edition of *Fundamentals of Astrodynamics and Applications* by Vallado.
[ "Model", "1980", "of", "nutation", "as", "described", "in", "Vallado", "p", ".", "224" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L80-L146
train
33,861
galactics/beyond
beyond/frames/iau1980.py
nutation
def nutation(date, eop_correction=True, terms=106): # pragma: no cover """Nutation as a rotation matrix """ epsilon_bar, delta_psi, delta_eps = np.deg2rad(_nutation(date, eop_correction, terms)) epsilon = epsilon_bar + delta_eps return rot1(-epsilon_bar) @ rot3(delta_psi) @ rot1(epsilon)
python
def nutation(date, eop_correction=True, terms=106): # pragma: no cover """Nutation as a rotation matrix """ epsilon_bar, delta_psi, delta_eps = np.deg2rad(_nutation(date, eop_correction, terms)) epsilon = epsilon_bar + delta_eps return rot1(-epsilon_bar) @ rot3(delta_psi) @ rot1(epsilon)
[ "def", "nutation", "(", "date", ",", "eop_correction", "=", "True", ",", "terms", "=", "106", ")", ":", "# pragma: no cover", "epsilon_bar", ",", "delta_psi", ",", "delta_eps", "=", "np", ".", "deg2rad", "(", "_nutation", "(", "date", ",", "eop_correction", ...
Nutation as a rotation matrix
[ "Nutation", "as", "a", "rotation", "matrix" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L149-L155
train
33,862
galactics/beyond
beyond/frames/iau1980.py
equinox
def equinox(date, eop_correction=True, terms=106, kinematic=True): """Equinox equation in degrees """ epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms) equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar)) if date.d >= 50506 and kinematic: # Starting 1992-02-27, we apply the effect of the moon ttt = date.change_scale('TT').julian_century om_m = 125.04455501 - (5 * 360. + 134.1361851) * ttt\ + 0.0020756 * ttt ** 2 + 2.139e-6 * ttt ** 3 equin += 0.00264 * np.sin(np.deg2rad(om_m)) + 6.3e-5 * np.sin(np.deg2rad(2 * om_m)) # print("equinox = {}\n".format(equin / 3600)) return equin / 3600.
python
def equinox(date, eop_correction=True, terms=106, kinematic=True): """Equinox equation in degrees """ epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms) equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar)) if date.d >= 50506 and kinematic: # Starting 1992-02-27, we apply the effect of the moon ttt = date.change_scale('TT').julian_century om_m = 125.04455501 - (5 * 360. + 134.1361851) * ttt\ + 0.0020756 * ttt ** 2 + 2.139e-6 * ttt ** 3 equin += 0.00264 * np.sin(np.deg2rad(om_m)) + 6.3e-5 * np.sin(np.deg2rad(2 * om_m)) # print("equinox = {}\n".format(equin / 3600)) return equin / 3600.
[ "def", "equinox", "(", "date", ",", "eop_correction", "=", "True", ",", "terms", "=", "106", ",", "kinematic", "=", "True", ")", ":", "epsilon_bar", ",", "delta_psi", ",", "delta_eps", "=", "_nutation", "(", "date", ",", "eop_correction", ",", "terms", "...
Equinox equation in degrees
[ "Equinox", "equation", "in", "degrees" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L158-L174
train
33,863
galactics/beyond
beyond/frames/iau1980.py
_sideral
def _sideral(date, longitude=0., model='mean', eop_correction=True, terms=106): """Get the sideral time at a defined date Args: date (Date): longitude (float): Longitude of the observer (in degrees) East positive/West negative. model (str): 'mean' or 'apparent' for GMST and GAST respectively Return: float: Sideral time in degrees GMST: Greenwich Mean Sideral Time LST: Local Sideral Time (Mean) GAST: Greenwich Apparent Sideral Time """ t = date.change_scale('UT1').julian_century # Compute GMST in seconds theta = 67310.54841 + (876600 * 3600 + 8640184.812866) * t + 0.093104 * t ** 2\ - 6.2e-6 * t ** 3 # Conversion from second (time) to degrees (angle) theta /= 240. if model == 'apparent': theta += equinox(date, eop_correction, terms) # Add local longitude to the sideral time theta += longitude # Force to 0-360 degrees range theta %= 360. return theta
python
def _sideral(date, longitude=0., model='mean', eop_correction=True, terms=106): """Get the sideral time at a defined date Args: date (Date): longitude (float): Longitude of the observer (in degrees) East positive/West negative. model (str): 'mean' or 'apparent' for GMST and GAST respectively Return: float: Sideral time in degrees GMST: Greenwich Mean Sideral Time LST: Local Sideral Time (Mean) GAST: Greenwich Apparent Sideral Time """ t = date.change_scale('UT1').julian_century # Compute GMST in seconds theta = 67310.54841 + (876600 * 3600 + 8640184.812866) * t + 0.093104 * t ** 2\ - 6.2e-6 * t ** 3 # Conversion from second (time) to degrees (angle) theta /= 240. if model == 'apparent': theta += equinox(date, eop_correction, terms) # Add local longitude to the sideral time theta += longitude # Force to 0-360 degrees range theta %= 360. return theta
[ "def", "_sideral", "(", "date", ",", "longitude", "=", "0.", ",", "model", "=", "'mean'", ",", "eop_correction", "=", "True", ",", "terms", "=", "106", ")", ":", "t", "=", "date", ".", "change_scale", "(", "'UT1'", ")", ".", "julian_century", "# Comput...
Get the sideral time at a defined date Args: date (Date): longitude (float): Longitude of the observer (in degrees) East positive/West negative. model (str): 'mean' or 'apparent' for GMST and GAST respectively Return: float: Sideral time in degrees GMST: Greenwich Mean Sideral Time LST: Local Sideral Time (Mean) GAST: Greenwich Apparent Sideral Time
[ "Get", "the", "sideral", "time", "at", "a", "defined", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L177-L210
train
33,864
galactics/beyond
beyond/frames/iau1980.py
sideral
def sideral(date, longitude=0., model='mean', eop_correction=True, terms=106): # pragma: no cover """Sideral time as a rotation matrix """ theta = _sideral(date, longitude, model, eop_correction, terms) return rot3(np.deg2rad(-theta))
python
def sideral(date, longitude=0., model='mean', eop_correction=True, terms=106): # pragma: no cover """Sideral time as a rotation matrix """ theta = _sideral(date, longitude, model, eop_correction, terms) return rot3(np.deg2rad(-theta))
[ "def", "sideral", "(", "date", ",", "longitude", "=", "0.", ",", "model", "=", "'mean'", ",", "eop_correction", "=", "True", ",", "terms", "=", "106", ")", ":", "# pragma: no cover", "theta", "=", "_sideral", "(", "date", ",", "longitude", ",", "model", ...
Sideral time as a rotation matrix
[ "Sideral", "time", "as", "a", "rotation", "matrix" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/iau1980.py#L213-L217
train
33,865
galactics/beyond
beyond/orbits/man.py
Maneuver.dv
def dv(self, orb): """Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3 """ orb = orb.copy(form="cartesian") if self.frame == "QSW": mat = to_qsw(orb).T elif self.frame == "TNW": mat = to_tnw(orb).T else: mat = np.identity(3) # velocity increment in the same reference frame as the orbit return mat @ self._dv
python
def dv(self, orb): """Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3 """ orb = orb.copy(form="cartesian") if self.frame == "QSW": mat = to_qsw(orb).T elif self.frame == "TNW": mat = to_tnw(orb).T else: mat = np.identity(3) # velocity increment in the same reference frame as the orbit return mat @ self._dv
[ "def", "dv", "(", "self", ",", "orb", ")", ":", "orb", "=", "orb", ".", "copy", "(", "form", "=", "\"cartesian\"", ")", "if", "self", ".", "frame", "==", "\"QSW\"", ":", "mat", "=", "to_qsw", "(", "orb", ")", ".", "T", "elif", "self", ".", "fra...
Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3
[ "Computation", "of", "the", "velocity", "increment", "in", "the", "reference", "frame", "of", "the", "orbit" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/man.py#L47-L66
train
33,866
galactics/beyond
beyond/orbits/orbit.py
Orbit.copy
def copy(self, *, frame=None, form=None): """Provide a new instance of the same point in space-time Keyword Args: frame (str or Frame): Frame to convert the new instance into form (str or Form): Form to convert the new instance into Return: Orbit: Override :py:meth:`numpy.ndarray.copy()` to include additional fields """ new_compl = {} for k, v in self.complements.items(): new_compl[k] = v.copy() if hasattr(v, 'copy') else v new_obj = self.__class__( self.date, self.base.copy(), self.form, self.frame, self.propagator.copy() if self.propagator is not None else None, **new_compl ) if frame and frame != self.frame: new_obj.frame = frame if form and form != self.form: new_obj.form = form return new_obj
python
def copy(self, *, frame=None, form=None): """Provide a new instance of the same point in space-time Keyword Args: frame (str or Frame): Frame to convert the new instance into form (str or Form): Form to convert the new instance into Return: Orbit: Override :py:meth:`numpy.ndarray.copy()` to include additional fields """ new_compl = {} for k, v in self.complements.items(): new_compl[k] = v.copy() if hasattr(v, 'copy') else v new_obj = self.__class__( self.date, self.base.copy(), self.form, self.frame, self.propagator.copy() if self.propagator is not None else None, **new_compl ) if frame and frame != self.frame: new_obj.frame = frame if form and form != self.form: new_obj.form = form return new_obj
[ "def", "copy", "(", "self", ",", "*", ",", "frame", "=", "None", ",", "form", "=", "None", ")", ":", "new_compl", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "complements", ".", "items", "(", ")", ":", "new_compl", "[", "k", "]", ...
Provide a new instance of the same point in space-time Keyword Args: frame (str or Frame): Frame to convert the new instance into form (str or Form): Form to convert the new instance into Return: Orbit: Override :py:meth:`numpy.ndarray.copy()` to include additional fields
[ "Provide", "a", "new", "instance", "of", "the", "same", "point", "in", "space", "-", "time" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L94-L120
train
33,867
galactics/beyond
beyond/orbits/orbit.py
Orbit.propagate
def propagate(self, date): """Propagate the orbit to a new date Args: date (Date) Return: Orbit """ if self.propagator.orbit is not self: self.propagator.orbit = self return self.propagator.propagate(date)
python
def propagate(self, date): """Propagate the orbit to a new date Args: date (Date) Return: Orbit """ if self.propagator.orbit is not self: self.propagator.orbit = self return self.propagator.propagate(date)
[ "def", "propagate", "(", "self", ",", "date", ")", ":", "if", "self", ".", "propagator", ".", "orbit", "is", "not", "self", ":", "self", ".", "propagator", ".", "orbit", "=", "self", "return", "self", ".", "propagator", ".", "propagate", "(", "date", ...
Propagate the orbit to a new date Args: date (Date) Return: Orbit
[ "Propagate", "the", "orbit", "to", "a", "new", "date" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L308-L320
train
33,868
galactics/beyond
beyond/orbits/orbit.py
Orbit.ephemeris
def ephemeris(self, **kwargs): """Generator giving the propagation of the orbit at different dates Args: start (Date) stop (Date or timedelta) step (timedelta) Yield: Orbit """ for orb in self.iter(inclusive=True, **kwargs): yield orb
python
def ephemeris(self, **kwargs): """Generator giving the propagation of the orbit at different dates Args: start (Date) stop (Date or timedelta) step (timedelta) Yield: Orbit """ for orb in self.iter(inclusive=True, **kwargs): yield orb
[ "def", "ephemeris", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "orb", "in", "self", ".", "iter", "(", "inclusive", "=", "True", ",", "*", "*", "kwargs", ")", ":", "yield", "orb" ]
Generator giving the propagation of the orbit at different dates Args: start (Date) stop (Date or timedelta) step (timedelta) Yield: Orbit
[ "Generator", "giving", "the", "propagation", "of", "the", "orbit", "at", "different", "dates" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L330-L342
train
33,869
galactics/beyond
beyond/orbits/orbit.py
OrbitInfos.period
def period(self): """Period of the orbit as a timedelta """ return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu))
python
def period(self): """Period of the orbit as a timedelta """ return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu))
[ "def", "period", "(", "self", ")", ":", "return", "timedelta", "(", "seconds", "=", "2", "*", "np", ".", "pi", "*", "np", ".", "sqrt", "(", "self", ".", "kep", ".", "a", "**", "3", "/", "self", ".", "mu", ")", ")" ]
Period of the orbit as a timedelta
[ "Period", "of", "the", "orbit", "as", "a", "timedelta" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L402-L405
train
33,870
galactics/beyond
beyond/orbits/orbit.py
OrbitInfos.va
def va(self): """Velocity at apocenter """ return np.sqrt(self.mu * (2 / (self.ra) - 1 / self.kep.a))
python
def va(self): """Velocity at apocenter """ return np.sqrt(self.mu * (2 / (self.ra) - 1 / self.kep.a))
[ "def", "va", "(", "self", ")", ":", "return", "np", ".", "sqrt", "(", "self", ".", "mu", "*", "(", "2", "/", "(", "self", ".", "ra", ")", "-", "1", "/", "self", ".", "kep", ".", "a", ")", ")" ]
Velocity at apocenter
[ "Velocity", "at", "apocenter" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L440-L443
train
33,871
galactics/beyond
beyond/orbits/orbit.py
OrbitInfos.vp
def vp(self): """Velocity at pericenter """ return np.sqrt(self.mu * (2 / (self.rp) - 1 / self.kep.a))
python
def vp(self): """Velocity at pericenter """ return np.sqrt(self.mu * (2 / (self.rp) - 1 / self.kep.a))
[ "def", "vp", "(", "self", ")", ":", "return", "np", ".", "sqrt", "(", "self", ".", "mu", "*", "(", "2", "/", "(", "self", ".", "rp", ")", "-", "1", "/", "self", ".", "kep", ".", "a", ")", ")" ]
Velocity at pericenter
[ "Velocity", "at", "pericenter" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L446-L449
train
33,872
galactics/beyond
beyond/utils/node.py
Node.path
def path(self, goal): """Get the shortest way between two nodes of the graph Args: goal (str): Name of the targeted node Return: list of Node """ if goal == self.name: return [self] if goal not in self.routes: raise ValueError("Unknown '{0}'".format(goal)) obj = self path = [obj] while True: obj = obj.routes[goal].direction path.append(obj) if obj.name == goal: break return path
python
def path(self, goal): """Get the shortest way between two nodes of the graph Args: goal (str): Name of the targeted node Return: list of Node """ if goal == self.name: return [self] if goal not in self.routes: raise ValueError("Unknown '{0}'".format(goal)) obj = self path = [obj] while True: obj = obj.routes[goal].direction path.append(obj) if obj.name == goal: break return path
[ "def", "path", "(", "self", ",", "goal", ")", ":", "if", "goal", "==", "self", ".", "name", ":", "return", "[", "self", "]", "if", "goal", "not", "in", "self", ".", "routes", ":", "raise", "ValueError", "(", "\"Unknown '{0}'\"", ".", "format", "(", ...
Get the shortest way between two nodes of the graph Args: goal (str): Name of the targeted node Return: list of Node
[ "Get", "the", "shortest", "way", "between", "two", "nodes", "of", "the", "graph" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/utils/node.py#L118-L139
train
33,873
galactics/beyond
beyond/utils/node.py
Node.steps
def steps(self, goal): """Get the list of individual relations leading to the targeted node Args: goal (str): Name of the targeted node Return: list of tuple of Node """ path = self.path(goal) for i in range(len(path) - 1): yield path[i], path[i + 1]
python
def steps(self, goal): """Get the list of individual relations leading to the targeted node Args: goal (str): Name of the targeted node Return: list of tuple of Node """ path = self.path(goal) for i in range(len(path) - 1): yield path[i], path[i + 1]
[ "def", "steps", "(", "self", ",", "goal", ")", ":", "path", "=", "self", ".", "path", "(", "goal", ")", "for", "i", "in", "range", "(", "len", "(", "path", ")", "-", "1", ")", ":", "yield", "path", "[", "i", "]", ",", "path", "[", "i", "+",...
Get the list of individual relations leading to the targeted node Args: goal (str): Name of the targeted node Return: list of tuple of Node
[ "Get", "the", "list", "of", "individual", "relations", "leading", "to", "the", "targeted", "node" ]
7a7590ff0fd4c0bac3e8e383ecca03caa98e5742
https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/utils/node.py#L141-L152
train
33,874
Patreon/patreon-python
examples/flask/my_site/models/tables/db_wrapper.py
build_if_needed
def build_if_needed(db): """Little helper method for making tables in SQL-Alchemy with SQLite""" if len(db.engine.table_names()) == 0: # import all classes here from my_site.models.tables.user import User db.create_all()
python
def build_if_needed(db): """Little helper method for making tables in SQL-Alchemy with SQLite""" if len(db.engine.table_names()) == 0: # import all classes here from my_site.models.tables.user import User db.create_all()
[ "def", "build_if_needed", "(", "db", ")", ":", "if", "len", "(", "db", ".", "engine", ".", "table_names", "(", ")", ")", "==", "0", ":", "# import all classes here", "from", "my_site", ".", "models", ".", "tables", ".", "user", "import", "User", "db", ...
Little helper method for making tables in SQL-Alchemy with SQLite
[ "Little", "helper", "method", "for", "making", "tables", "in", "SQL", "-", "Alchemy", "with", "SQLite" ]
80c83f018d6bd93b83c188baff727c5e77e01ce6
https://github.com/Patreon/patreon-python/blob/80c83f018d6bd93b83c188baff727c5e77e01ce6/examples/flask/my_site/models/tables/db_wrapper.py#L1-L7
train
33,875
andersinno/django-sanitized-dump
sanitized_dump/utils/compat.py
deunicode
def deunicode(item): """ Convert unicode objects to str """ if item is None: return None if isinstance(item, str): return item if isinstance(item, six.text_type): return item.encode('utf-8') if isinstance(item, dict): return { deunicode(key): deunicode(value) for (key, value) in item.items() } if isinstance(item, list): return [deunicode(x) for x in item] raise TypeError('Unhandled item type: {!r}'.format(item))
python
def deunicode(item): """ Convert unicode objects to str """ if item is None: return None if isinstance(item, str): return item if isinstance(item, six.text_type): return item.encode('utf-8') if isinstance(item, dict): return { deunicode(key): deunicode(value) for (key, value) in item.items() } if isinstance(item, list): return [deunicode(x) for x in item] raise TypeError('Unhandled item type: {!r}'.format(item))
[ "def", "deunicode", "(", "item", ")", ":", "if", "item", "is", "None", ":", "return", "None", "if", "isinstance", "(", "item", ",", "str", ")", ":", "return", "item", "if", "isinstance", "(", "item", ",", "six", ".", "text_type", ")", ":", "return", ...
Convert unicode objects to str
[ "Convert", "unicode", "objects", "to", "str" ]
185a693d153dd9fb56cdc58382e4744635afc2e7
https://github.com/andersinno/django-sanitized-dump/blob/185a693d153dd9fb56cdc58382e4744635afc2e7/sanitized_dump/utils/compat.py#L9-L24
train
33,876
srittau/python-asserts
asserts/__init__.py
assert_true
def assert_true(expr, msg_fmt="{msg}"): """Fail the test unless the expression is truthy. >>> assert_true("Hello World!") >>> assert_true("") Traceback (most recent call last): ... AssertionError: '' is not truthy The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if not expr: msg = "{!r} is not truthy".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
python
def assert_true(expr, msg_fmt="{msg}"): """Fail the test unless the expression is truthy. >>> assert_true("Hello World!") >>> assert_true("") Traceback (most recent call last): ... AssertionError: '' is not truthy The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if not expr: msg = "{!r} is not truthy".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
[ "def", "assert_true", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "expr", ":", "msg", "=", "\"{!r} is not truthy\"", ".", "format", "(", "expr", ")", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", "msg", ",", "expr", ...
Fail the test unless the expression is truthy. >>> assert_true("Hello World!") >>> assert_true("") Traceback (most recent call last): ... AssertionError: '' is not truthy The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
[ "Fail", "the", "test", "unless", "the", "expression", "is", "truthy", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L42-L58
train
33,877
srittau/python-asserts
asserts/__init__.py
assert_false
def assert_false(expr, msg_fmt="{msg}"): """Fail the test unless the expression is falsy. >>> assert_false("") >>> assert_false("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not falsy The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr: msg = "{!r} is not falsy".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
python
def assert_false(expr, msg_fmt="{msg}"): """Fail the test unless the expression is falsy. >>> assert_false("") >>> assert_false("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not falsy The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr: msg = "{!r} is not falsy".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
[ "def", "assert_false", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", ":", "msg", "=", "\"{!r} is not falsy\"", ".", "format", "(", "expr", ")", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", "msg", ",", "expr", "=", ...
Fail the test unless the expression is falsy. >>> assert_false("") >>> assert_false("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not falsy The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
[ "Fail", "the", "test", "unless", "the", "expression", "is", "falsy", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L61-L77
train
33,878
srittau/python-asserts
asserts/__init__.py
assert_boolean_true
def assert_boolean_true(expr, msg_fmt="{msg}"): """Fail the test unless the expression is the constant True. >>> assert_boolean_true(True) >>> assert_boolean_true("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not True The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is not True: msg = "{!r} is not True".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
python
def assert_boolean_true(expr, msg_fmt="{msg}"): """Fail the test unless the expression is the constant True. >>> assert_boolean_true(True) >>> assert_boolean_true("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not True The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is not True: msg = "{!r} is not True".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
[ "def", "assert_boolean_true", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", "is", "not", "True", ":", "msg", "=", "\"{!r} is not True\"", ".", "format", "(", "expr", ")", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", ...
Fail the test unless the expression is the constant True. >>> assert_boolean_true(True) >>> assert_boolean_true("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not True The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
[ "Fail", "the", "test", "unless", "the", "expression", "is", "the", "constant", "True", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L80-L96
train
33,879
srittau/python-asserts
asserts/__init__.py
assert_boolean_false
def assert_boolean_false(expr, msg_fmt="{msg}"): """Fail the test unless the expression is the constant False. >>> assert_boolean_false(False) >>> assert_boolean_false(0) Traceback (most recent call last): ... AssertionError: 0 is not False The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is not False: msg = "{!r} is not False".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
python
def assert_boolean_false(expr, msg_fmt="{msg}"): """Fail the test unless the expression is the constant False. >>> assert_boolean_false(False) >>> assert_boolean_false(0) Traceback (most recent call last): ... AssertionError: 0 is not False The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is not False: msg = "{!r} is not False".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
[ "def", "assert_boolean_false", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", "is", "not", "False", ":", "msg", "=", "\"{!r} is not False\"", ".", "format", "(", "expr", ")", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=",...
Fail the test unless the expression is the constant False. >>> assert_boolean_false(False) >>> assert_boolean_false(0) Traceback (most recent call last): ... AssertionError: 0 is not False The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
[ "Fail", "the", "test", "unless", "the", "expression", "is", "the", "constant", "False", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L99-L115
train
33,880
srittau/python-asserts
asserts/__init__.py
assert_is_none
def assert_is_none(expr, msg_fmt="{msg}"): """Fail if the expression is not None. >>> assert_is_none(None) >>> assert_is_none(False) Traceback (most recent call last): ... AssertionError: False is not None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is not None: msg = "{!r} is not None".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
python
def assert_is_none(expr, msg_fmt="{msg}"): """Fail if the expression is not None. >>> assert_is_none(None) >>> assert_is_none(False) Traceback (most recent call last): ... AssertionError: False is not None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is not None: msg = "{!r} is not None".format(expr) fail(msg_fmt.format(msg=msg, expr=expr))
[ "def", "assert_is_none", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", "is", "not", "None", ":", "msg", "=", "\"{!r} is not None\"", ".", "format", "(", "expr", ")", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", "msg"...
Fail if the expression is not None. >>> assert_is_none(None) >>> assert_is_none(False) Traceback (most recent call last): ... AssertionError: False is not None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
[ "Fail", "if", "the", "expression", "is", "not", "None", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L118-L134
train
33,881
srittau/python-asserts
asserts/__init__.py
assert_is_not_none
def assert_is_not_none(expr, msg_fmt="{msg}"): """Fail if the expression is None. >>> assert_is_not_none(0) >>> assert_is_not_none(None) Traceback (most recent call last): ... AssertionError: expression is None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is None: msg = "expression is None" fail(msg_fmt.format(msg=msg, expr=expr))
python
def assert_is_not_none(expr, msg_fmt="{msg}"): """Fail if the expression is None. >>> assert_is_not_none(0) >>> assert_is_not_none(None) Traceback (most recent call last): ... AssertionError: expression is None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression """ if expr is None: msg = "expression is None" fail(msg_fmt.format(msg=msg, expr=expr))
[ "def", "assert_is_not_none", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", "is", "None", ":", "msg", "=", "\"expression is None\"", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", "msg", ",", "expr", "=", "expr", ")", "...
Fail if the expression is None. >>> assert_is_not_none(0) >>> assert_is_not_none(None) Traceback (most recent call last): ... AssertionError: expression is None The following msg_fmt arguments are supported: * msg - the default error message * expr - tested expression
[ "Fail", "if", "the", "expression", "is", "None", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L137-L152
train
33,882
srittau/python-asserts
asserts/__init__.py
assert_equal
def assert_equal(first, second, msg_fmt="{msg}"): """Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if isinstance(first, dict) and isinstance(second, dict): assert_dict_equal(first, second, msg_fmt) elif not first == second: msg = "{!r} != {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_equal(first, second, msg_fmt="{msg}"): """Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if isinstance(first, dict) and isinstance(second, dict): assert_dict_equal(first, second, msg_fmt) elif not first == second: msg = "{!r} != {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_equal", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "isinstance", "(", "first", ",", "dict", ")", "and", "isinstance", "(", "second", ",", "dict", ")", ":", "assert_dict_equal", "(", "first", ",", "second...
Fail unless first equals second, as determined by the '==' operator. >>> assert_equal(5, 5.0) >>> assert_equal("Hello World!", "Goodbye!") Traceback (most recent call last): ... AssertionError: 'Hello World!' != 'Goodbye!' The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "unless", "first", "equals", "second", "as", "determined", "by", "the", "==", "operator", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L155-L174
train
33,883
srittau/python-asserts
asserts/__init__.py
assert_not_equal
def assert_not_equal(first, second, msg_fmt="{msg}"): """Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if first == second: msg = "{!r} == {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_not_equal(first, second, msg_fmt="{msg}"): """Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if first == second: msg = "{!r} == {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_not_equal", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "first", "==", "second", ":", "msg", "=", "\"{!r} == {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_fmt", ".", "format"...
Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "equals", "second", "as", "determined", "by", "the", "==", "operator", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L177-L194
train
33,884
srittau/python-asserts
asserts/__init__.py
assert_almost_equal
def assert_almost_equal( first, second, msg_fmt="{msg}", places=None, delta=None ): """Fail if first and second are not equal after rounding. By default, the difference between first and second is rounded to 7 decimal places. This can be configured with the places argument. Alternatively, delta can be used to specify the maximum allowed difference between first and second. If first and second can not be rounded or both places and delta are supplied, a TypeError is raised. >>> assert_almost_equal(5, 5.00000001) >>> assert_almost_equal(5, 5.001) Traceback (most recent call last): ... AssertionError: 5 != 5.001 within 7 places >>> assert_almost_equal(5, 5.001, places=2) >>> assert_almost_equal(5, 5.001, delta=0.1) The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument * places - number of places to compare or None * delta - delta or None """ if delta is not None and places is not None: raise TypeError("'places' and 'delta' are mutually exclusive") if delta is not None: if delta <= 0: raise ValueError("delta must be larger than 0") diff = abs(second - first) success = diff < delta detail_msg = "with delta={}".format(delta) else: if places is None: places = 7 success = not round(second - first, places) detail_msg = "within {} places".format(places) if not success: msg = "{!r} != {!r} {}".format(first, second, detail_msg) fail( msg_fmt.format( msg=msg, first=first, second=second, places=places, delta=delta ) )
python
def assert_almost_equal( first, second, msg_fmt="{msg}", places=None, delta=None ): """Fail if first and second are not equal after rounding. By default, the difference between first and second is rounded to 7 decimal places. This can be configured with the places argument. Alternatively, delta can be used to specify the maximum allowed difference between first and second. If first and second can not be rounded or both places and delta are supplied, a TypeError is raised. >>> assert_almost_equal(5, 5.00000001) >>> assert_almost_equal(5, 5.001) Traceback (most recent call last): ... AssertionError: 5 != 5.001 within 7 places >>> assert_almost_equal(5, 5.001, places=2) >>> assert_almost_equal(5, 5.001, delta=0.1) The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument * places - number of places to compare or None * delta - delta or None """ if delta is not None and places is not None: raise TypeError("'places' and 'delta' are mutually exclusive") if delta is not None: if delta <= 0: raise ValueError("delta must be larger than 0") diff = abs(second - first) success = diff < delta detail_msg = "with delta={}".format(delta) else: if places is None: places = 7 success = not round(second - first, places) detail_msg = "within {} places".format(places) if not success: msg = "{!r} != {!r} {}".format(first, second, detail_msg) fail( msg_fmt.format( msg=msg, first=first, second=second, places=places, delta=delta ) )
[ "def", "assert_almost_equal", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ",", "places", "=", "None", ",", "delta", "=", "None", ")", ":", "if", "delta", "is", "not", "None", "and", "places", "is", "not", "None", ":", "raise", "TypeE...
Fail if first and second are not equal after rounding. By default, the difference between first and second is rounded to 7 decimal places. This can be configured with the places argument. Alternatively, delta can be used to specify the maximum allowed difference between first and second. If first and second can not be rounded or both places and delta are supplied, a TypeError is raised. >>> assert_almost_equal(5, 5.00000001) >>> assert_almost_equal(5, 5.001) Traceback (most recent call last): ... AssertionError: 5 != 5.001 within 7 places >>> assert_almost_equal(5, 5.001, places=2) >>> assert_almost_equal(5, 5.001, delta=0.1) The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument * places - number of places to compare or None * delta - delta or None
[ "Fail", "if", "first", "and", "second", "are", "not", "equal", "after", "rounding", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L197-L245
train
33,885
srittau/python-asserts
asserts/__init__.py
assert_dict_equal
def assert_dict_equal( first, second, key_msg_fmt="{msg}", value_msg_fmt="{msg}" ): """Fail unless first dictionary equals second. The dictionaries are considered equal, if they both contain the same keys, and their respective values are also equal. >>> assert_dict_equal({"foo": 5}, {"foo": 5}) >>> assert_dict_equal({"foo": 5}, {}) Traceback (most recent call last): ... AssertionError: key 'foo' missing from right dict The following key_msg_fmt arguments are supported, if the keys do not match: * msg - the default error message * first - the first dict * second - the second dict * missing_keys - list of keys missing from right * extra_keys - list of keys missing from left The following value_msg_fmt arguments are supported, if a value does not match: * msg - the default error message * first - the first dict * second - the second dict * key - the key where the value does not match * first_value - the value in the first dict * second_value - the value in the second dict """ first_keys = set(first.keys()) second_keys = set(second.keys()) missing_keys = list(first_keys - second_keys) extra_keys = list(second_keys - first_keys) if missing_keys or extra_keys: if missing_keys: if len(missing_keys) == 1: msg = "key {!r} missing from right dict".format( missing_keys[0] ) else: keys = ", ".join(sorted(repr(k) for k in missing_keys)) msg = "keys {} missing from right dict".format(keys) else: if len(extra_keys) == 1: msg = "extra key {!r} in right dict".format(extra_keys[0]) else: keys = ", ".join(sorted(repr(k) for k in extra_keys)) msg = "extra keys {} in right dict".format(keys) if key_msg_fmt: msg = key_msg_fmt.format( msg=msg, first=first, second=second, missing_keys=missing_keys, extra_keys=extra_keys, ) raise AssertionError(msg) for key in first: first_value = first[key] second_value = second[key] msg = "key '{}' differs: {!r} != {!r}".format( key, first_value, second_value ) if value_msg_fmt: msg = value_msg_fmt.format( msg=msg, first=first, second=second, key=key, first_value=first_value, second_value=second_value, ) msg = msg.replace("{", "{{").replace("}", "}}") assert_equal(first_value, second_value, msg_fmt=msg)
python
def assert_dict_equal( first, second, key_msg_fmt="{msg}", value_msg_fmt="{msg}" ): """Fail unless first dictionary equals second. The dictionaries are considered equal, if they both contain the same keys, and their respective values are also equal. >>> assert_dict_equal({"foo": 5}, {"foo": 5}) >>> assert_dict_equal({"foo": 5}, {}) Traceback (most recent call last): ... AssertionError: key 'foo' missing from right dict The following key_msg_fmt arguments are supported, if the keys do not match: * msg - the default error message * first - the first dict * second - the second dict * missing_keys - list of keys missing from right * extra_keys - list of keys missing from left The following value_msg_fmt arguments are supported, if a value does not match: * msg - the default error message * first - the first dict * second - the second dict * key - the key where the value does not match * first_value - the value in the first dict * second_value - the value in the second dict """ first_keys = set(first.keys()) second_keys = set(second.keys()) missing_keys = list(first_keys - second_keys) extra_keys = list(second_keys - first_keys) if missing_keys or extra_keys: if missing_keys: if len(missing_keys) == 1: msg = "key {!r} missing from right dict".format( missing_keys[0] ) else: keys = ", ".join(sorted(repr(k) for k in missing_keys)) msg = "keys {} missing from right dict".format(keys) else: if len(extra_keys) == 1: msg = "extra key {!r} in right dict".format(extra_keys[0]) else: keys = ", ".join(sorted(repr(k) for k in extra_keys)) msg = "extra keys {} in right dict".format(keys) if key_msg_fmt: msg = key_msg_fmt.format( msg=msg, first=first, second=second, missing_keys=missing_keys, extra_keys=extra_keys, ) raise AssertionError(msg) for key in first: first_value = first[key] second_value = second[key] msg = "key '{}' differs: {!r} != {!r}".format( key, first_value, second_value ) if value_msg_fmt: msg = value_msg_fmt.format( msg=msg, first=first, second=second, key=key, first_value=first_value, second_value=second_value, ) msg = msg.replace("{", "{{").replace("}", "}}") assert_equal(first_value, second_value, msg_fmt=msg)
[ "def", "assert_dict_equal", "(", "first", ",", "second", ",", "key_msg_fmt", "=", "\"{msg}\"", ",", "value_msg_fmt", "=", "\"{msg}\"", ")", ":", "first_keys", "=", "set", "(", "first", ".", "keys", "(", ")", ")", "second_keys", "=", "set", "(", "second", ...
Fail unless first dictionary equals second. The dictionaries are considered equal, if they both contain the same keys, and their respective values are also equal. >>> assert_dict_equal({"foo": 5}, {"foo": 5}) >>> assert_dict_equal({"foo": 5}, {}) Traceback (most recent call last): ... AssertionError: key 'foo' missing from right dict The following key_msg_fmt arguments are supported, if the keys do not match: * msg - the default error message * first - the first dict * second - the second dict * missing_keys - list of keys missing from right * extra_keys - list of keys missing from left The following value_msg_fmt arguments are supported, if a value does not match: * msg - the default error message * first - the first dict * second - the second dict * key - the key where the value does not match * first_value - the value in the first dict * second_value - the value in the second dict
[ "Fail", "unless", "first", "dictionary", "equals", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L305-L380
train
33,886
srittau/python-asserts
asserts/__init__.py
assert_less
def assert_less(first, second, msg_fmt="{msg}"): """Fail if first is not less than second. >>> assert_less('bar', 'foo') >>> assert_less(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not less than 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first < second: msg = "{!r} is not less than {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_less(first, second, msg_fmt="{msg}"): """Fail if first is not less than second. >>> assert_less('bar', 'foo') >>> assert_less(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not less than 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first < second: msg = "{!r} is not less than {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_less", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "first", "<", "second", ":", "msg", "=", "\"{!r} is not less than {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_fmt", ...
Fail if first is not less than second. >>> assert_less('bar', 'foo') >>> assert_less(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not less than 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "is", "not", "less", "than", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L447-L464
train
33,887
srittau/python-asserts
asserts/__init__.py
assert_less_equal
def assert_less_equal(first, second, msg_fmt="{msg}"): """Fail if first is not less than or equal to second. >>> assert_less_equal('bar', 'foo') >>> assert_less_equal(5, 5) >>> assert_less_equal(6, 5) Traceback (most recent call last): ... AssertionError: 6 is not less than or equal to 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first <= second: msg = "{!r} is not less than or equal to {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_less_equal(first, second, msg_fmt="{msg}"): """Fail if first is not less than or equal to second. >>> assert_less_equal('bar', 'foo') >>> assert_less_equal(5, 5) >>> assert_less_equal(6, 5) Traceback (most recent call last): ... AssertionError: 6 is not less than or equal to 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first <= second: msg = "{!r} is not less than or equal to {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_less_equal", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "first", "<=", "second", ":", "msg", "=", "\"{!r} is not less than or equal to {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", ...
Fail if first is not less than or equal to second. >>> assert_less_equal('bar', 'foo') >>> assert_less_equal(5, 5) >>> assert_less_equal(6, 5) Traceback (most recent call last): ... AssertionError: 6 is not less than or equal to 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "is", "not", "less", "than", "or", "equal", "to", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L467-L485
train
33,888
srittau/python-asserts
asserts/__init__.py
assert_greater
def assert_greater(first, second, msg_fmt="{msg}"): """Fail if first is not greater than second. >>> assert_greater('foo', 'bar') >>> assert_greater(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not greater than 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first > second: msg = "{!r} is not greater than {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_greater(first, second, msg_fmt="{msg}"): """Fail if first is not greater than second. >>> assert_greater('foo', 'bar') >>> assert_greater(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not greater than 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first > second: msg = "{!r} is not greater than {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_greater", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "first", ">", "second", ":", "msg", "=", "\"{!r} is not greater than {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_...
Fail if first is not greater than second. >>> assert_greater('foo', 'bar') >>> assert_greater(5, 5) Traceback (most recent call last): ... AssertionError: 5 is not greater than 5 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "is", "not", "greater", "than", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L488-L505
train
33,889
srittau/python-asserts
asserts/__init__.py
assert_greater_equal
def assert_greater_equal(first, second, msg_fmt="{msg}"): """Fail if first is not greater than or equal to second. >>> assert_greater_equal('foo', 'bar') >>> assert_greater_equal(5, 5) >>> assert_greater_equal(5, 6) Traceback (most recent call last): ... AssertionError: 5 is not greater than or equal to 6 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first >= second: msg = "{!r} is not greater than or equal to {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_greater_equal(first, second, msg_fmt="{msg}"): """Fail if first is not greater than or equal to second. >>> assert_greater_equal('foo', 'bar') >>> assert_greater_equal(5, 5) >>> assert_greater_equal(5, 6) Traceback (most recent call last): ... AssertionError: 5 is not greater than or equal to 6 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if not first >= second: msg = "{!r} is not greater than or equal to {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_greater_equal", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "first", ">=", "second", ":", "msg", "=", "\"{!r} is not greater than or equal to {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fa...
Fail if first is not greater than or equal to second. >>> assert_greater_equal('foo', 'bar') >>> assert_greater_equal(5, 5) >>> assert_greater_equal(5, 6) Traceback (most recent call last): ... AssertionError: 5 is not greater than or equal to 6 The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "is", "not", "greater", "than", "or", "equal", "to", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L508-L526
train
33,890
srittau/python-asserts
asserts/__init__.py
assert_regex
def assert_regex(text, regex, msg_fmt="{msg}"): """Fail if text does not match the regular expression. regex can be either a regular expression string or a compiled regular expression object. >>> assert_regex("Hello World!", r"llo.*rld!$") >>> assert_regex("Hello World!", r"\\d") Traceback (most recent call last): ... AssertionError: 'Hello World!' does not match '\\\\d' The following msg_fmt arguments are supported: * msg - the default error message * text - text that is matched * pattern - regular expression pattern as string """ compiled = re.compile(regex) if not compiled.search(text): msg = "{!r} does not match {!r}".format(text, compiled.pattern) fail(msg_fmt.format(msg=msg, text=text, pattern=compiled.pattern))
python
def assert_regex(text, regex, msg_fmt="{msg}"): """Fail if text does not match the regular expression. regex can be either a regular expression string or a compiled regular expression object. >>> assert_regex("Hello World!", r"llo.*rld!$") >>> assert_regex("Hello World!", r"\\d") Traceback (most recent call last): ... AssertionError: 'Hello World!' does not match '\\\\d' The following msg_fmt arguments are supported: * msg - the default error message * text - text that is matched * pattern - regular expression pattern as string """ compiled = re.compile(regex) if not compiled.search(text): msg = "{!r} does not match {!r}".format(text, compiled.pattern) fail(msg_fmt.format(msg=msg, text=text, pattern=compiled.pattern))
[ "def", "assert_regex", "(", "text", ",", "regex", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "compiled", "=", "re", ".", "compile", "(", "regex", ")", "if", "not", "compiled", ".", "search", "(", "text", ")", ":", "msg", "=", "\"{!r} does not match {!r}...
Fail if text does not match the regular expression. regex can be either a regular expression string or a compiled regular expression object. >>> assert_regex("Hello World!", r"llo.*rld!$") >>> assert_regex("Hello World!", r"\\d") Traceback (most recent call last): ... AssertionError: 'Hello World!' does not match '\\\\d' The following msg_fmt arguments are supported: * msg - the default error message * text - text that is matched * pattern - regular expression pattern as string
[ "Fail", "if", "text", "does", "not", "match", "the", "regular", "expression", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L529-L550
train
33,891
srittau/python-asserts
asserts/__init__.py
assert_is
def assert_is(first, second, msg_fmt="{msg}"): """Fail if first and second do not refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is(list1, list1) >>> assert_is(list1, list2) Traceback (most recent call last): ... AssertionError: [5, 'foo'] is not [5, 'foo'] The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if first is not second: msg = "{!r} is not {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_is(first, second, msg_fmt="{msg}"): """Fail if first and second do not refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is(list1, list1) >>> assert_is(list1, list2) Traceback (most recent call last): ... AssertionError: [5, 'foo'] is not [5, 'foo'] The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if first is not second: msg = "{!r} is not {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_is", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "first", "is", "not", "second", ":", "msg", "=", "\"{!r} is not {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_fmt", ".", "f...
Fail if first and second do not refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is(list1, list1) >>> assert_is(list1, list2) Traceback (most recent call last): ... AssertionError: [5, 'foo'] is not [5, 'foo'] The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "and", "second", "do", "not", "refer", "to", "the", "same", "object", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L553-L572
train
33,892
srittau/python-asserts
asserts/__init__.py
assert_is_not
def assert_is_not(first, second, msg_fmt="{msg}"): """Fail if first and second refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is_not(list1, list2) >>> assert_is_not(list1, list1) Traceback (most recent call last): ... AssertionError: both arguments refer to [5, 'foo'] The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if first is second: msg = "both arguments refer to {!r}".format(first) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_is_not(first, second, msg_fmt="{msg}"): """Fail if first and second refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is_not(list1, list2) >>> assert_is_not(list1, list1) Traceback (most recent call last): ... AssertionError: both arguments refer to [5, 'foo'] The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument """ if first is second: msg = "both arguments refer to {!r}".format(first) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_is_not", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "first", "is", "second", ":", "msg", "=", "\"both arguments refer to {!r}\"", ".", "format", "(", "first", ")", "fail", "(", "msg_fmt", ".", "format", "(...
Fail if first and second refer to the same object. >>> list1 = [5, "foo"] >>> list2 = [5, "foo"] >>> assert_is_not(list1, list2) >>> assert_is_not(list1, list1) Traceback (most recent call last): ... AssertionError: both arguments refer to [5, 'foo'] The following msg_fmt arguments are supported: * msg - the default error message * first - the first argument * second - the second argument
[ "Fail", "if", "first", "and", "second", "refer", "to", "the", "same", "object", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L575-L594
train
33,893
srittau/python-asserts
asserts/__init__.py
assert_in
def assert_in(first, second, msg_fmt="{msg}"): """Fail if first is not in collection second. >>> assert_in("foo", [4, "foo", {}]) >>> assert_in("bar", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'bar' not in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in """ if first not in second: msg = "{!r} not in {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_in(first, second, msg_fmt="{msg}"): """Fail if first is not in collection second. >>> assert_in("foo", [4, "foo", {}]) >>> assert_in("bar", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'bar' not in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in """ if first not in second: msg = "{!r} not in {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_in", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "first", "not", "in", "second", ":", "msg", "=", "\"{!r} not in {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_fmt", ".", "f...
Fail if first is not in collection second. >>> assert_in("foo", [4, "foo", {}]) >>> assert_in("bar", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'bar' not in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in
[ "Fail", "if", "first", "is", "not", "in", "collection", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L597-L614
train
33,894
srittau/python-asserts
asserts/__init__.py
assert_not_in
def assert_not_in(first, second, msg_fmt="{msg}"): """Fail if first is in a collection second. >>> assert_not_in("bar", [4, "foo", {}]) >>> assert_not_in("foo", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'foo' is in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in """ if first in second: msg = "{!r} is in {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
python
def assert_not_in(first, second, msg_fmt="{msg}"): """Fail if first is in a collection second. >>> assert_not_in("bar", [4, "foo", {}]) >>> assert_not_in("foo", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'foo' is in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in """ if first in second: msg = "{!r} is in {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
[ "def", "assert_not_in", "(", "first", ",", "second", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "first", "in", "second", ":", "msg", "=", "\"{!r} is in {!r}\"", ".", "format", "(", "first", ",", "second", ")", "fail", "(", "msg_fmt", ".", "format"...
Fail if first is in a collection second. >>> assert_not_in("bar", [4, "foo", {}]) >>> assert_not_in("foo", [4, "foo", {}]) Traceback (most recent call last): ... AssertionError: 'foo' is in [4, 'foo', {}] The following msg_fmt arguments are supported: * msg - the default error message * first - the element looked for * second - the container looked in
[ "Fail", "if", "first", "is", "in", "a", "collection", "second", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L617-L633
train
33,895
srittau/python-asserts
asserts/__init__.py
assert_count_equal
def assert_count_equal(sequence1, sequence2, msg_fmt="{msg}"): """Compare the items of two sequences, ignoring order. >>> assert_count_equal([1, 2], {2, 1}) Items missing in either sequence will be listed: >>> assert_count_equal(["a", "b", "c"], ["a", "d"]) Traceback (most recent call last): ... AssertionError: missing from sequence 1: 'd'; missing from sequence 2: 'b', 'c' Items are counted in each sequence. This makes it useful to detect duplicates: >>> assert_count_equal({"a", "b"}, ["a", "a", "b"]) Traceback (most recent call last): ... AssertionError: missing from sequence 1: 'a' The following msg_fmt arguments are supported: * msg - the default error message * first - first sequence * second - second sequence """ def compare(): missing1 = list(sequence2) missing2 = [] for item in sequence1: try: missing1.remove(item) except ValueError: missing2.append(item) return missing1, missing2 def build_message(): msg = "" if missing_from_1: msg += "missing from sequence 1: " + ", ".join( repr(i) for i in missing_from_1 ) if missing_from_1 and missing_from_2: msg += "; " if missing_from_2: msg += "missing from sequence 2: " + ", ".join( repr(i) for i in missing_from_2 ) return msg missing_from_1, missing_from_2 = compare() if missing_from_1 or missing_from_2: fail( msg_fmt.format( msg=build_message(), first=sequence1, second=sequence2 ) )
python
def assert_count_equal(sequence1, sequence2, msg_fmt="{msg}"): """Compare the items of two sequences, ignoring order. >>> assert_count_equal([1, 2], {2, 1}) Items missing in either sequence will be listed: >>> assert_count_equal(["a", "b", "c"], ["a", "d"]) Traceback (most recent call last): ... AssertionError: missing from sequence 1: 'd'; missing from sequence 2: 'b', 'c' Items are counted in each sequence. This makes it useful to detect duplicates: >>> assert_count_equal({"a", "b"}, ["a", "a", "b"]) Traceback (most recent call last): ... AssertionError: missing from sequence 1: 'a' The following msg_fmt arguments are supported: * msg - the default error message * first - first sequence * second - second sequence """ def compare(): missing1 = list(sequence2) missing2 = [] for item in sequence1: try: missing1.remove(item) except ValueError: missing2.append(item) return missing1, missing2 def build_message(): msg = "" if missing_from_1: msg += "missing from sequence 1: " + ", ".join( repr(i) for i in missing_from_1 ) if missing_from_1 and missing_from_2: msg += "; " if missing_from_2: msg += "missing from sequence 2: " + ", ".join( repr(i) for i in missing_from_2 ) return msg missing_from_1, missing_from_2 = compare() if missing_from_1 or missing_from_2: fail( msg_fmt.format( msg=build_message(), first=sequence1, second=sequence2 ) )
[ "def", "assert_count_equal", "(", "sequence1", ",", "sequence2", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "def", "compare", "(", ")", ":", "missing1", "=", "list", "(", "sequence2", ")", "missing2", "=", "[", "]", "for", "item", "in", "sequence1", ":"...
Compare the items of two sequences, ignoring order. >>> assert_count_equal([1, 2], {2, 1}) Items missing in either sequence will be listed: >>> assert_count_equal(["a", "b", "c"], ["a", "d"]) Traceback (most recent call last): ... AssertionError: missing from sequence 1: 'd'; missing from sequence 2: 'b', 'c' Items are counted in each sequence. This makes it useful to detect duplicates: >>> assert_count_equal({"a", "b"}, ["a", "a", "b"]) Traceback (most recent call last): ... AssertionError: missing from sequence 1: 'a' The following msg_fmt arguments are supported: * msg - the default error message * first - first sequence * second - second sequence
[ "Compare", "the", "items", "of", "two", "sequences", "ignoring", "order", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L636-L692
train
33,896
srittau/python-asserts
asserts/__init__.py
assert_is_instance
def assert_is_instance(obj, cls, msg_fmt="{msg}"): """Fail if an object is not an instance of a class or tuple of classes. >>> assert_is_instance(5, int) >>> assert_is_instance('foo', (str, bytes)) >>> assert_is_instance(5, str) Traceback (most recent call last): ... AssertionError: 5 is an instance of <class 'int'>, expected <class 'str'> The following msg_fmt arguments are supported: * msg - the default error message * obj - object to test * types - tuple of types tested against """ if not isinstance(obj, cls): msg = "{!r} is an instance of {!r}, expected {!r}".format( obj, obj.__class__, cls ) types = cls if isinstance(cls, tuple) else (cls,) fail(msg_fmt.format(msg=msg, obj=obj, types=types))
python
def assert_is_instance(obj, cls, msg_fmt="{msg}"): """Fail if an object is not an instance of a class or tuple of classes. >>> assert_is_instance(5, int) >>> assert_is_instance('foo', (str, bytes)) >>> assert_is_instance(5, str) Traceback (most recent call last): ... AssertionError: 5 is an instance of <class 'int'>, expected <class 'str'> The following msg_fmt arguments are supported: * msg - the default error message * obj - object to test * types - tuple of types tested against """ if not isinstance(obj, cls): msg = "{!r} is an instance of {!r}, expected {!r}".format( obj, obj.__class__, cls ) types = cls if isinstance(cls, tuple) else (cls,) fail(msg_fmt.format(msg=msg, obj=obj, types=types))
[ "def", "assert_is_instance", "(", "obj", ",", "cls", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "cls", ")", ":", "msg", "=", "\"{!r} is an instance of {!r}, expected {!r}\"", ".", "format", "(", "obj", ",", "obj",...
Fail if an object is not an instance of a class or tuple of classes. >>> assert_is_instance(5, int) >>> assert_is_instance('foo', (str, bytes)) >>> assert_is_instance(5, str) Traceback (most recent call last): ... AssertionError: 5 is an instance of <class 'int'>, expected <class 'str'> The following msg_fmt arguments are supported: * msg - the default error message * obj - object to test * types - tuple of types tested against
[ "Fail", "if", "an", "object", "is", "not", "an", "instance", "of", "a", "class", "or", "tuple", "of", "classes", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L723-L743
train
33,897
srittau/python-asserts
asserts/__init__.py
assert_has_attr
def assert_has_attr(obj, attribute, msg_fmt="{msg}"): """Fail is an object does not have an attribute. >>> assert_has_attr([], "index") >>> assert_has_attr([], "i_do_not_have_this") Traceback (most recent call last): ... AssertionError: [] does not have attribute 'i_do_not_have_this' The following msg_fmt arguments are supported: * msg - the default error message * obj - object to test * attribute - name of the attribute to check """ if not hasattr(obj, attribute): msg = "{!r} does not have attribute '{}'".format(obj, attribute) fail(msg_fmt.format(msg=msg, obj=obj, attribute=attribute))
python
def assert_has_attr(obj, attribute, msg_fmt="{msg}"): """Fail is an object does not have an attribute. >>> assert_has_attr([], "index") >>> assert_has_attr([], "i_do_not_have_this") Traceback (most recent call last): ... AssertionError: [] does not have attribute 'i_do_not_have_this' The following msg_fmt arguments are supported: * msg - the default error message * obj - object to test * attribute - name of the attribute to check """ if not hasattr(obj, attribute): msg = "{!r} does not have attribute '{}'".format(obj, attribute) fail(msg_fmt.format(msg=msg, obj=obj, attribute=attribute))
[ "def", "assert_has_attr", "(", "obj", ",", "attribute", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "attribute", ")", ":", "msg", "=", "\"{!r} does not have attribute '{}'\"", ".", "format", "(", "obj", ",", "attribut...
Fail is an object does not have an attribute. >>> assert_has_attr([], "index") >>> assert_has_attr([], "i_do_not_have_this") Traceback (most recent call last): ... AssertionError: [] does not have attribute 'i_do_not_have_this' The following msg_fmt arguments are supported: * msg - the default error message * obj - object to test * attribute - name of the attribute to check
[ "Fail", "is", "an", "object", "does", "not", "have", "an", "attribute", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L767-L784
train
33,898
srittau/python-asserts
asserts/__init__.py
assert_datetime_about_now
def assert_datetime_about_now(actual, msg_fmt="{msg}"): """Fail if a datetime object is not within 5 seconds of the local time. >>> assert_datetime_about_now(datetime.now()) >>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0)) Traceback (most recent call last): ... AssertionError: datetime.datetime(1900, 1, 1, 12, 0) is not close to current date/time The following msg_fmt arguments are supported: * msg - the default error message * actual - datetime object to check * now - current datetime that was tested against """ now = datetime.now() if actual is None: msg = "None is not a valid date/time" fail(msg_fmt.format(msg=msg, actual=actual, now=now)) lower_bound = now - timedelta(seconds=_EPSILON_SECONDS) upper_bound = now + timedelta(seconds=_EPSILON_SECONDS) if not lower_bound <= actual <= upper_bound: msg = "{!r} is not close to current date/time".format(actual) fail(msg_fmt.format(msg=msg, actual=actual, now=now))
python
def assert_datetime_about_now(actual, msg_fmt="{msg}"): """Fail if a datetime object is not within 5 seconds of the local time. >>> assert_datetime_about_now(datetime.now()) >>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0)) Traceback (most recent call last): ... AssertionError: datetime.datetime(1900, 1, 1, 12, 0) is not close to current date/time The following msg_fmt arguments are supported: * msg - the default error message * actual - datetime object to check * now - current datetime that was tested against """ now = datetime.now() if actual is None: msg = "None is not a valid date/time" fail(msg_fmt.format(msg=msg, actual=actual, now=now)) lower_bound = now - timedelta(seconds=_EPSILON_SECONDS) upper_bound = now + timedelta(seconds=_EPSILON_SECONDS) if not lower_bound <= actual <= upper_bound: msg = "{!r} is not close to current date/time".format(actual) fail(msg_fmt.format(msg=msg, actual=actual, now=now))
[ "def", "assert_datetime_about_now", "(", "actual", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", "if", "actual", "is", "None", ":", "msg", "=", "\"None is not a valid date/time\"", "fail", "(", "msg_fmt", ".", "for...
Fail if a datetime object is not within 5 seconds of the local time. >>> assert_datetime_about_now(datetime.now()) >>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0)) Traceback (most recent call last): ... AssertionError: datetime.datetime(1900, 1, 1, 12, 0) is not close to current date/time The following msg_fmt arguments are supported: * msg - the default error message * actual - datetime object to check * now - current datetime that was tested against
[ "Fail", "if", "a", "datetime", "object", "is", "not", "within", "5", "seconds", "of", "the", "local", "time", "." ]
1d5c797031c68ee27552d1c94e7f918c3d3d0453
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L790-L813
train
33,899