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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.tai | def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TAI calendar date.
Supply the International Atomic Time (TAI) as a proleptic
Gregorian calendar date:
>>> t = ts.tai(2014, 1, 18, 1, 35, 37.5)
>>> t.tai
2456675.56640625
>>> t.tai_calendar()
(2014, 1, 18, 1, 35, 37.5)
"""
if jd is not None:
tai = jd
else:
tai = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
return self.tai_jd(tai) | python | def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TAI calendar date.
Supply the International Atomic Time (TAI) as a proleptic
Gregorian calendar date:
>>> t = ts.tai(2014, 1, 18, 1, 35, 37.5)
>>> t.tai
2456675.56640625
>>> t.tai_calendar()
(2014, 1, 18, 1, 35, 37.5)
"""
if jd is not None:
tai = jd
else:
tai = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
return self.tai_jd(tai) | [
"def",
"tai",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
",",
"jd",
"=",
"None",
")",
":",
"if",
"jd",
"is",
"not",
"None",... | Build a `Time` from a TAI calendar date.
Supply the International Atomic Time (TAI) as a proleptic
Gregorian calendar date:
>>> t = ts.tai(2014, 1, 18, 1, 35, 37.5)
>>> t.tai
2456675.56640625
>>> t.tai_calendar()
(2014, 1, 18, 1, 35, 37.5) | [
"Build",
"a",
"Time",
"from",
"a",
"TAI",
"calendar",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L129-L150 | train | 224,800 |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.tai_jd | def tai_jd(self, jd):
"""Build a `Time` from a TAI Julian date.
Supply the International Atomic Time (TAI) as a Julian date:
>>> t = ts.tai_jd(2456675.56640625)
>>> t.tai
2456675.56640625
>>> t.tai_calendar()
(2014, 1, 18, 1, 35, 37.5)
"""
tai = _to_array(jd)
t = Time(self, tai + tt_minus_tai)
t.tai = tai
return t | python | def tai_jd(self, jd):
"""Build a `Time` from a TAI Julian date.
Supply the International Atomic Time (TAI) as a Julian date:
>>> t = ts.tai_jd(2456675.56640625)
>>> t.tai
2456675.56640625
>>> t.tai_calendar()
(2014, 1, 18, 1, 35, 37.5)
"""
tai = _to_array(jd)
t = Time(self, tai + tt_minus_tai)
t.tai = tai
return t | [
"def",
"tai_jd",
"(",
"self",
",",
"jd",
")",
":",
"tai",
"=",
"_to_array",
"(",
"jd",
")",
"t",
"=",
"Time",
"(",
"self",
",",
"tai",
"+",
"tt_minus_tai",
")",
"t",
".",
"tai",
"=",
"tai",
"return",
"t"
] | Build a `Time` from a TAI Julian date.
Supply the International Atomic Time (TAI) as a Julian date:
>>> t = ts.tai_jd(2456675.56640625)
>>> t.tai
2456675.56640625
>>> t.tai_calendar()
(2014, 1, 18, 1, 35, 37.5) | [
"Build",
"a",
"Time",
"from",
"a",
"TAI",
"Julian",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L152-L167 | train | 224,801 |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.tt | def tt(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TT calendar date.
Supply the Terrestrial Time (TT) as a proleptic Gregorian
calendar date:
>>> t = ts.tt(2014, 1, 18, 1, 35, 37.5)
>>> t.tt
2456675.56640625
>>> t.tt_calendar()
(2014, 1, 18, 1, 35, 37.5)
"""
if jd is not None:
tt = jd
else:
tt = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
tt = _to_array(tt)
return Time(self, tt) | python | def tt(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TT calendar date.
Supply the Terrestrial Time (TT) as a proleptic Gregorian
calendar date:
>>> t = ts.tt(2014, 1, 18, 1, 35, 37.5)
>>> t.tt
2456675.56640625
>>> t.tt_calendar()
(2014, 1, 18, 1, 35, 37.5)
"""
if jd is not None:
tt = jd
else:
tt = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
tt = _to_array(tt)
return Time(self, tt) | [
"def",
"tt",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
",",
"jd",
"=",
"None",
")",
":",
"if",
"jd",
"is",
"not",
"None",
... | Build a `Time` from a TT calendar date.
Supply the Terrestrial Time (TT) as a proleptic Gregorian
calendar date:
>>> t = ts.tt(2014, 1, 18, 1, 35, 37.5)
>>> t.tt
2456675.56640625
>>> t.tt_calendar()
(2014, 1, 18, 1, 35, 37.5) | [
"Build",
"a",
"Time",
"from",
"a",
"TT",
"calendar",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L169-L191 | train | 224,802 |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.tdb | def tdb(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TDB calendar date.
Supply the Barycentric Dynamical Time (TDB) as a proleptic
Gregorian calendar date:
>>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5)
>>> t.tdb
2456675.56640625
"""
if jd is not None:
tdb = jd
else:
tdb = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
tdb = _to_array(tdb)
tt = tdb - tdb_minus_tt(tdb) / DAY_S
t = Time(self, tt)
t.tdb = tdb
return t | python | def tdb(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TDB calendar date.
Supply the Barycentric Dynamical Time (TDB) as a proleptic
Gregorian calendar date:
>>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5)
>>> t.tdb
2456675.56640625
"""
if jd is not None:
tdb = jd
else:
tdb = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
tdb = _to_array(tdb)
tt = tdb - tdb_minus_tt(tdb) / DAY_S
t = Time(self, tt)
t.tdb = tdb
return t | [
"def",
"tdb",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
",",
"jd",
"=",
"None",
")",
":",
"if",
"jd",
"is",
"not",
"None",... | Build a `Time` from a TDB calendar date.
Supply the Barycentric Dynamical Time (TDB) as a proleptic
Gregorian calendar date:
>>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5)
>>> t.tdb
2456675.56640625 | [
"Build",
"a",
"Time",
"from",
"a",
"TDB",
"calendar",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L208-L231 | train | 224,803 |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.tdb_jd | def tdb_jd(self, jd):
"""Build a `Time` from a TDB Julian date.
Supply the Barycentric Dynamical Time (TDB) as a Julian date:
>>> t = ts.tdb_jd(2456675.56640625)
>>> t.tdb
2456675.56640625
"""
tdb = _to_array(jd)
tt = tdb - tdb_minus_tt(tdb) / DAY_S
t = Time(self, tt)
t.tdb = tdb
return t | python | def tdb_jd(self, jd):
"""Build a `Time` from a TDB Julian date.
Supply the Barycentric Dynamical Time (TDB) as a Julian date:
>>> t = ts.tdb_jd(2456675.56640625)
>>> t.tdb
2456675.56640625
"""
tdb = _to_array(jd)
tt = tdb - tdb_minus_tt(tdb) / DAY_S
t = Time(self, tt)
t.tdb = tdb
return t | [
"def",
"tdb_jd",
"(",
"self",
",",
"jd",
")",
":",
"tdb",
"=",
"_to_array",
"(",
"jd",
")",
"tt",
"=",
"tdb",
"-",
"tdb_minus_tt",
"(",
"tdb",
")",
"/",
"DAY_S",
"t",
"=",
"Time",
"(",
"self",
",",
"tt",
")",
"t",
".",
"tdb",
"=",
"tdb",
"ret... | Build a `Time` from a TDB Julian date.
Supply the Barycentric Dynamical Time (TDB) as a Julian date:
>>> t = ts.tdb_jd(2456675.56640625)
>>> t.tdb
2456675.56640625 | [
"Build",
"a",
"Time",
"from",
"a",
"TDB",
"Julian",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L233-L247 | train | 224,804 |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.ut1 | def ut1(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a UT1 calendar date.
Supply the Universal Time (UT1) as a proleptic Gregorian
calendar date:
>>> t = ts.ut1(2014, 1, 18, 1, 35, 37.5)
>>> t.ut1
2456675.56640625
"""
if jd is not None:
ut1 = jd
else:
ut1 = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
return self.ut1_jd(ut1) | python | def ut1(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a UT1 calendar date.
Supply the Universal Time (UT1) as a proleptic Gregorian
calendar date:
>>> t = ts.ut1(2014, 1, 18, 1, 35, 37.5)
>>> t.ut1
2456675.56640625
"""
if jd is not None:
ut1 = jd
else:
ut1 = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
return self.ut1_jd(ut1) | [
"def",
"ut1",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
",",
"jd",
"=",
"None",
")",
":",
"if",
"jd",
"is",
"not",
"None",... | Build a `Time` from a UT1 calendar date.
Supply the Universal Time (UT1) as a proleptic Gregorian
calendar date:
>>> t = ts.ut1(2014, 1, 18, 1, 35, 37.5)
>>> t.ut1
2456675.56640625 | [
"Build",
"a",
"Time",
"from",
"a",
"UT1",
"calendar",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L249-L268 | train | 224,805 |
skyfielders/python-skyfield | skyfield/timelib.py | Timescale.ut1_jd | def ut1_jd(self, jd):
"""Build a `Time` from UT1 a Julian date.
Supply the Universal Time (UT1) as a Julian date:
>>> t = ts.ut1_jd(2456675.56640625)
>>> t.ut1
2456675.56640625
"""
ut1 = _to_array(jd)
# Estimate TT = UT1, to get a rough Delta T estimate.
tt_approx = ut1
delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx)
# Use the rough Delta T to make a much better estimate of TT,
# then generate an even better Delta T.
tt_approx = ut1 + delta_t_approx / DAY_S
delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx)
# We can now estimate TT with an error of < 1e-9 seconds within
# 10 centuries of either side of the present; for details, see:
# https://github.com/skyfielders/astronomy-notebooks
# and look for the notebook "error-in-timescale-ut1.ipynb".
tt = ut1 + delta_t_approx / DAY_S
t = Time(self, tt)
t.ut1 = ut1
return t | python | def ut1_jd(self, jd):
"""Build a `Time` from UT1 a Julian date.
Supply the Universal Time (UT1) as a Julian date:
>>> t = ts.ut1_jd(2456675.56640625)
>>> t.ut1
2456675.56640625
"""
ut1 = _to_array(jd)
# Estimate TT = UT1, to get a rough Delta T estimate.
tt_approx = ut1
delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx)
# Use the rough Delta T to make a much better estimate of TT,
# then generate an even better Delta T.
tt_approx = ut1 + delta_t_approx / DAY_S
delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx)
# We can now estimate TT with an error of < 1e-9 seconds within
# 10 centuries of either side of the present; for details, see:
# https://github.com/skyfielders/astronomy-notebooks
# and look for the notebook "error-in-timescale-ut1.ipynb".
tt = ut1 + delta_t_approx / DAY_S
t = Time(self, tt)
t.ut1 = ut1
return t | [
"def",
"ut1_jd",
"(",
"self",
",",
"jd",
")",
":",
"ut1",
"=",
"_to_array",
"(",
"jd",
")",
"# Estimate TT = UT1, to get a rough Delta T estimate.",
"tt_approx",
"=",
"ut1",
"delta_t_approx",
"=",
"interpolate_delta_t",
"(",
"self",
".",
"delta_t_table",
",",
"tt_... | Build a `Time` from UT1 a Julian date.
Supply the Universal Time (UT1) as a Julian date:
>>> t = ts.ut1_jd(2456675.56640625)
>>> t.ut1
2456675.56640625 | [
"Build",
"a",
"Time",
"from",
"UT1",
"a",
"Julian",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L270-L298 | train | 224,806 |
skyfielders/python-skyfield | skyfield/timelib.py | Time.astimezone_and_leap_second | def astimezone_and_leap_second(self, tz):
"""Convert to a Python ``datetime`` and leap second in a timezone.
Convert this time to a Python ``datetime`` and a leap second::
dt, leap_second = t.astimezone_and_leap_second(tz)
The argument ``tz`` should be a timezone from the third-party
``pytz`` package, which must be installed separately. The date
and time returned will be for that time zone.
The leap second value is provided because a Python ``datetime``
can only number seconds ``0`` through ``59``, but leap seconds
have a designation of at least ``60``. The leap second return
value will normally be ``0``, but will instead be ``1`` if the
date and time are a UTC leap second. Add the leap second value
to the ``second`` field of the ``datetime`` to learn the real
name of the second.
If this time is an array, then an array of ``datetime`` objects
and an array of leap second integers is returned, instead of a
single value each.
"""
dt, leap_second = self.utc_datetime_and_leap_second()
normalize = getattr(tz, 'normalize', None)
if self.shape and normalize is not None:
dt = array([normalize(d.astimezone(tz)) for d in dt])
elif self.shape:
dt = array([d.astimezone(tz) for d in dt])
elif normalize is not None:
dt = normalize(dt.astimezone(tz))
else:
dt = dt.astimezone(tz)
return dt, leap_second | python | def astimezone_and_leap_second(self, tz):
"""Convert to a Python ``datetime`` and leap second in a timezone.
Convert this time to a Python ``datetime`` and a leap second::
dt, leap_second = t.astimezone_and_leap_second(tz)
The argument ``tz`` should be a timezone from the third-party
``pytz`` package, which must be installed separately. The date
and time returned will be for that time zone.
The leap second value is provided because a Python ``datetime``
can only number seconds ``0`` through ``59``, but leap seconds
have a designation of at least ``60``. The leap second return
value will normally be ``0``, but will instead be ``1`` if the
date and time are a UTC leap second. Add the leap second value
to the ``second`` field of the ``datetime`` to learn the real
name of the second.
If this time is an array, then an array of ``datetime`` objects
and an array of leap second integers is returned, instead of a
single value each.
"""
dt, leap_second = self.utc_datetime_and_leap_second()
normalize = getattr(tz, 'normalize', None)
if self.shape and normalize is not None:
dt = array([normalize(d.astimezone(tz)) for d in dt])
elif self.shape:
dt = array([d.astimezone(tz) for d in dt])
elif normalize is not None:
dt = normalize(dt.astimezone(tz))
else:
dt = dt.astimezone(tz)
return dt, leap_second | [
"def",
"astimezone_and_leap_second",
"(",
"self",
",",
"tz",
")",
":",
"dt",
",",
"leap_second",
"=",
"self",
".",
"utc_datetime_and_leap_second",
"(",
")",
"normalize",
"=",
"getattr",
"(",
"tz",
",",
"'normalize'",
",",
"None",
")",
"if",
"self",
".",
"s... | Convert to a Python ``datetime`` and leap second in a timezone.
Convert this time to a Python ``datetime`` and a leap second::
dt, leap_second = t.astimezone_and_leap_second(tz)
The argument ``tz`` should be a timezone from the third-party
``pytz`` package, which must be installed separately. The date
and time returned will be for that time zone.
The leap second value is provided because a Python ``datetime``
can only number seconds ``0`` through ``59``, but leap seconds
have a designation of at least ``60``. The leap second return
value will normally be ``0``, but will instead be ``1`` if the
date and time are a UTC leap second. Add the leap second value
to the ``second`` field of the ``datetime`` to learn the real
name of the second.
If this time is an array, then an array of ``datetime`` objects
and an array of leap second integers is returned, instead of a
single value each. | [
"Convert",
"to",
"a",
"Python",
"datetime",
"and",
"leap",
"second",
"in",
"a",
"timezone",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L365-L399 | train | 224,807 |
skyfielders/python-skyfield | skyfield/timelib.py | Time.utc_datetime_and_leap_second | def utc_datetime_and_leap_second(self):
"""Convert to a Python ``datetime`` in UTC, plus a leap second value.
Convert this time to a `datetime`_ object and a leap second::
dt, leap_second = t.utc_datetime_and_leap_second()
If the third-party `pytz`_ package is available, then its
``utc`` timezone will be used as the timezone of the return
value. Otherwise, Skyfield uses its own ``utc`` timezone.
The leap second value is provided because a Python ``datetime``
can only number seconds ``0`` through ``59``, but leap seconds
have a designation of at least ``60``. The leap second return
value will normally be ``0``, but will instead be ``1`` if the
date and time are a UTC leap second. Add the leap second value
to the ``second`` field of the ``datetime`` to learn the real
name of the second.
If this time is an array, then an array of ``datetime`` objects
and an array of leap second integers is returned, instead of a
single value each.
"""
year, month, day, hour, minute, second = self._utc_tuple(
_half_millisecond)
second, fraction = divmod(second, 1.0)
second = second.astype(int)
leap_second = second // 60
second -= leap_second
milli = (fraction * 1000).astype(int) * 1000
if self.shape:
utcs = [utc] * self.shape[0]
argsets = zip(year, month, day, hour, minute, second, milli, utcs)
dt = array([datetime(*args) for args in argsets])
else:
dt = datetime(year, month, day, hour, minute, second, milli, utc)
return dt, leap_second | python | def utc_datetime_and_leap_second(self):
"""Convert to a Python ``datetime`` in UTC, plus a leap second value.
Convert this time to a `datetime`_ object and a leap second::
dt, leap_second = t.utc_datetime_and_leap_second()
If the third-party `pytz`_ package is available, then its
``utc`` timezone will be used as the timezone of the return
value. Otherwise, Skyfield uses its own ``utc`` timezone.
The leap second value is provided because a Python ``datetime``
can only number seconds ``0`` through ``59``, but leap seconds
have a designation of at least ``60``. The leap second return
value will normally be ``0``, but will instead be ``1`` if the
date and time are a UTC leap second. Add the leap second value
to the ``second`` field of the ``datetime`` to learn the real
name of the second.
If this time is an array, then an array of ``datetime`` objects
and an array of leap second integers is returned, instead of a
single value each.
"""
year, month, day, hour, minute, second = self._utc_tuple(
_half_millisecond)
second, fraction = divmod(second, 1.0)
second = second.astype(int)
leap_second = second // 60
second -= leap_second
milli = (fraction * 1000).astype(int) * 1000
if self.shape:
utcs = [utc] * self.shape[0]
argsets = zip(year, month, day, hour, minute, second, milli, utcs)
dt = array([datetime(*args) for args in argsets])
else:
dt = datetime(year, month, day, hour, minute, second, milli, utc)
return dt, leap_second | [
"def",
"utc_datetime_and_leap_second",
"(",
"self",
")",
":",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
"=",
"self",
".",
"_utc_tuple",
"(",
"_half_millisecond",
")",
"second",
",",
"fraction",
"=",
"divmod",
"(",
"second... | Convert to a Python ``datetime`` in UTC, plus a leap second value.
Convert this time to a `datetime`_ object and a leap second::
dt, leap_second = t.utc_datetime_and_leap_second()
If the third-party `pytz`_ package is available, then its
``utc`` timezone will be used as the timezone of the return
value. Otherwise, Skyfield uses its own ``utc`` timezone.
The leap second value is provided because a Python ``datetime``
can only number seconds ``0`` through ``59``, but leap seconds
have a designation of at least ``60``. The leap second return
value will normally be ``0``, but will instead be ``1`` if the
date and time are a UTC leap second. Add the leap second value
to the ``second`` field of the ``datetime`` to learn the real
name of the second.
If this time is an array, then an array of ``datetime`` objects
and an array of leap second integers is returned, instead of a
single value each. | [
"Convert",
"to",
"a",
"Python",
"datetime",
"in",
"UTC",
"plus",
"a",
"leap",
"second",
"value",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L425-L462 | train | 224,808 |
skyfielders/python-skyfield | skyfield/timelib.py | Time.utc_strftime | def utc_strftime(self, format):
"""Format the UTC time using a Python date formatting string.
This internally calls the Python ``strftime()`` routine from the
Standard Library ``time()`` module, for which you can find a
quick reference at ``http://strftime.org/``. If this object is
an array of times, then a sequence of strings is returned
instead of a single string.
"""
tup = self._utc_tuple(_half_second)
year, month, day, hour, minute, second = tup
second = second.astype(int)
zero = zeros_like(year)
tup = (year, month, day, hour, minute, second, zero, zero, zero)
if self.shape:
return [strftime(format, item) for item in zip(*tup)]
else:
return strftime(format, tup) | python | def utc_strftime(self, format):
"""Format the UTC time using a Python date formatting string.
This internally calls the Python ``strftime()`` routine from the
Standard Library ``time()`` module, for which you can find a
quick reference at ``http://strftime.org/``. If this object is
an array of times, then a sequence of strings is returned
instead of a single string.
"""
tup = self._utc_tuple(_half_second)
year, month, day, hour, minute, second = tup
second = second.astype(int)
zero = zeros_like(year)
tup = (year, month, day, hour, minute, second, zero, zero, zero)
if self.shape:
return [strftime(format, item) for item in zip(*tup)]
else:
return strftime(format, tup) | [
"def",
"utc_strftime",
"(",
"self",
",",
"format",
")",
":",
"tup",
"=",
"self",
".",
"_utc_tuple",
"(",
"_half_second",
")",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
"=",
"tup",
"second",
"=",
"second",
".",
"asty... | Format the UTC time using a Python date formatting string.
This internally calls the Python ``strftime()`` routine from the
Standard Library ``time()`` module, for which you can find a
quick reference at ``http://strftime.org/``. If this object is
an array of times, then a sequence of strings is returned
instead of a single string. | [
"Format",
"the",
"UTC",
"time",
"using",
"a",
"Python",
"date",
"formatting",
"string",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L520-L538 | train | 224,809 |
skyfielders/python-skyfield | skyfield/timelib.py | Time._utc_year | def _utc_year(self):
"""Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below.
"""
d = self._utc_float() - 1721059.5
#d += offset
C = 365 * 100 + 24
d -= 365
d += d // C - d // (4 * C)
d += 365
# Y = d / C * 100
# print(Y)
K = 365 * 3 + 366
d -= (d + K*7//8) // K
# d -= d // 1461.0
return d / 365.0 | python | def _utc_year(self):
"""Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below.
"""
d = self._utc_float() - 1721059.5
#d += offset
C = 365 * 100 + 24
d -= 365
d += d // C - d // (4 * C)
d += 365
# Y = d / C * 100
# print(Y)
K = 365 * 3 + 366
d -= (d + K*7//8) // K
# d -= d // 1461.0
return d / 365.0 | [
"def",
"_utc_year",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"_utc_float",
"(",
")",
"-",
"1721059.5",
"#d += offset",
"C",
"=",
"365",
"*",
"100",
"+",
"24",
"d",
"-=",
"365",
"d",
"+=",
"d",
"//",
"C",
"-",
"d",
"//",
"(",
"4",
"*",
"C... | Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below. | [
"Return",
"a",
"fractional",
"UTC",
"year",
"for",
"convenience",
"when",
"plotting",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L540-L557 | train | 224,810 |
skyfielders/python-skyfield | skyfield/timelib.py | Time._utc_float | def _utc_float(self):
"""Return UTC as a floating point Julian date."""
tai = self.tai
leap_dates = self.ts.leap_dates
leap_offsets = self.ts.leap_offsets
leap_reverse_dates = leap_dates + leap_offsets / DAY_S
i = searchsorted(leap_reverse_dates, tai, 'right')
return tai - leap_offsets[i] / DAY_S | python | def _utc_float(self):
"""Return UTC as a floating point Julian date."""
tai = self.tai
leap_dates = self.ts.leap_dates
leap_offsets = self.ts.leap_offsets
leap_reverse_dates = leap_dates + leap_offsets / DAY_S
i = searchsorted(leap_reverse_dates, tai, 'right')
return tai - leap_offsets[i] / DAY_S | [
"def",
"_utc_float",
"(",
"self",
")",
":",
"tai",
"=",
"self",
".",
"tai",
"leap_dates",
"=",
"self",
".",
"ts",
".",
"leap_dates",
"leap_offsets",
"=",
"self",
".",
"ts",
".",
"leap_offsets",
"leap_reverse_dates",
"=",
"leap_dates",
"+",
"leap_offsets",
... | Return UTC as a floating point Julian date. | [
"Return",
"UTC",
"as",
"a",
"floating",
"point",
"Julian",
"date",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/timelib.py#L586-L593 | train | 224,811 |
skyfielders/python-skyfield | skyfield/earthlib.py | terra | def terra(latitude, longitude, elevation, gast):
"""Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).
The return value is a tuple of two 3-vectors `(pos, vel)` in the
dynamical reference system (the true equator and equinox of date)
whose components are measured in au with respect to the center of
the Earth.
"""
zero = zeros_like(gast)
sinphi = sin(latitude)
cosphi = cos(latitude)
c = 1.0 / sqrt(cosphi * cosphi +
sinphi * sinphi * one_minus_flattening_squared)
s = one_minus_flattening_squared * c
ach = earth_radius_au * c + elevation
ash = earth_radius_au * s + elevation
# Compute local sidereal time factors at the observer's longitude.
stlocl = 15.0 * DEG2RAD * gast + longitude
sinst = sin(stlocl)
cosst = cos(stlocl)
# Compute position vector components in kilometers.
ac = ach * cosphi
acsst = ac * sinst
accst = ac * cosst
pos = array((accst, acsst, zero + ash * sinphi))
# Compute velocity vector components in kilometers/sec.
vel = ANGVEL * DAY_S * array((-acsst, accst, zero))
return pos, vel | python | def terra(latitude, longitude, elevation, gast):
"""Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).
The return value is a tuple of two 3-vectors `(pos, vel)` in the
dynamical reference system (the true equator and equinox of date)
whose components are measured in au with respect to the center of
the Earth.
"""
zero = zeros_like(gast)
sinphi = sin(latitude)
cosphi = cos(latitude)
c = 1.0 / sqrt(cosphi * cosphi +
sinphi * sinphi * one_minus_flattening_squared)
s = one_minus_flattening_squared * c
ach = earth_radius_au * c + elevation
ash = earth_radius_au * s + elevation
# Compute local sidereal time factors at the observer's longitude.
stlocl = 15.0 * DEG2RAD * gast + longitude
sinst = sin(stlocl)
cosst = cos(stlocl)
# Compute position vector components in kilometers.
ac = ach * cosphi
acsst = ac * sinst
accst = ac * cosst
pos = array((accst, acsst, zero + ash * sinphi))
# Compute velocity vector components in kilometers/sec.
vel = ANGVEL * DAY_S * array((-acsst, accst, zero))
return pos, vel | [
"def",
"terra",
"(",
"latitude",
",",
"longitude",
",",
"elevation",
",",
"gast",
")",
":",
"zero",
"=",
"zeros_like",
"(",
"gast",
")",
"sinphi",
"=",
"sin",
"(",
"latitude",
")",
"cosphi",
"=",
"cos",
"(",
"latitude",
")",
"c",
"=",
"1.0",
"/",
"... | Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).
The return value is a tuple of two 3-vectors `(pos, vel)` in the
dynamical reference system (the true equator and equinox of date)
whose components are measured in au with respect to the center of
the Earth. | [
"Compute",
"the",
"position",
"and",
"velocity",
"of",
"a",
"terrestrial",
"observer",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L15-L55 | train | 224,812 |
skyfielders/python-skyfield | skyfield/earthlib.py | compute_limb_angle | def compute_limb_angle(position_au, observer_au):
"""Determine the angle of an object above or below the Earth's limb.
Given an object's GCRS `position_au` [x,y,z] vector and the position
of an `observer_au` as a vector in the same coordinate system,
return a tuple that provides `(limb_ang, nadir_ang)`:
limb_angle
Angle of observed object above (+) or below (-) limb in degrees.
nadir_angle
Nadir angle of observed object as a fraction of apparent radius
of limb: <1.0 means below the limb, =1.0 means on the limb, and
>1.0 means above the limb.
"""
# Compute the distance to the object and the distance to the observer.
disobj = sqrt(dots(position_au, position_au))
disobs = sqrt(dots(observer_au, observer_au))
# Compute apparent angular radius of Earth's limb.
aprad = arcsin(minimum(earth_radius_au / disobs, 1.0))
# Compute zenith distance of Earth's limb.
zdlim = pi - aprad
# Compute zenith distance of observed object.
coszd = dots(position_au, observer_au) / (disobj * disobs)
coszd = clip(coszd, -1.0, 1.0)
zdobj = arccos(coszd)
# Angle of object wrt limb is difference in zenith distances.
limb_angle = (zdlim - zdobj) * RAD2DEG
# Nadir angle of object as a fraction of angular radius of limb.
nadir_angle = (pi - zdobj) / aprad
return limb_angle, nadir_angle | python | def compute_limb_angle(position_au, observer_au):
"""Determine the angle of an object above or below the Earth's limb.
Given an object's GCRS `position_au` [x,y,z] vector and the position
of an `observer_au` as a vector in the same coordinate system,
return a tuple that provides `(limb_ang, nadir_ang)`:
limb_angle
Angle of observed object above (+) or below (-) limb in degrees.
nadir_angle
Nadir angle of observed object as a fraction of apparent radius
of limb: <1.0 means below the limb, =1.0 means on the limb, and
>1.0 means above the limb.
"""
# Compute the distance to the object and the distance to the observer.
disobj = sqrt(dots(position_au, position_au))
disobs = sqrt(dots(observer_au, observer_au))
# Compute apparent angular radius of Earth's limb.
aprad = arcsin(minimum(earth_radius_au / disobs, 1.0))
# Compute zenith distance of Earth's limb.
zdlim = pi - aprad
# Compute zenith distance of observed object.
coszd = dots(position_au, observer_au) / (disobj * disobs)
coszd = clip(coszd, -1.0, 1.0)
zdobj = arccos(coszd)
# Angle of object wrt limb is difference in zenith distances.
limb_angle = (zdlim - zdobj) * RAD2DEG
# Nadir angle of object as a fraction of angular radius of limb.
nadir_angle = (pi - zdobj) / aprad
return limb_angle, nadir_angle | [
"def",
"compute_limb_angle",
"(",
"position_au",
",",
"observer_au",
")",
":",
"# Compute the distance to the object and the distance to the observer.",
"disobj",
"=",
"sqrt",
"(",
"dots",
"(",
"position_au",
",",
"position_au",
")",
")",
"disobs",
"=",
"sqrt",
"(",
"... | Determine the angle of an object above or below the Earth's limb.
Given an object's GCRS `position_au` [x,y,z] vector and the position
of an `observer_au` as a vector in the same coordinate system,
return a tuple that provides `(limb_ang, nadir_ang)`:
limb_angle
Angle of observed object above (+) or below (-) limb in degrees.
nadir_angle
Nadir angle of observed object as a fraction of apparent radius
of limb: <1.0 means below the limb, =1.0 means on the limb, and
>1.0 means above the limb. | [
"Determine",
"the",
"angle",
"of",
"an",
"object",
"above",
"or",
"below",
"the",
"Earth",
"s",
"limb",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L85-L127 | train | 224,813 |
skyfielders/python-skyfield | skyfield/earthlib.py | sidereal_time | def sidereal_time(t):
"""Compute Greenwich sidereal time at the given ``Time``."""
# Compute the Earth Rotation Angle. Time argument is UT1.
theta = earth_rotation_angle(t.ut1)
# The equinox method. See Circular 179, Section 2.6.2.
# Precession-in-RA terms in mean sidereal time taken from third
# reference, eq. (42), with coefficients in arcseconds.
t = (t.tdb - T0) / 36525.0
st = ( 0.014506 +
(((( - 0.0000000368 * t
- 0.000029956 ) * t
- 0.00000044 ) * t
+ 1.3915817 ) * t
+ 4612.156534 ) * t)
# Form the Greenwich sidereal time.
return (st / 54000.0 + theta * 24.0) % 24.0 | python | def sidereal_time(t):
"""Compute Greenwich sidereal time at the given ``Time``."""
# Compute the Earth Rotation Angle. Time argument is UT1.
theta = earth_rotation_angle(t.ut1)
# The equinox method. See Circular 179, Section 2.6.2.
# Precession-in-RA terms in mean sidereal time taken from third
# reference, eq. (42), with coefficients in arcseconds.
t = (t.tdb - T0) / 36525.0
st = ( 0.014506 +
(((( - 0.0000000368 * t
- 0.000029956 ) * t
- 0.00000044 ) * t
+ 1.3915817 ) * t
+ 4612.156534 ) * t)
# Form the Greenwich sidereal time.
return (st / 54000.0 + theta * 24.0) % 24.0 | [
"def",
"sidereal_time",
"(",
"t",
")",
":",
"# Compute the Earth Rotation Angle. Time argument is UT1.",
"theta",
"=",
"earth_rotation_angle",
"(",
"t",
".",
"ut1",
")",
"# The equinox method. See Circular 179, Section 2.6.2.",
"# Precession-in-RA terms in mean sidereal time taken ... | Compute Greenwich sidereal time at the given ``Time``. | [
"Compute",
"Greenwich",
"sidereal",
"time",
"at",
"the",
"given",
"Time",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L130-L151 | train | 224,814 |
skyfielders/python-skyfield | skyfield/earthlib.py | refraction | def refraction(alt_degrees, temperature_C, pressure_mbar):
"""Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon.
"""
r = 0.016667 / tan((alt_degrees + 7.31 / (alt_degrees + 4.4)) * DEG2RAD)
d = r * (0.28 * pressure_mbar / (temperature_C + 273.0))
return where((-1.0 <= alt_degrees) & (alt_degrees <= 89.9), d, 0.0) | python | def refraction(alt_degrees, temperature_C, pressure_mbar):
"""Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon.
"""
r = 0.016667 / tan((alt_degrees + 7.31 / (alt_degrees + 4.4)) * DEG2RAD)
d = r * (0.28 * pressure_mbar / (temperature_C + 273.0))
return where((-1.0 <= alt_degrees) & (alt_degrees <= 89.9), d, 0.0) | [
"def",
"refraction",
"(",
"alt_degrees",
",",
"temperature_C",
",",
"pressure_mbar",
")",
":",
"r",
"=",
"0.016667",
"/",
"tan",
"(",
"(",
"alt_degrees",
"+",
"7.31",
"/",
"(",
"alt_degrees",
"+",
"4.4",
")",
")",
"*",
"DEG2RAD",
")",
"d",
"=",
"r",
... | Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon. | [
"Given",
"an",
"observed",
"altitude",
"return",
"how",
"much",
"the",
"image",
"is",
"refracted",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L166-L175 | train | 224,815 |
skyfielders/python-skyfield | skyfield/earthlib.py | refract | def refract(alt_degrees, temperature_C, pressure_mbar):
"""Given an unrefracted `alt` determine where it will appear in the sky."""
alt = alt_degrees
while True:
alt1 = alt
alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar)
converged = abs(alt - alt1) <= 3.0e-5
if converged.all():
break
return alt | python | def refract(alt_degrees, temperature_C, pressure_mbar):
"""Given an unrefracted `alt` determine where it will appear in the sky."""
alt = alt_degrees
while True:
alt1 = alt
alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar)
converged = abs(alt - alt1) <= 3.0e-5
if converged.all():
break
return alt | [
"def",
"refract",
"(",
"alt_degrees",
",",
"temperature_C",
",",
"pressure_mbar",
")",
":",
"alt",
"=",
"alt_degrees",
"while",
"True",
":",
"alt1",
"=",
"alt",
"alt",
"=",
"alt_degrees",
"+",
"refraction",
"(",
"alt",
",",
"temperature_C",
",",
"pressure_mb... | Given an unrefracted `alt` determine where it will appear in the sky. | [
"Given",
"an",
"unrefracted",
"alt",
"determine",
"where",
"it",
"will",
"appear",
"in",
"the",
"sky",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/earthlib.py#L178-L187 | train | 224,816 |
skyfielders/python-skyfield | skyfield/precessionlib.py | compute_precession | def compute_precession(jd_tdb):
"""Return the rotation matrices for precessing to an array of epochs.
`jd_tdb` - array of TDB Julian dates
The array returned has the shape `(3, 3, n)` where `n` is the number
of dates that have been provided as input.
"""
eps0 = 84381.406
# 't' is time in TDB centuries.
t = (jd_tdb - T0) / 36525.0
# Numerical coefficients of psi_a, omega_a, and chi_a, along with
# epsilon_0, the obliquity at J2000.0, are 4-angle formulation from
# Capitaine et al. (2003), eqs. (4), (37), & (39).
psia = ((((- 0.0000000951 * t
+ 0.000132851 ) * t
- 0.00114045 ) * t
- 1.0790069 ) * t
+ 5038.481507 ) * t
omegaa = ((((+ 0.0000003337 * t
- 0.000000467 ) * t
- 0.00772503 ) * t
+ 0.0512623 ) * t
- 0.025754 ) * t + eps0
chia = ((((- 0.0000000560 * t
+ 0.000170663 ) * t
- 0.00121197 ) * t
- 2.3814292 ) * t
+ 10.556403 ) * t
eps0 = eps0 * ASEC2RAD
psia = psia * ASEC2RAD
omegaa = omegaa * ASEC2RAD
chia = chia * ASEC2RAD
sa = sin(eps0)
ca = cos(eps0)
sb = sin(-psia)
cb = cos(-psia)
sc = sin(-omegaa)
cc = cos(-omegaa)
sd = sin(chia)
cd = cos(chia)
# Compute elements of precession rotation matrix equivalent to
# R3(chi_a) R1(-omega_a) R3(-psi_a) R1(epsilon_0).
rot3 = array(((cd * cb - sb * sd * cc,
cd * sb * ca + sd * cc * cb * ca - sa * sd * sc,
cd * sb * sa + sd * cc * cb * sa + ca * sd * sc),
(-sd * cb - sb * cd * cc,
-sd * sb * ca + cd * cc * cb * ca - sa * cd * sc,
-sd * sb * sa + cd * cc * cb * sa + ca * cd * sc),
(sb * sc,
-sc * cb * ca - sa * cc,
-sc * cb * sa + cc * ca)))
return rot3 | python | def compute_precession(jd_tdb):
"""Return the rotation matrices for precessing to an array of epochs.
`jd_tdb` - array of TDB Julian dates
The array returned has the shape `(3, 3, n)` where `n` is the number
of dates that have been provided as input.
"""
eps0 = 84381.406
# 't' is time in TDB centuries.
t = (jd_tdb - T0) / 36525.0
# Numerical coefficients of psi_a, omega_a, and chi_a, along with
# epsilon_0, the obliquity at J2000.0, are 4-angle formulation from
# Capitaine et al. (2003), eqs. (4), (37), & (39).
psia = ((((- 0.0000000951 * t
+ 0.000132851 ) * t
- 0.00114045 ) * t
- 1.0790069 ) * t
+ 5038.481507 ) * t
omegaa = ((((+ 0.0000003337 * t
- 0.000000467 ) * t
- 0.00772503 ) * t
+ 0.0512623 ) * t
- 0.025754 ) * t + eps0
chia = ((((- 0.0000000560 * t
+ 0.000170663 ) * t
- 0.00121197 ) * t
- 2.3814292 ) * t
+ 10.556403 ) * t
eps0 = eps0 * ASEC2RAD
psia = psia * ASEC2RAD
omegaa = omegaa * ASEC2RAD
chia = chia * ASEC2RAD
sa = sin(eps0)
ca = cos(eps0)
sb = sin(-psia)
cb = cos(-psia)
sc = sin(-omegaa)
cc = cos(-omegaa)
sd = sin(chia)
cd = cos(chia)
# Compute elements of precession rotation matrix equivalent to
# R3(chi_a) R1(-omega_a) R3(-psi_a) R1(epsilon_0).
rot3 = array(((cd * cb - sb * sd * cc,
cd * sb * ca + sd * cc * cb * ca - sa * sd * sc,
cd * sb * sa + sd * cc * cb * sa + ca * sd * sc),
(-sd * cb - sb * cd * cc,
-sd * sb * ca + cd * cc * cb * ca - sa * cd * sc,
-sd * sb * sa + cd * cc * cb * sa + ca * cd * sc),
(sb * sc,
-sc * cb * ca - sa * cc,
-sc * cb * sa + cc * ca)))
return rot3 | [
"def",
"compute_precession",
"(",
"jd_tdb",
")",
":",
"eps0",
"=",
"84381.406",
"# 't' is time in TDB centuries.",
"t",
"=",
"(",
"jd_tdb",
"-",
"T0",
")",
"/",
"36525.0",
"# Numerical coefficients of psi_a, omega_a, and chi_a, along with",
"# epsilon_0, the obliquity at J200... | Return the rotation matrices for precessing to an array of epochs.
`jd_tdb` - array of TDB Julian dates
The array returned has the shape `(3, 3, n)` where `n` is the number
of dates that have been provided as input. | [
"Return",
"the",
"rotation",
"matrices",
"for",
"precessing",
"to",
"an",
"array",
"of",
"epochs",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/precessionlib.py#L5-L69 | train | 224,817 |
skyfielders/python-skyfield | skyfield/nutationlib.py | compute_nutation | def compute_nutation(t):
"""Generate the nutation rotations for Time `t`.
If the Julian date is scalar, a simple ``(3, 3)`` matrix is
returned; if the date is an array of length ``n``, then an array of
matrices is returned with dimensions ``(3, 3, n)``.
"""
oblm, oblt, eqeq, psi, eps = t._earth_tilt
cobm = cos(oblm * DEG2RAD)
sobm = sin(oblm * DEG2RAD)
cobt = cos(oblt * DEG2RAD)
sobt = sin(oblt * DEG2RAD)
cpsi = cos(psi * ASEC2RAD)
spsi = sin(psi * ASEC2RAD)
return array(((cpsi,
-spsi * cobm,
-spsi * sobm),
(spsi * cobt,
cpsi * cobm * cobt + sobm * sobt,
cpsi * sobm * cobt - cobm * sobt),
(spsi * sobt,
cpsi * cobm * sobt - sobm * cobt,
cpsi * sobm * sobt + cobm * cobt))) | python | def compute_nutation(t):
"""Generate the nutation rotations for Time `t`.
If the Julian date is scalar, a simple ``(3, 3)`` matrix is
returned; if the date is an array of length ``n``, then an array of
matrices is returned with dimensions ``(3, 3, n)``.
"""
oblm, oblt, eqeq, psi, eps = t._earth_tilt
cobm = cos(oblm * DEG2RAD)
sobm = sin(oblm * DEG2RAD)
cobt = cos(oblt * DEG2RAD)
sobt = sin(oblt * DEG2RAD)
cpsi = cos(psi * ASEC2RAD)
spsi = sin(psi * ASEC2RAD)
return array(((cpsi,
-spsi * cobm,
-spsi * sobm),
(spsi * cobt,
cpsi * cobm * cobt + sobm * sobt,
cpsi * sobm * cobt - cobm * sobt),
(spsi * sobt,
cpsi * cobm * sobt - sobm * cobt,
cpsi * sobm * sobt + cobm * cobt))) | [
"def",
"compute_nutation",
"(",
"t",
")",
":",
"oblm",
",",
"oblt",
",",
"eqeq",
",",
"psi",
",",
"eps",
"=",
"t",
".",
"_earth_tilt",
"cobm",
"=",
"cos",
"(",
"oblm",
"*",
"DEG2RAD",
")",
"sobm",
"=",
"sin",
"(",
"oblm",
"*",
"DEG2RAD",
")",
"co... | Generate the nutation rotations for Time `t`.
If the Julian date is scalar, a simple ``(3, 3)`` matrix is
returned; if the date is an array of length ``n``, then an array of
matrices is returned with dimensions ``(3, 3, n)``. | [
"Generate",
"the",
"nutation",
"rotations",
"for",
"Time",
"t",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L19-L44 | train | 224,818 |
skyfielders/python-skyfield | skyfield/nutationlib.py | earth_tilt | def earth_tilt(t):
"""Return a tuple of information about the earth's axis and position.
`t` - A Time object.
The returned tuple contains five items:
``mean_ob`` - Mean obliquity of the ecliptic in degrees.
``true_ob`` - True obliquity of the ecliptic in degrees.
``eq_eq`` - Equation of the equinoxes in seconds of time.
``d_psi`` - Nutation in longitude in arcseconds.
``d_eps`` - Nutation in obliquity in arcseconds.
"""
dp, de = t._nutation_angles
c_terms = equation_of_the_equinoxes_complimentary_terms(t.tt) / ASEC2RAD
d_psi = dp * 1e-7 + t.psi_correction
d_eps = de * 1e-7 + t.eps_correction
mean_ob = mean_obliquity(t.tdb)
true_ob = mean_ob + d_eps
mean_ob /= 3600.0
true_ob /= 3600.0
eq_eq = d_psi * cos(mean_ob * DEG2RAD) + c_terms
eq_eq /= 15.0
return mean_ob, true_ob, eq_eq, d_psi, d_eps | python | def earth_tilt(t):
"""Return a tuple of information about the earth's axis and position.
`t` - A Time object.
The returned tuple contains five items:
``mean_ob`` - Mean obliquity of the ecliptic in degrees.
``true_ob`` - True obliquity of the ecliptic in degrees.
``eq_eq`` - Equation of the equinoxes in seconds of time.
``d_psi`` - Nutation in longitude in arcseconds.
``d_eps`` - Nutation in obliquity in arcseconds.
"""
dp, de = t._nutation_angles
c_terms = equation_of_the_equinoxes_complimentary_terms(t.tt) / ASEC2RAD
d_psi = dp * 1e-7 + t.psi_correction
d_eps = de * 1e-7 + t.eps_correction
mean_ob = mean_obliquity(t.tdb)
true_ob = mean_ob + d_eps
mean_ob /= 3600.0
true_ob /= 3600.0
eq_eq = d_psi * cos(mean_ob * DEG2RAD) + c_terms
eq_eq /= 15.0
return mean_ob, true_ob, eq_eq, d_psi, d_eps | [
"def",
"earth_tilt",
"(",
"t",
")",
":",
"dp",
",",
"de",
"=",
"t",
".",
"_nutation_angles",
"c_terms",
"=",
"equation_of_the_equinoxes_complimentary_terms",
"(",
"t",
".",
"tt",
")",
"/",
"ASEC2RAD",
"d_psi",
"=",
"dp",
"*",
"1e-7",
"+",
"t",
".",
"psi_... | Return a tuple of information about the earth's axis and position.
`t` - A Time object.
The returned tuple contains five items:
``mean_ob`` - Mean obliquity of the ecliptic in degrees.
``true_ob`` - True obliquity of the ecliptic in degrees.
``eq_eq`` - Equation of the equinoxes in seconds of time.
``d_psi`` - Nutation in longitude in arcseconds.
``d_eps`` - Nutation in obliquity in arcseconds. | [
"Return",
"a",
"tuple",
"of",
"information",
"about",
"the",
"earth",
"s",
"axis",
"and",
"position",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L46-L75 | train | 224,819 |
skyfielders/python-skyfield | skyfield/nutationlib.py | mean_obliquity | def mean_obliquity(jd_tdb):
"""Return the mean obliquity of the ecliptic in arcseconds.
`jd_tt` - TDB time as a Julian date float, or NumPy array of floats
"""
# Compute time in Julian centuries from epoch J2000.0.
t = (jd_tdb - T0) / 36525.0
# Compute the mean obliquity in arcseconds. Use expression from the
# reference's eq. (39) with obliquity at J2000.0 taken from eq. (37)
# or Table 8.
epsilon = (((( - 0.0000000434 * t
- 0.000000576 ) * t
+ 0.00200340 ) * t
- 0.0001831 ) * t
- 46.836769 ) * t + 84381.406
return epsilon | python | def mean_obliquity(jd_tdb):
"""Return the mean obliquity of the ecliptic in arcseconds.
`jd_tt` - TDB time as a Julian date float, or NumPy array of floats
"""
# Compute time in Julian centuries from epoch J2000.0.
t = (jd_tdb - T0) / 36525.0
# Compute the mean obliquity in arcseconds. Use expression from the
# reference's eq. (39) with obliquity at J2000.0 taken from eq. (37)
# or Table 8.
epsilon = (((( - 0.0000000434 * t
- 0.000000576 ) * t
+ 0.00200340 ) * t
- 0.0001831 ) * t
- 46.836769 ) * t + 84381.406
return epsilon | [
"def",
"mean_obliquity",
"(",
"jd_tdb",
")",
":",
"# Compute time in Julian centuries from epoch J2000.0.",
"t",
"=",
"(",
"jd_tdb",
"-",
"T0",
")",
"/",
"36525.0",
"# Compute the mean obliquity in arcseconds. Use expression from the",
"# reference's eq. (39) with obliquity at J20... | Return the mean obliquity of the ecliptic in arcseconds.
`jd_tt` - TDB time as a Julian date float, or NumPy array of floats | [
"Return",
"the",
"mean",
"obliquity",
"of",
"the",
"ecliptic",
"in",
"arcseconds",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L79-L99 | train | 224,820 |
skyfielders/python-skyfield | skyfield/nutationlib.py | equation_of_the_equinoxes_complimentary_terms | def equation_of_the_equinoxes_complimentary_terms(jd_tt):
"""Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
"""
# Interval between fundamental epoch J2000.0 and current date.
t = (jd_tt - T0) / 36525.0
# Build array for intermediate results.
shape = getattr(jd_tt, 'shape', ())
fa = zeros((14,) if shape == () else (14, shape[0]))
# Mean Anomaly of the Moon.
fa[0] = ((485868.249036 +
(715923.2178 +
( 31.8792 +
( 0.051635 +
( -0.00024470)
* t) * t) * t) * t) * ASEC2RAD
+ (1325.0*t % 1.0) * tau)
# Mean Anomaly of the Sun.
fa[1] = ((1287104.793048 +
(1292581.0481 +
( -0.5532 +
( +0.000136 +
( -0.00001149)
* t) * t) * t) * t) * ASEC2RAD
+ (99.0*t % 1.0) * tau)
# Mean Longitude of the Moon minus Mean Longitude of the Ascending
# Node of the Moon.
fa[2] = (( 335779.526232 +
( 295262.8478 +
( -12.7512 +
( -0.001037 +
( 0.00000417)
* t) * t) * t) * t) * ASEC2RAD
+ (1342.0*t % 1.0) * tau)
# Mean Elongation of the Moon from the Sun.
fa[3] = ((1072260.703692 +
(1105601.2090 +
( -6.3706 +
( 0.006593 +
( -0.00003169)
* t) * t) * t) * t) * ASEC2RAD
+ (1236.0*t % 1.0) * tau)
# Mean Longitude of the Ascending Node of the Moon.
fa[4] = (( 450160.398036 +
(-482890.5431 +
( 7.4722 +
( 0.007702 +
( -0.00005939)
* t) * t) * t) * t) * ASEC2RAD
+ (-5.0*t % 1.0) * tau)
fa[ 5] = (4.402608842 + 2608.7903141574 * t)
fa[ 6] = (3.176146697 + 1021.3285546211 * t)
fa[ 7] = (1.753470314 + 628.3075849991 * t)
fa[ 8] = (6.203480913 + 334.0612426700 * t)
fa[ 9] = (0.599546497 + 52.9690962641 * t)
fa[10] = (0.874016757 + 21.3299104960 * t)
fa[11] = (5.481293872 + 7.4781598567 * t)
fa[12] = (5.311886287 + 3.8133035638 * t)
fa[13] = (0.024381750 + 0.00000538691 * t) * t
fa %= tau
# Evaluate the complementary terms.
a = ke0_t.dot(fa)
s0 = se0_t_0.dot(sin(a)) + se0_t_1.dot(cos(a))
a = ke1.dot(fa)
s1 = se1_0 * sin(a) + se1_1 * cos(a)
c_terms = s0 + s1 * t
c_terms *= ASEC2RAD
return c_terms | python | def equation_of_the_equinoxes_complimentary_terms(jd_tt):
"""Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
"""
# Interval between fundamental epoch J2000.0 and current date.
t = (jd_tt - T0) / 36525.0
# Build array for intermediate results.
shape = getattr(jd_tt, 'shape', ())
fa = zeros((14,) if shape == () else (14, shape[0]))
# Mean Anomaly of the Moon.
fa[0] = ((485868.249036 +
(715923.2178 +
( 31.8792 +
( 0.051635 +
( -0.00024470)
* t) * t) * t) * t) * ASEC2RAD
+ (1325.0*t % 1.0) * tau)
# Mean Anomaly of the Sun.
fa[1] = ((1287104.793048 +
(1292581.0481 +
( -0.5532 +
( +0.000136 +
( -0.00001149)
* t) * t) * t) * t) * ASEC2RAD
+ (99.0*t % 1.0) * tau)
# Mean Longitude of the Moon minus Mean Longitude of the Ascending
# Node of the Moon.
fa[2] = (( 335779.526232 +
( 295262.8478 +
( -12.7512 +
( -0.001037 +
( 0.00000417)
* t) * t) * t) * t) * ASEC2RAD
+ (1342.0*t % 1.0) * tau)
# Mean Elongation of the Moon from the Sun.
fa[3] = ((1072260.703692 +
(1105601.2090 +
( -6.3706 +
( 0.006593 +
( -0.00003169)
* t) * t) * t) * t) * ASEC2RAD
+ (1236.0*t % 1.0) * tau)
# Mean Longitude of the Ascending Node of the Moon.
fa[4] = (( 450160.398036 +
(-482890.5431 +
( 7.4722 +
( 0.007702 +
( -0.00005939)
* t) * t) * t) * t) * ASEC2RAD
+ (-5.0*t % 1.0) * tau)
fa[ 5] = (4.402608842 + 2608.7903141574 * t)
fa[ 6] = (3.176146697 + 1021.3285546211 * t)
fa[ 7] = (1.753470314 + 628.3075849991 * t)
fa[ 8] = (6.203480913 + 334.0612426700 * t)
fa[ 9] = (0.599546497 + 52.9690962641 * t)
fa[10] = (0.874016757 + 21.3299104960 * t)
fa[11] = (5.481293872 + 7.4781598567 * t)
fa[12] = (5.311886287 + 3.8133035638 * t)
fa[13] = (0.024381750 + 0.00000538691 * t) * t
fa %= tau
# Evaluate the complementary terms.
a = ke0_t.dot(fa)
s0 = se0_t_0.dot(sin(a)) + se0_t_1.dot(cos(a))
a = ke1.dot(fa)
s1 = se1_0 * sin(a) + se1_1 * cos(a)
c_terms = s0 + s1 * t
c_terms *= ASEC2RAD
return c_terms | [
"def",
"equation_of_the_equinoxes_complimentary_terms",
"(",
"jd_tt",
")",
":",
"# Interval between fundamental epoch J2000.0 and current date.",
"t",
"=",
"(",
"jd_tt",
"-",
"T0",
")",
"/",
"36525.0",
"# Build array for intermediate results.",
"shape",
"=",
"getattr",
"(",
... | Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats | [
"Compute",
"the",
"complementary",
"terms",
"of",
"the",
"equation",
"of",
"the",
"equinoxes",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L101-L189 | train | 224,821 |
skyfielders/python-skyfield | skyfield/nutationlib.py | iau2000a | def iau2000a(jd_tt):
"""Compute Earth nutation based on the IAU 2000A nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each value is either a float, or a NumPy array
with the same dimensions as the input argument.
"""
# Interval between fundamental epoch J2000.0 and given date.
t = (jd_tt - T0) / 36525.0
# Compute fundamental arguments from Simon et al. (1994), in radians.
a = fundamental_arguments(t)
# ** Luni-solar nutation **
# Summation of luni-solar nutation series (in reverse order).
arg = nals_t.dot(a)
fmod(arg, tau, out=arg)
sarg = sin(arg)
carg = cos(arg)
stsc = array((sarg, t * sarg, carg)).T
ctcs = array((carg, t * carg, sarg)).T
dpsi = tensordot(stsc, lunisolar_longitude_coefficients)
deps = tensordot(ctcs, lunisolar_obliquity_coefficients)
# Compute and add in planetary components.
if getattr(t, 'shape', ()) == ():
a = t * anomaly_coefficient + anomaly_constant
else:
a = (outer(anomaly_coefficient, t).T + anomaly_constant).T
a[-1] *= t
fmod(a, tau, out=a)
arg = napl_t.dot(a)
fmod(arg, tau, out=arg)
sc = array((sin(arg), cos(arg))).T
dpsi += tensordot(sc, nutation_coefficients_longitude)
deps += tensordot(sc, nutation_coefficients_obliquity)
return dpsi, deps | python | def iau2000a(jd_tt):
"""Compute Earth nutation based on the IAU 2000A nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each value is either a float, or a NumPy array
with the same dimensions as the input argument.
"""
# Interval between fundamental epoch J2000.0 and given date.
t = (jd_tt - T0) / 36525.0
# Compute fundamental arguments from Simon et al. (1994), in radians.
a = fundamental_arguments(t)
# ** Luni-solar nutation **
# Summation of luni-solar nutation series (in reverse order).
arg = nals_t.dot(a)
fmod(arg, tau, out=arg)
sarg = sin(arg)
carg = cos(arg)
stsc = array((sarg, t * sarg, carg)).T
ctcs = array((carg, t * carg, sarg)).T
dpsi = tensordot(stsc, lunisolar_longitude_coefficients)
deps = tensordot(ctcs, lunisolar_obliquity_coefficients)
# Compute and add in planetary components.
if getattr(t, 'shape', ()) == ():
a = t * anomaly_coefficient + anomaly_constant
else:
a = (outer(anomaly_coefficient, t).T + anomaly_constant).T
a[-1] *= t
fmod(a, tau, out=a)
arg = napl_t.dot(a)
fmod(arg, tau, out=arg)
sc = array((sin(arg), cos(arg))).T
dpsi += tensordot(sc, nutation_coefficients_longitude)
deps += tensordot(sc, nutation_coefficients_obliquity)
return dpsi, deps | [
"def",
"iau2000a",
"(",
"jd_tt",
")",
":",
"# Interval between fundamental epoch J2000.0 and given date.",
"t",
"=",
"(",
"jd_tt",
"-",
"T0",
")",
"/",
"36525.0",
"# Compute fundamental arguments from Simon et al. (1994), in radians.",
"a",
"=",
"fundamental_arguments",
"(",
... | Compute Earth nutation based on the IAU 2000A nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each value is either a float, or a NumPy array
with the same dimensions as the input argument. | [
"Compute",
"Earth",
"nutation",
"based",
"on",
"the",
"IAU",
"2000A",
"nutation",
"model",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L222-L271 | train | 224,822 |
skyfielders/python-skyfield | skyfield/nutationlib.py | iau2000b | def iau2000b(jd_tt):
"""Compute Earth nutation based on the faster IAU 2000B nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each is either a float, or a NumPy array with
the same dimensions as the input argument. The result will not take
as long to compute as the full IAU 2000A series, but should still
agree with ``iau2000a()`` to within a milliarcsecond between the
years 1995 and 2020.
"""
dpplan = -0.000135 * 1e7
deplan = 0.000388 * 1e7
t = (jd_tt - T0) / 36525.0
# TODO: can these be replaced with fa0 and f1?
el = fmod (485868.249036 +
t * 1717915923.2178, ASEC360) * ASEC2RAD;
elp = fmod (1287104.79305 +
t * 129596581.0481, ASEC360) * ASEC2RAD;
f = fmod (335779.526232 +
t * 1739527262.8478, ASEC360) * ASEC2RAD;
d = fmod (1072260.70369 +
t * 1602961601.2090, ASEC360) * ASEC2RAD;
om = fmod (450160.398036 -
t * 6962890.5431, ASEC360) * ASEC2RAD;
a = array((el, elp, f, d, om))
arg = nals_t[:77].dot(a)
fmod(arg, tau, out=arg)
sarg = sin(arg)
carg = cos(arg)
stsc = array((sarg, t * sarg, carg)).T
ctcs = array((carg, t * carg, sarg)).T
dp = tensordot(stsc, lunisolar_longitude_coefficients[:77,])
de = tensordot(ctcs, lunisolar_obliquity_coefficients[:77,])
dpsi = dpplan + dp
deps = deplan + de
return dpsi, deps | python | def iau2000b(jd_tt):
"""Compute Earth nutation based on the faster IAU 2000B nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each is either a float, or a NumPy array with
the same dimensions as the input argument. The result will not take
as long to compute as the full IAU 2000A series, but should still
agree with ``iau2000a()`` to within a milliarcsecond between the
years 1995 and 2020.
"""
dpplan = -0.000135 * 1e7
deplan = 0.000388 * 1e7
t = (jd_tt - T0) / 36525.0
# TODO: can these be replaced with fa0 and f1?
el = fmod (485868.249036 +
t * 1717915923.2178, ASEC360) * ASEC2RAD;
elp = fmod (1287104.79305 +
t * 129596581.0481, ASEC360) * ASEC2RAD;
f = fmod (335779.526232 +
t * 1739527262.8478, ASEC360) * ASEC2RAD;
d = fmod (1072260.70369 +
t * 1602961601.2090, ASEC360) * ASEC2RAD;
om = fmod (450160.398036 -
t * 6962890.5431, ASEC360) * ASEC2RAD;
a = array((el, elp, f, d, om))
arg = nals_t[:77].dot(a)
fmod(arg, tau, out=arg)
sarg = sin(arg)
carg = cos(arg)
stsc = array((sarg, t * sarg, carg)).T
ctcs = array((carg, t * carg, sarg)).T
dp = tensordot(stsc, lunisolar_longitude_coefficients[:77,])
de = tensordot(ctcs, lunisolar_obliquity_coefficients[:77,])
dpsi = dpplan + dp
deps = deplan + de
return dpsi, deps | [
"def",
"iau2000b",
"(",
"jd_tt",
")",
":",
"dpplan",
"=",
"-",
"0.000135",
"*",
"1e7",
"deplan",
"=",
"0.000388",
"*",
"1e7",
"t",
"=",
"(",
"jd_tt",
"-",
"T0",
")",
"/",
"36525.0",
"# TODO: can these be replaced with fa0 and f1?",
"el",
"=",
"fmod",
"(",
... | Compute Earth nutation based on the faster IAU 2000B nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each is either a float, or a NumPy array with
the same dimensions as the input argument. The result will not take
as long to compute as the full IAU 2000A series, but should still
agree with ``iau2000a()`` to within a milliarcsecond between the
years 1995 and 2020. | [
"Compute",
"Earth",
"nutation",
"based",
"on",
"the",
"faster",
"IAU",
"2000B",
"nutation",
"model",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/nutationlib.py#L273-L325 | train | 224,823 |
skyfielders/python-skyfield | skyfield/data/hipparcos.py | load_dataframe | def load_dataframe(fobj, compression='gzip'):
"""Given an open file for `hip_main.dat.gz`, return a parsed dataframe.
If your copy of ``hip_main.dat`` has already been unzipped, pass the
optional argument ``compression=None``.
"""
try:
from pandas import read_fwf
except ImportError:
raise ImportError(PANDAS_MESSAGE)
names, colspecs = zip(
('hip', (2, 14)),
('magnitude', (41, 46)),
('ra_degrees', (51, 63)),
('dec_degrees', (64, 76)),
('parallax_mas', (79, 86)), # TODO: have Star load this
('ra_mas_per_year', (87, 95)),
('dec_mas_per_year', (96, 104)),
)
df = read_fwf(fobj, colspecs, names=names, compression=compression)
df = df.assign(
ra_hours = df['ra_degrees'] / 15.0,
epoch_year = 1991.25,
)
return df.set_index('hip') | python | def load_dataframe(fobj, compression='gzip'):
"""Given an open file for `hip_main.dat.gz`, return a parsed dataframe.
If your copy of ``hip_main.dat`` has already been unzipped, pass the
optional argument ``compression=None``.
"""
try:
from pandas import read_fwf
except ImportError:
raise ImportError(PANDAS_MESSAGE)
names, colspecs = zip(
('hip', (2, 14)),
('magnitude', (41, 46)),
('ra_degrees', (51, 63)),
('dec_degrees', (64, 76)),
('parallax_mas', (79, 86)), # TODO: have Star load this
('ra_mas_per_year', (87, 95)),
('dec_mas_per_year', (96, 104)),
)
df = read_fwf(fobj, colspecs, names=names, compression=compression)
df = df.assign(
ra_hours = df['ra_degrees'] / 15.0,
epoch_year = 1991.25,
)
return df.set_index('hip') | [
"def",
"load_dataframe",
"(",
"fobj",
",",
"compression",
"=",
"'gzip'",
")",
":",
"try",
":",
"from",
"pandas",
"import",
"read_fwf",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"PANDAS_MESSAGE",
")",
"names",
",",
"colspecs",
"=",
"zip",
"("... | Given an open file for `hip_main.dat.gz`, return a parsed dataframe.
If your copy of ``hip_main.dat`` has already been unzipped, pass the
optional argument ``compression=None``. | [
"Given",
"an",
"open",
"file",
"for",
"hip_main",
".",
"dat",
".",
"gz",
"return",
"a",
"parsed",
"dataframe",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/data/hipparcos.py#L44-L71 | train | 224,824 |
skyfielders/python-skyfield | skyfield/toposlib.py | Topos._altaz_rotation | def _altaz_rotation(self, t):
"""Compute the rotation from the ICRF into the alt-az system."""
R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0)
return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M) | python | def _altaz_rotation(self, t):
"""Compute the rotation from the ICRF into the alt-az system."""
R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0)
return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M) | [
"def",
"_altaz_rotation",
"(",
"self",
",",
"t",
")",
":",
"R_lon",
"=",
"rot_z",
"(",
"-",
"self",
".",
"longitude",
".",
"radians",
"-",
"t",
".",
"gast",
"*",
"tau",
"/",
"24.0",
")",
"return",
"einsum",
"(",
"'ij...,jk...,kl...->il...'",
",",
"self... | Compute the rotation from the ICRF into the alt-az system. | [
"Compute",
"the",
"rotation",
"from",
"the",
"ICRF",
"into",
"the",
"alt",
"-",
"az",
"system",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/toposlib.py#L70-L73 | train | 224,825 |
skyfielders/python-skyfield | skyfield/toposlib.py | Topos._at | def _at(self, t):
"""Compute the GCRS position and velocity of this Topos at time `t`."""
pos, vel = terra(self.latitude.radians, self.longitude.radians,
self.elevation.au, t.gast)
pos = einsum('ij...,j...->i...', t.MT, pos)
vel = einsum('ij...,j...->i...', t.MT, vel)
if self.x:
R = rot_y(self.x * ASEC2RAD)
pos = einsum('ij...,j...->i...', R, pos)
if self.y:
R = rot_x(self.y * ASEC2RAD)
pos = einsum('ij...,j...->i...', R, pos)
# TODO: also rotate velocity
return pos, vel, pos, None | python | def _at(self, t):
"""Compute the GCRS position and velocity of this Topos at time `t`."""
pos, vel = terra(self.latitude.radians, self.longitude.radians,
self.elevation.au, t.gast)
pos = einsum('ij...,j...->i...', t.MT, pos)
vel = einsum('ij...,j...->i...', t.MT, vel)
if self.x:
R = rot_y(self.x * ASEC2RAD)
pos = einsum('ij...,j...->i...', R, pos)
if self.y:
R = rot_x(self.y * ASEC2RAD)
pos = einsum('ij...,j...->i...', R, pos)
# TODO: also rotate velocity
return pos, vel, pos, None | [
"def",
"_at",
"(",
"self",
",",
"t",
")",
":",
"pos",
",",
"vel",
"=",
"terra",
"(",
"self",
".",
"latitude",
".",
"radians",
",",
"self",
".",
"longitude",
".",
"radians",
",",
"self",
".",
"elevation",
".",
"au",
",",
"t",
".",
"gast",
")",
"... | Compute the GCRS position and velocity of this Topos at time `t`. | [
"Compute",
"the",
"GCRS",
"position",
"and",
"velocity",
"of",
"this",
"Topos",
"at",
"time",
"t",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/toposlib.py#L75-L89 | train | 224,826 |
skyfielders/python-skyfield | skyfield/elementslib.py | osculating_elements_of | def osculating_elements_of(position, reference_frame=None):
"""Produce the osculating orbital elements for a position.
The ``position`` should be an :class:`~skyfield.positionlib.ICRF`
instance like that returned by the ``at()`` method of any Solar
System body, specifying a position, a velocity, and a time. An
instance of :class:`~skyfield.elementslib.OsculatingElements` is
returned.
"""
mu = GM_dict.get(position.center, 0) + GM_dict.get(position.target, 0)
if reference_frame is not None:
position_vec = Distance(reference_frame.dot(position.position.au))
velocity_vec = Velocity(reference_frame.dot(position.velocity.au_per_d))
else:
position_vec = position.position
velocity_vec = position.velocity
return OsculatingElements(position_vec,
velocity_vec,
position.t,
mu) | python | def osculating_elements_of(position, reference_frame=None):
"""Produce the osculating orbital elements for a position.
The ``position`` should be an :class:`~skyfield.positionlib.ICRF`
instance like that returned by the ``at()`` method of any Solar
System body, specifying a position, a velocity, and a time. An
instance of :class:`~skyfield.elementslib.OsculatingElements` is
returned.
"""
mu = GM_dict.get(position.center, 0) + GM_dict.get(position.target, 0)
if reference_frame is not None:
position_vec = Distance(reference_frame.dot(position.position.au))
velocity_vec = Velocity(reference_frame.dot(position.velocity.au_per_d))
else:
position_vec = position.position
velocity_vec = position.velocity
return OsculatingElements(position_vec,
velocity_vec,
position.t,
mu) | [
"def",
"osculating_elements_of",
"(",
"position",
",",
"reference_frame",
"=",
"None",
")",
":",
"mu",
"=",
"GM_dict",
".",
"get",
"(",
"position",
".",
"center",
",",
"0",
")",
"+",
"GM_dict",
".",
"get",
"(",
"position",
".",
"target",
",",
"0",
")",... | Produce the osculating orbital elements for a position.
The ``position`` should be an :class:`~skyfield.positionlib.ICRF`
instance like that returned by the ``at()`` method of any Solar
System body, specifying a position, a velocity, and a time. An
instance of :class:`~skyfield.elementslib.OsculatingElements` is
returned. | [
"Produce",
"the",
"osculating",
"orbital",
"elements",
"for",
"a",
"position",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/elementslib.py#L12-L34 | train | 224,827 |
skyfielders/python-skyfield | skyfield/sgp4lib.py | theta_GMST1982 | def theta_GMST1982(jd_ut1):
"""Return the angle of Greenwich Mean Standard Time 1982 given the JD.
This angle defines the difference between the idiosyncratic True
Equator Mean Equinox (TEME) frame of reference used by SGP4 and the
more standard Pseudo Earth Fixed (PEF) frame of reference.
From AIAA 2006-6753 Appendix C.
"""
t = (jd_ut1 - T0) / 36525.0
g = 67310.54841 + (8640184.812866 + (0.093104 + (-6.2e-6) * t) * t) * t
dg = 8640184.812866 + (0.093104 * 2.0 + (-6.2e-6 * 3.0) * t) * t
theta = (jd_ut1 % 1.0 + g * _second % 1.0) * tau
theta_dot = (1.0 + dg * _second / 36525.0) * tau
return theta, theta_dot | python | def theta_GMST1982(jd_ut1):
"""Return the angle of Greenwich Mean Standard Time 1982 given the JD.
This angle defines the difference between the idiosyncratic True
Equator Mean Equinox (TEME) frame of reference used by SGP4 and the
more standard Pseudo Earth Fixed (PEF) frame of reference.
From AIAA 2006-6753 Appendix C.
"""
t = (jd_ut1 - T0) / 36525.0
g = 67310.54841 + (8640184.812866 + (0.093104 + (-6.2e-6) * t) * t) * t
dg = 8640184.812866 + (0.093104 * 2.0 + (-6.2e-6 * 3.0) * t) * t
theta = (jd_ut1 % 1.0 + g * _second % 1.0) * tau
theta_dot = (1.0 + dg * _second / 36525.0) * tau
return theta, theta_dot | [
"def",
"theta_GMST1982",
"(",
"jd_ut1",
")",
":",
"t",
"=",
"(",
"jd_ut1",
"-",
"T0",
")",
"/",
"36525.0",
"g",
"=",
"67310.54841",
"+",
"(",
"8640184.812866",
"+",
"(",
"0.093104",
"+",
"(",
"-",
"6.2e-6",
")",
"*",
"t",
")",
"*",
"t",
")",
"*",... | Return the angle of Greenwich Mean Standard Time 1982 given the JD.
This angle defines the difference between the idiosyncratic True
Equator Mean Equinox (TEME) frame of reference used by SGP4 and the
more standard Pseudo Earth Fixed (PEF) frame of reference.
From AIAA 2006-6753 Appendix C. | [
"Return",
"the",
"angle",
"of",
"Greenwich",
"Mean",
"Standard",
"Time",
"1982",
"given",
"the",
"JD",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L160-L175 | train | 224,828 |
skyfielders/python-skyfield | skyfield/sgp4lib.py | TEME_to_ITRF | def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0):
"""Convert TEME position and velocity into standard ITRS coordinates.
This converts a position and velocity vector in the idiosyncratic
True Equator Mean Equinox (TEME) frame of reference used by the SGP4
theory into vectors into the more standard ITRS frame of reference.
The velocity should be provided in units per day, not per second.
From AIAA 2006-6753 Appendix C.
"""
theta, theta_dot = theta_GMST1982(jd_ut1)
zero = theta_dot * 0.0
angular_velocity = array([zero, zero, -theta_dot])
R = rot_z(-theta)
if len(rTEME.shape) == 1:
rPEF = (R).dot(rTEME)
vPEF = (R).dot(vTEME) + cross(angular_velocity, rPEF)
else:
rPEF = einsum('ij...,j...->i...', R, rTEME)
vPEF = einsum('ij...,j...->i...', R, vTEME) + cross(
angular_velocity, rPEF, 0, 0).T
if xp == 0.0 and yp == 0.0:
rITRF = rPEF
vITRF = vPEF
else:
W = (rot_x(yp)).dot(rot_y(xp))
rITRF = (W).dot(rPEF)
vITRF = (W).dot(vPEF)
return rITRF, vITRF | python | def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0):
"""Convert TEME position and velocity into standard ITRS coordinates.
This converts a position and velocity vector in the idiosyncratic
True Equator Mean Equinox (TEME) frame of reference used by the SGP4
theory into vectors into the more standard ITRS frame of reference.
The velocity should be provided in units per day, not per second.
From AIAA 2006-6753 Appendix C.
"""
theta, theta_dot = theta_GMST1982(jd_ut1)
zero = theta_dot * 0.0
angular_velocity = array([zero, zero, -theta_dot])
R = rot_z(-theta)
if len(rTEME.shape) == 1:
rPEF = (R).dot(rTEME)
vPEF = (R).dot(vTEME) + cross(angular_velocity, rPEF)
else:
rPEF = einsum('ij...,j...->i...', R, rTEME)
vPEF = einsum('ij...,j...->i...', R, vTEME) + cross(
angular_velocity, rPEF, 0, 0).T
if xp == 0.0 and yp == 0.0:
rITRF = rPEF
vITRF = vPEF
else:
W = (rot_x(yp)).dot(rot_y(xp))
rITRF = (W).dot(rPEF)
vITRF = (W).dot(vPEF)
return rITRF, vITRF | [
"def",
"TEME_to_ITRF",
"(",
"jd_ut1",
",",
"rTEME",
",",
"vTEME",
",",
"xp",
"=",
"0.0",
",",
"yp",
"=",
"0.0",
")",
":",
"theta",
",",
"theta_dot",
"=",
"theta_GMST1982",
"(",
"jd_ut1",
")",
"zero",
"=",
"theta_dot",
"*",
"0.0",
"angular_velocity",
"=... | Convert TEME position and velocity into standard ITRS coordinates.
This converts a position and velocity vector in the idiosyncratic
True Equator Mean Equinox (TEME) frame of reference used by the SGP4
theory into vectors into the more standard ITRS frame of reference.
The velocity should be provided in units per day, not per second.
From AIAA 2006-6753 Appendix C. | [
"Convert",
"TEME",
"position",
"and",
"velocity",
"into",
"standard",
"ITRS",
"coordinates",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L177-L208 | train | 224,829 |
skyfielders/python-skyfield | skyfield/sgp4lib.py | EarthSatellite.ITRF_position_velocity_error | def ITRF_position_velocity_error(self, t):
"""Return the ITRF position, velocity, and error at time `t`.
The position is an x,y,z vector measured in au, the velocity is
an x,y,z vector measured in au/day, and the error is a vector of
possible error messages for the time or vector of times `t`.
"""
rTEME, vTEME, error = self._position_and_velocity_TEME_km(t)
rTEME /= AU_KM
vTEME /= AU_KM
vTEME *= DAY_S
rITRF, vITRF = TEME_to_ITRF(t.ut1, rTEME, vTEME)
return rITRF, vITRF, error | python | def ITRF_position_velocity_error(self, t):
"""Return the ITRF position, velocity, and error at time `t`.
The position is an x,y,z vector measured in au, the velocity is
an x,y,z vector measured in au/day, and the error is a vector of
possible error messages for the time or vector of times `t`.
"""
rTEME, vTEME, error = self._position_and_velocity_TEME_km(t)
rTEME /= AU_KM
vTEME /= AU_KM
vTEME *= DAY_S
rITRF, vITRF = TEME_to_ITRF(t.ut1, rTEME, vTEME)
return rITRF, vITRF, error | [
"def",
"ITRF_position_velocity_error",
"(",
"self",
",",
"t",
")",
":",
"rTEME",
",",
"vTEME",
",",
"error",
"=",
"self",
".",
"_position_and_velocity_TEME_km",
"(",
"t",
")",
"rTEME",
"/=",
"AU_KM",
"vTEME",
"/=",
"AU_KM",
"vTEME",
"*=",
"DAY_S",
"rITRF",
... | Return the ITRF position, velocity, and error at time `t`.
The position is an x,y,z vector measured in au, the velocity is
an x,y,z vector measured in au/day, and the error is a vector of
possible error messages for the time or vector of times `t`. | [
"Return",
"the",
"ITRF",
"position",
"velocity",
"and",
"error",
"at",
"time",
"t",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L136-L149 | train | 224,830 |
skyfielders/python-skyfield | skyfield/sgp4lib.py | EarthSatellite._at | def _at(self, t):
"""Compute this satellite's GCRS position and velocity at time `t`."""
rITRF, vITRF, error = self.ITRF_position_velocity_error(t)
rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF)
return rGCRS, vGCRS, rGCRS, error | python | def _at(self, t):
"""Compute this satellite's GCRS position and velocity at time `t`."""
rITRF, vITRF, error = self.ITRF_position_velocity_error(t)
rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF)
return rGCRS, vGCRS, rGCRS, error | [
"def",
"_at",
"(",
"self",
",",
"t",
")",
":",
"rITRF",
",",
"vITRF",
",",
"error",
"=",
"self",
".",
"ITRF_position_velocity_error",
"(",
"t",
")",
"rGCRS",
",",
"vGCRS",
"=",
"ITRF_to_GCRS2",
"(",
"t",
",",
"rITRF",
",",
"vITRF",
")",
"return",
"rG... | Compute this satellite's GCRS position and velocity at time `t`. | [
"Compute",
"this",
"satellite",
"s",
"GCRS",
"position",
"and",
"velocity",
"at",
"time",
"t",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/sgp4lib.py#L151-L155 | train | 224,831 |
skyfielders/python-skyfield | skyfield/data/earth_orientation.py | morrison_and_stephenson_2004_table | def morrison_and_stephenson_2004_table():
"""Table of smoothed Delta T values from Morrison and Stephenson, 2004."""
import pandas as pd
f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html')
tables = pd.read_html(f.read())
df = tables[0]
return pd.DataFrame({'year': df[0], 'delta_t': df[1]}) | python | def morrison_and_stephenson_2004_table():
"""Table of smoothed Delta T values from Morrison and Stephenson, 2004."""
import pandas as pd
f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html')
tables = pd.read_html(f.read())
df = tables[0]
return pd.DataFrame({'year': df[0], 'delta_t': df[1]}) | [
"def",
"morrison_and_stephenson_2004_table",
"(",
")",
":",
"import",
"pandas",
"as",
"pd",
"f",
"=",
"load",
".",
"open",
"(",
"'http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html'",
")",
"tables",
"=",
"pd",
".",
"read_html",
"(",
"f",
".",
"read",
"(",
")",
")... | Table of smoothed Delta T values from Morrison and Stephenson, 2004. | [
"Table",
"of",
"smoothed",
"Delta",
"T",
"values",
"from",
"Morrison",
"and",
"Stephenson",
"2004",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/data/earth_orientation.py#L8-L14 | train | 224,832 |
skyfielders/python-skyfield | skyfield/functions.py | angle_between | def angle_between(u_vec, v_vec):
"""Given 2 vectors in `v` and `u`, return the angle separating them.
This works whether `v` and `u` each have the shape ``(3,)``, or
whether they are each whole arrays of corresponding x, y, and z
coordinates and have shape ``(3, N)``. The returned angle will be
between 0 and 180 degrees.
This formula is from Section 12 of:
https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf
"""
u = length_of(u_vec)
v = length_of(v_vec)
num = v*u_vec - u*v_vec
denom = v*u_vec + u*v_vec
return 2*arctan2(length_of(num), length_of(denom)) | python | def angle_between(u_vec, v_vec):
"""Given 2 vectors in `v` and `u`, return the angle separating them.
This works whether `v` and `u` each have the shape ``(3,)``, or
whether they are each whole arrays of corresponding x, y, and z
coordinates and have shape ``(3, N)``. The returned angle will be
between 0 and 180 degrees.
This formula is from Section 12 of:
https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf
"""
u = length_of(u_vec)
v = length_of(v_vec)
num = v*u_vec - u*v_vec
denom = v*u_vec + u*v_vec
return 2*arctan2(length_of(num), length_of(denom)) | [
"def",
"angle_between",
"(",
"u_vec",
",",
"v_vec",
")",
":",
"u",
"=",
"length_of",
"(",
"u_vec",
")",
"v",
"=",
"length_of",
"(",
"v_vec",
")",
"num",
"=",
"v",
"*",
"u_vec",
"-",
"u",
"*",
"v_vec",
"denom",
"=",
"v",
"*",
"u_vec",
"+",
"u",
... | Given 2 vectors in `v` and `u`, return the angle separating them.
This works whether `v` and `u` each have the shape ``(3,)``, or
whether they are each whole arrays of corresponding x, y, and z
coordinates and have shape ``(3, N)``. The returned angle will be
between 0 and 180 degrees.
This formula is from Section 12 of:
https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf | [
"Given",
"2",
"vectors",
"in",
"v",
"and",
"u",
"return",
"the",
"angle",
"separating",
"them",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/functions.py#L26-L42 | train | 224,833 |
skyfielders/python-skyfield | skyfield/starlib.py | Star._compute_vectors | def _compute_vectors(self):
"""Compute the star's position as an ICRF position and velocity."""
# Use 1 gigaparsec for stars whose parallax is zero.
parallax = self.parallax_mas
if parallax <= 0.0:
parallax = 1.0e-6
# Convert right ascension, declination, and parallax to position
# vector in equatorial system with units of au.
dist = 1.0 / sin(parallax * 1.0e-3 * ASEC2RAD)
r = self.ra.radians
d = self.dec.radians
cra = cos(r)
sra = sin(r)
cdc = cos(d)
sdc = sin(d)
self._position_au = array((
dist * cdc * cra,
dist * cdc * sra,
dist * sdc,
))
# Compute Doppler factor, which accounts for change in light
# travel time to star.
k = 1.0 / (1.0 - self.radial_km_per_s / C * 1000.0)
# Convert proper motion and radial velocity to orthogonal
# components of motion with units of au/day.
pmr = self.ra_mas_per_year / (parallax * 365.25) * k
pmd = self.dec_mas_per_year / (parallax * 365.25) * k
rvl = self.radial_km_per_s * DAY_S / self.au_km * k
# Transform motion vector to equatorial system.
self._velocity_au_per_d = array((
- pmr * sra - pmd * sdc * cra + rvl * cdc * cra,
pmr * cra - pmd * sdc * sra + rvl * cdc * sra,
pmd * cdc + rvl * sdc,
)) | python | def _compute_vectors(self):
"""Compute the star's position as an ICRF position and velocity."""
# Use 1 gigaparsec for stars whose parallax is zero.
parallax = self.parallax_mas
if parallax <= 0.0:
parallax = 1.0e-6
# Convert right ascension, declination, and parallax to position
# vector in equatorial system with units of au.
dist = 1.0 / sin(parallax * 1.0e-3 * ASEC2RAD)
r = self.ra.radians
d = self.dec.radians
cra = cos(r)
sra = sin(r)
cdc = cos(d)
sdc = sin(d)
self._position_au = array((
dist * cdc * cra,
dist * cdc * sra,
dist * sdc,
))
# Compute Doppler factor, which accounts for change in light
# travel time to star.
k = 1.0 / (1.0 - self.radial_km_per_s / C * 1000.0)
# Convert proper motion and radial velocity to orthogonal
# components of motion with units of au/day.
pmr = self.ra_mas_per_year / (parallax * 365.25) * k
pmd = self.dec_mas_per_year / (parallax * 365.25) * k
rvl = self.radial_km_per_s * DAY_S / self.au_km * k
# Transform motion vector to equatorial system.
self._velocity_au_per_d = array((
- pmr * sra - pmd * sdc * cra + rvl * cdc * cra,
pmr * cra - pmd * sdc * sra + rvl * cdc * sra,
pmd * cdc + rvl * sdc,
)) | [
"def",
"_compute_vectors",
"(",
"self",
")",
":",
"# Use 1 gigaparsec for stars whose parallax is zero.",
"parallax",
"=",
"self",
".",
"parallax_mas",
"if",
"parallax",
"<=",
"0.0",
":",
"parallax",
"=",
"1.0e-6",
"# Convert right ascension, declination, and parallax to posi... | Compute the star's position as an ICRF position and velocity. | [
"Compute",
"the",
"star",
"s",
"position",
"as",
"an",
"ICRF",
"position",
"and",
"velocity",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/starlib.py#L126-L170 | train | 224,834 |
skyfielders/python-skyfield | skyfield/units.py | _to_array | def _to_array(value):
"""As a convenience, turn Python lists and tuples into NumPy arrays."""
if isinstance(value, (tuple, list)):
return array(value)
elif isinstance(value, (float, int)):
return np.float64(value)
else:
return value | python | def _to_array(value):
"""As a convenience, turn Python lists and tuples into NumPy arrays."""
if isinstance(value, (tuple, list)):
return array(value)
elif isinstance(value, (float, int)):
return np.float64(value)
else:
return value | [
"def",
"_to_array",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"array",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"... | As a convenience, turn Python lists and tuples into NumPy arrays. | [
"As",
"a",
"convenience",
"turn",
"Python",
"lists",
"and",
"tuples",
"into",
"NumPy",
"arrays",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L12-L19 | train | 224,835 |
skyfielders/python-skyfield | skyfield/units.py | _sexagesimalize_to_float | def _sexagesimalize_to_float(value):
"""Decompose `value` into units, minutes, and seconds.
Note that this routine is not appropriate for displaying a value,
because rounding to the smallest digit of display is necessary
before showing a value to the user. Use `_sexagesimalize_to_int()`
for data being displayed to the user.
This routine simply decomposes the floating point `value` into a
sign (+1.0 or -1.0), units, minutes, and seconds, returning the
result in a four-element tuple.
>>> _sexagesimalize_to_float(12.05125)
(1.0, 12.0, 3.0, 4.5)
>>> _sexagesimalize_to_float(-12.05125)
(-1.0, 12.0, 3.0, 4.5)
"""
sign = np.sign(value)
n = abs(value)
minutes, seconds = divmod(n * 3600.0, 60.0)
units, minutes = divmod(minutes, 60.0)
return sign, units, minutes, seconds | python | def _sexagesimalize_to_float(value):
"""Decompose `value` into units, minutes, and seconds.
Note that this routine is not appropriate for displaying a value,
because rounding to the smallest digit of display is necessary
before showing a value to the user. Use `_sexagesimalize_to_int()`
for data being displayed to the user.
This routine simply decomposes the floating point `value` into a
sign (+1.0 or -1.0), units, minutes, and seconds, returning the
result in a four-element tuple.
>>> _sexagesimalize_to_float(12.05125)
(1.0, 12.0, 3.0, 4.5)
>>> _sexagesimalize_to_float(-12.05125)
(-1.0, 12.0, 3.0, 4.5)
"""
sign = np.sign(value)
n = abs(value)
minutes, seconds = divmod(n * 3600.0, 60.0)
units, minutes = divmod(minutes, 60.0)
return sign, units, minutes, seconds | [
"def",
"_sexagesimalize_to_float",
"(",
"value",
")",
":",
"sign",
"=",
"np",
".",
"sign",
"(",
"value",
")",
"n",
"=",
"abs",
"(",
"value",
")",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"n",
"*",
"3600.0",
",",
"60.0",
")",
"units",
",",
"mi... | Decompose `value` into units, minutes, and seconds.
Note that this routine is not appropriate for displaying a value,
because rounding to the smallest digit of display is necessary
before showing a value to the user. Use `_sexagesimalize_to_int()`
for data being displayed to the user.
This routine simply decomposes the floating point `value` into a
sign (+1.0 or -1.0), units, minutes, and seconds, returning the
result in a four-element tuple.
>>> _sexagesimalize_to_float(12.05125)
(1.0, 12.0, 3.0, 4.5)
>>> _sexagesimalize_to_float(-12.05125)
(-1.0, 12.0, 3.0, 4.5) | [
"Decompose",
"value",
"into",
"units",
"minutes",
"and",
"seconds",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L310-L332 | train | 224,836 |
skyfielders/python-skyfield | skyfield/units.py | _sexagesimalize_to_int | def _sexagesimalize_to_int(value, places=0):
"""Decompose `value` into units, minutes, seconds, and second fractions.
This routine prepares a value for sexagesimal display, with its
seconds fraction expressed as an integer with `places` digits. The
result is a tuple of five integers:
``(sign [either +1 or -1], units, minutes, seconds, second_fractions)``
The integers are properly rounded per astronomical convention so
that, for example, given ``places=3`` the result tuple ``(1, 11, 22,
33, 444)`` means that the input was closer to 11u 22' 33.444" than
to either 33.443" or 33.445" in its value.
"""
sign = int(np.sign(value))
value = abs(value)
power = 10 ** places
n = int(7200 * power * value + 1) // 2
n, fraction = divmod(n, power)
n, seconds = divmod(n, 60)
n, minutes = divmod(n, 60)
return sign, n, minutes, seconds, fraction | python | def _sexagesimalize_to_int(value, places=0):
"""Decompose `value` into units, minutes, seconds, and second fractions.
This routine prepares a value for sexagesimal display, with its
seconds fraction expressed as an integer with `places` digits. The
result is a tuple of five integers:
``(sign [either +1 or -1], units, minutes, seconds, second_fractions)``
The integers are properly rounded per astronomical convention so
that, for example, given ``places=3`` the result tuple ``(1, 11, 22,
33, 444)`` means that the input was closer to 11u 22' 33.444" than
to either 33.443" or 33.445" in its value.
"""
sign = int(np.sign(value))
value = abs(value)
power = 10 ** places
n = int(7200 * power * value + 1) // 2
n, fraction = divmod(n, power)
n, seconds = divmod(n, 60)
n, minutes = divmod(n, 60)
return sign, n, minutes, seconds, fraction | [
"def",
"_sexagesimalize_to_int",
"(",
"value",
",",
"places",
"=",
"0",
")",
":",
"sign",
"=",
"int",
"(",
"np",
".",
"sign",
"(",
"value",
")",
")",
"value",
"=",
"abs",
"(",
"value",
")",
"power",
"=",
"10",
"**",
"places",
"n",
"=",
"int",
"("... | Decompose `value` into units, minutes, seconds, and second fractions.
This routine prepares a value for sexagesimal display, with its
seconds fraction expressed as an integer with `places` digits. The
result is a tuple of five integers:
``(sign [either +1 or -1], units, minutes, seconds, second_fractions)``
The integers are properly rounded per astronomical convention so
that, for example, given ``places=3`` the result tuple ``(1, 11, 22,
33, 444)`` means that the input was closer to 11u 22' 33.444" than
to either 33.443" or 33.445" in its value. | [
"Decompose",
"value",
"into",
"units",
"minutes",
"seconds",
"and",
"second",
"fractions",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L334-L356 | train | 224,837 |
skyfielders/python-skyfield | skyfield/units.py | _hstr | def _hstr(hours, places=2):
"""Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan'
"""
if isnan(hours):
return 'nan'
sgn, h, m, s, etc = _sexagesimalize_to_int(hours, places)
sign = '-' if sgn < 0.0 else ''
return '%s%02dh %02dm %02d.%0*ds' % (sign, h, m, s, places, etc) | python | def _hstr(hours, places=2):
"""Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan'
"""
if isnan(hours):
return 'nan'
sgn, h, m, s, etc = _sexagesimalize_to_int(hours, places)
sign = '-' if sgn < 0.0 else ''
return '%s%02dh %02dm %02d.%0*ds' % (sign, h, m, s, places, etc) | [
"def",
"_hstr",
"(",
"hours",
",",
"places",
"=",
"2",
")",
":",
"if",
"isnan",
"(",
"hours",
")",
":",
"return",
"'nan'",
"sgn",
",",
"h",
",",
"m",
",",
"s",
",",
"etc",
"=",
"_sexagesimalize_to_int",
"(",
"hours",
",",
"places",
")",
"sign",
"... | Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan' | [
"Convert",
"floating",
"point",
"hours",
"into",
"a",
"sexagesimal",
"string",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L358-L373 | train | 224,838 |
skyfielders/python-skyfield | skyfield/units.py | _dstr | def _dstr(degrees, places=1, signed=False):
r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan'
"""
if isnan(degrees):
return 'nan'
sgn, d, m, s, etc = _sexagesimalize_to_int(degrees, places)
sign = '-' if sgn < 0.0 else '+' if signed else ''
return '%s%02ddeg %02d\' %02d.%0*d"' % (sign, d, m, s, places, etc) | python | def _dstr(degrees, places=1, signed=False):
r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan'
"""
if isnan(degrees):
return 'nan'
sgn, d, m, s, etc = _sexagesimalize_to_int(degrees, places)
sign = '-' if sgn < 0.0 else '+' if signed else ''
return '%s%02ddeg %02d\' %02d.%0*d"' % (sign, d, m, s, places, etc) | [
"def",
"_dstr",
"(",
"degrees",
",",
"places",
"=",
"1",
",",
"signed",
"=",
"False",
")",
":",
"if",
"isnan",
"(",
"degrees",
")",
":",
"return",
"'nan'",
"sgn",
",",
"d",
",",
"m",
",",
"s",
",",
"etc",
"=",
"_sexagesimalize_to_int",
"(",
"degree... | r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan' | [
"r",
"Convert",
"floating",
"point",
"degrees",
"into",
"a",
"sexagesimal",
"string",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L375-L392 | train | 224,839 |
skyfielders/python-skyfield | skyfield/units.py | _interpret_angle | def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
"""Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interpretation.
"""
if angle_object is not None:
if isinstance(angle_object, Angle):
return angle_object.radians
elif angle_float is not None:
return _unsexagesimalize(angle_float) * _from_degrees
raise ValueError('you must either provide the {0}= parameter with'
' an Angle argument or supply the {0}_{1}= parameter'
' with a numeric argument'.format(name, unit)) | python | def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
"""Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interpretation.
"""
if angle_object is not None:
if isinstance(angle_object, Angle):
return angle_object.radians
elif angle_float is not None:
return _unsexagesimalize(angle_float) * _from_degrees
raise ValueError('you must either provide the {0}= parameter with'
' an Angle argument or supply the {0}_{1}= parameter'
' with a numeric argument'.format(name, unit)) | [
"def",
"_interpret_angle",
"(",
"name",
",",
"angle_object",
",",
"angle_float",
",",
"unit",
"=",
"'degrees'",
")",
":",
"if",
"angle_object",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"angle_object",
",",
"Angle",
")",
":",
"return",
"angle_object... | Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interpretation. | [
"Return",
"an",
"angle",
"in",
"radians",
"from",
"one",
"of",
"two",
"arguments",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L423-L439 | train | 224,840 |
skyfielders/python-skyfield | skyfield/units.py | _interpret_ltude | def _interpret_ltude(value, name, psuffix, nsuffix):
"""Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`negative` - The string that indicates a negative angle ('S' or 'W').
"""
if not isinstance(value, str):
return Angle(degrees=_unsexagesimalize(value))
value = value.strip().upper()
if value.endswith(psuffix):
sign = +1.0
elif value.endswith(nsuffix):
sign = -1.0
else:
raise ValueError('your {0} string {1!r} does not end with either {2!r}'
' or {3!r}'.format(name, value, psuffix, nsuffix))
try:
value = float(value[:-1])
except ValueError:
raise ValueError('your {0} string {1!r} cannot be parsed as a floating'
' point number'.format(name, value))
return Angle(degrees=sign * value) | python | def _interpret_ltude(value, name, psuffix, nsuffix):
"""Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`negative` - The string that indicates a negative angle ('S' or 'W').
"""
if not isinstance(value, str):
return Angle(degrees=_unsexagesimalize(value))
value = value.strip().upper()
if value.endswith(psuffix):
sign = +1.0
elif value.endswith(nsuffix):
sign = -1.0
else:
raise ValueError('your {0} string {1!r} does not end with either {2!r}'
' or {3!r}'.format(name, value, psuffix, nsuffix))
try:
value = float(value[:-1])
except ValueError:
raise ValueError('your {0} string {1!r} cannot be parsed as a floating'
' point number'.format(name, value))
return Angle(degrees=sign * value) | [
"def",
"_interpret_ltude",
"(",
"value",
",",
"name",
",",
"psuffix",
",",
"nsuffix",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"Angle",
"(",
"degrees",
"=",
"_unsexagesimalize",
"(",
"value",
")",
")",
"value",
... | Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`negative` - The string that indicates a negative angle ('S' or 'W'). | [
"Interpret",
"a",
"string",
"float",
"or",
"tuple",
"as",
"a",
"latitude",
"or",
"longitude",
"angle",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L441-L469 | train | 224,841 |
skyfielders/python-skyfield | skyfield/units.py | Distance.to | def to(self, unit):
"""Convert this distance to the given AstroPy unit."""
from astropy.units import au
return (self.au * au).to(unit) | python | def to(self, unit):
"""Convert this distance to the given AstroPy unit."""
from astropy.units import au
return (self.au * au).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"au",
"return",
"(",
"self",
".",
"au",
"*",
"au",
")",
".",
"to",
"(",
"unit",
")"
] | Convert this distance to the given AstroPy unit. | [
"Convert",
"this",
"distance",
"to",
"the",
"given",
"AstroPy",
"unit",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L76-L79 | train | 224,842 |
skyfielders/python-skyfield | skyfield/units.py | Velocity.to | def to(self, unit):
"""Convert this velocity to the given AstroPy unit."""
from astropy.units import au, d
return (self.au_per_d * au / d).to(unit) | python | def to(self, unit):
"""Convert this velocity to the given AstroPy unit."""
from astropy.units import au, d
return (self.au_per_d * au / d).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"au",
",",
"d",
"return",
"(",
"self",
".",
"au_per_d",
"*",
"au",
"/",
"d",
")",
".",
"to",
"(",
"unit",
")"
] | Convert this velocity to the given AstroPy unit. | [
"Convert",
"this",
"velocity",
"to",
"the",
"given",
"AstroPy",
"unit",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L123-L126 | train | 224,843 |
skyfielders/python-skyfield | skyfield/units.py | Angle.hstr | def hstr(self, places=2, warn=True):
"""Convert to a string like ``12h 07m 30.00s``."""
if warn and self.preference != 'hours':
raise WrongUnitError('hstr')
if self.radians.size == 0:
return '<Angle []>'
hours = self._hours
shape = getattr(hours, 'shape', ())
if shape and shape != (1,):
return "{0} values from {1} to {2}".format(
len(hours),
_hstr(min(hours), places),
_hstr(max(hours), places),
)
return _hstr(hours, places) | python | def hstr(self, places=2, warn=True):
"""Convert to a string like ``12h 07m 30.00s``."""
if warn and self.preference != 'hours':
raise WrongUnitError('hstr')
if self.radians.size == 0:
return '<Angle []>'
hours = self._hours
shape = getattr(hours, 'shape', ())
if shape and shape != (1,):
return "{0} values from {1} to {2}".format(
len(hours),
_hstr(min(hours), places),
_hstr(max(hours), places),
)
return _hstr(hours, places) | [
"def",
"hstr",
"(",
"self",
",",
"places",
"=",
"2",
",",
"warn",
"=",
"True",
")",
":",
"if",
"warn",
"and",
"self",
".",
"preference",
"!=",
"'hours'",
":",
"raise",
"WrongUnitError",
"(",
"'hstr'",
")",
"if",
"self",
".",
"radians",
".",
"size",
... | Convert to a string like ``12h 07m 30.00s``. | [
"Convert",
"to",
"a",
"string",
"like",
"12h",
"07m",
"30",
".",
"00s",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L232-L246 | train | 224,844 |
skyfielders/python-skyfield | skyfield/units.py | Angle.dstr | def dstr(self, places=1, warn=True):
"""Convert to a string like ``181deg 52\' 30.0"``."""
if warn and self.preference != 'degrees':
raise WrongUnitError('dstr')
if self.radians.size == 0:
return '<Angle []>'
degrees = self._degrees
signed = self.signed
shape = getattr(degrees, 'shape', ())
if shape and shape != (1,):
return "{0} values from {1} to {2}".format(
len(degrees),
_dstr(min(degrees), places, signed),
_dstr(max(degrees), places, signed),
)
return _dstr(degrees, places, signed) | python | def dstr(self, places=1, warn=True):
"""Convert to a string like ``181deg 52\' 30.0"``."""
if warn and self.preference != 'degrees':
raise WrongUnitError('dstr')
if self.radians.size == 0:
return '<Angle []>'
degrees = self._degrees
signed = self.signed
shape = getattr(degrees, 'shape', ())
if shape and shape != (1,):
return "{0} values from {1} to {2}".format(
len(degrees),
_dstr(min(degrees), places, signed),
_dstr(max(degrees), places, signed),
)
return _dstr(degrees, places, signed) | [
"def",
"dstr",
"(",
"self",
",",
"places",
"=",
"1",
",",
"warn",
"=",
"True",
")",
":",
"if",
"warn",
"and",
"self",
".",
"preference",
"!=",
"'degrees'",
":",
"raise",
"WrongUnitError",
"(",
"'dstr'",
")",
"if",
"self",
".",
"radians",
".",
"size",... | Convert to a string like ``181deg 52\' 30.0"``. | [
"Convert",
"to",
"a",
"string",
"like",
"181deg",
"52",
"\\",
"30",
".",
"0",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L270-L285 | train | 224,845 |
skyfielders/python-skyfield | skyfield/units.py | Angle.to | def to(self, unit):
"""Convert this angle to the given AstroPy unit."""
from astropy.units import rad
return (self.radians * rad).to(unit)
# Or should this do:
from astropy.coordinates import Angle
from astropy.units import rad
return Angle(self.radians, rad).to(unit) | python | def to(self, unit):
"""Convert this angle to the given AstroPy unit."""
from astropy.units import rad
return (self.radians * rad).to(unit)
# Or should this do:
from astropy.coordinates import Angle
from astropy.units import rad
return Angle(self.radians, rad).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"rad",
"return",
"(",
"self",
".",
"radians",
"*",
"rad",
")",
".",
"to",
"(",
"unit",
")",
"# Or should this do:",
"from",
"astropy",
".",
"coordinates",
"impo... | Convert this angle to the given AstroPy unit. | [
"Convert",
"this",
"angle",
"to",
"the",
"given",
"AstroPy",
"unit",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L287-L295 | train | 224,846 |
skyfielders/python-skyfield | skyfield/positionlib.py | ICRF.separation_from | def separation_from(self, another_icrf):
"""Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1], [0,0,0,0]])
>>> directions.separation_from(ICRF([0,1,0])).degrees
array([ 90., 0., 90., 180.])
"""
p1 = self.position.au
p2 = another_icrf.position.au
u1 = p1 / length_of(p1)
u2 = p2 / length_of(p2)
if u2.ndim > 1:
if u1.ndim == 1:
u1 = u1[:,None]
elif u1.ndim > 1:
u2 = u2[:,None]
c = dots(u1, u2)
return Angle(radians=arccos(clip(c, -1.0, 1.0))) | python | def separation_from(self, another_icrf):
"""Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1], [0,0,0,0]])
>>> directions.separation_from(ICRF([0,1,0])).degrees
array([ 90., 0., 90., 180.])
"""
p1 = self.position.au
p2 = another_icrf.position.au
u1 = p1 / length_of(p1)
u2 = p2 / length_of(p2)
if u2.ndim > 1:
if u1.ndim == 1:
u1 = u1[:,None]
elif u1.ndim > 1:
u2 = u2[:,None]
c = dots(u1, u2)
return Angle(radians=arccos(clip(c, -1.0, 1.0))) | [
"def",
"separation_from",
"(",
"self",
",",
"another_icrf",
")",
":",
"p1",
"=",
"self",
".",
"position",
".",
"au",
"p2",
"=",
"another_icrf",
".",
"position",
".",
"au",
"u1",
"=",
"p1",
"/",
"length_of",
"(",
"p1",
")",
"u2",
"=",
"p2",
"/",
"le... | Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1], [0,0,0,0]])
>>> directions.separation_from(ICRF([0,1,0])).degrees
array([ 90., 0., 90., 180.]) | [
"Return",
"the",
"angle",
"between",
"this",
"position",
"and",
"another",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L134-L157 | train | 224,847 |
skyfielders/python-skyfield | skyfield/positionlib.py | ICRF.to_skycoord | def to_skycoord(self, unit=None):
"""Convert this distance to an AstroPy ``SkyCoord`` object."""
from astropy.coordinates import SkyCoord
from astropy.units import au
x, y, z = self.position.au
return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au) | python | def to_skycoord(self, unit=None):
"""Convert this distance to an AstroPy ``SkyCoord`` object."""
from astropy.coordinates import SkyCoord
from astropy.units import au
x, y, z = self.position.au
return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au) | [
"def",
"to_skycoord",
"(",
"self",
",",
"unit",
"=",
"None",
")",
":",
"from",
"astropy",
".",
"coordinates",
"import",
"SkyCoord",
"from",
"astropy",
".",
"units",
"import",
"au",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"position",
".",
"au",
"re... | Convert this distance to an AstroPy ``SkyCoord`` object. | [
"Convert",
"this",
"distance",
"to",
"an",
"AstroPy",
"SkyCoord",
"object",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L262-L267 | train | 224,848 |
skyfielders/python-skyfield | skyfield/positionlib.py | ICRF.from_altaz | def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None,
distance=Distance(au=0.1)):
"""Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as either a
float or a tuple of degrees, arcminutes, and arcseconds::
alt=Angle(...), az=Angle(...)
alt_degrees=23.2289, az_degrees=142.1161
alt_degrees=(23, 13, 44.1), az_degrees=(142, 6, 58.1)
The distance should be a :class:`~skyfield.units.Distance`
object, if provided; otherwise a default of 0.1 au is used.
"""
# TODO: should this method live on another class?
R = self.observer_data.altaz_rotation if self.observer_data else None
if R is None:
raise ValueError('only a position generated by a topos() call'
' knows the orientation of the horizon'
' and can understand altitude and azimuth')
alt = _interpret_angle('alt', alt, alt_degrees)
az = _interpret_angle('az', az, az_degrees)
r = distance.au
p = from_polar(r, alt, az)
p = einsum('ji...,j...->i...', R, p)
return Apparent(p) | python | def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None,
distance=Distance(au=0.1)):
"""Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as either a
float or a tuple of degrees, arcminutes, and arcseconds::
alt=Angle(...), az=Angle(...)
alt_degrees=23.2289, az_degrees=142.1161
alt_degrees=(23, 13, 44.1), az_degrees=(142, 6, 58.1)
The distance should be a :class:`~skyfield.units.Distance`
object, if provided; otherwise a default of 0.1 au is used.
"""
# TODO: should this method live on another class?
R = self.observer_data.altaz_rotation if self.observer_data else None
if R is None:
raise ValueError('only a position generated by a topos() call'
' knows the orientation of the horizon'
' and can understand altitude and azimuth')
alt = _interpret_angle('alt', alt, alt_degrees)
az = _interpret_angle('az', az, az_degrees)
r = distance.au
p = from_polar(r, alt, az)
p = einsum('ji...,j...->i...', R, p)
return Apparent(p) | [
"def",
"from_altaz",
"(",
"self",
",",
"alt",
"=",
"None",
",",
"az",
"=",
"None",
",",
"alt_degrees",
"=",
"None",
",",
"az_degrees",
"=",
"None",
",",
"distance",
"=",
"Distance",
"(",
"au",
"=",
"0.1",
")",
")",
":",
"# TODO: should this method live o... | Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as either a
float or a tuple of degrees, arcminutes, and arcseconds::
alt=Angle(...), az=Angle(...)
alt_degrees=23.2289, az_degrees=142.1161
alt_degrees=(23, 13, 44.1), az_degrees=(142, 6, 58.1)
The distance should be a :class:`~skyfield.units.Distance`
object, if provided; otherwise a default of 0.1 au is used. | [
"Generate",
"an",
"Apparent",
"position",
"from",
"an",
"altitude",
"and",
"azimuth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L277-L304 | train | 224,849 |
skyfielders/python-skyfield | skyfield/positionlib.py | Barycentric.observe | def observe(self, body):
"""Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
find how long it takes its light to arrive. Finally, the light
travel time is subtracted from `t` and the body is asked for a
series of increasingly exact positions to learn where it was
when it emitted the light that is now reaching this position.
>>> earth.at(t).observe(mars)
<Astrometric position and velocity at date t>
"""
p, v, t, light_time = body._observe_from_bcrs(self)
astrometric = Astrometric(p, v, t, observer_data=self.observer_data)
astrometric.light_time = light_time
return astrometric | python | def observe(self, body):
"""Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
find how long it takes its light to arrive. Finally, the light
travel time is subtracted from `t` and the body is asked for a
series of increasingly exact positions to learn where it was
when it emitted the light that is now reaching this position.
>>> earth.at(t).observe(mars)
<Astrometric position and velocity at date t>
"""
p, v, t, light_time = body._observe_from_bcrs(self)
astrometric = Astrometric(p, v, t, observer_data=self.observer_data)
astrometric.light_time = light_time
return astrometric | [
"def",
"observe",
"(",
"self",
",",
"body",
")",
":",
"p",
",",
"v",
",",
"t",
",",
"light_time",
"=",
"body",
".",
"_observe_from_bcrs",
"(",
"self",
")",
"astrometric",
"=",
"Astrometric",
"(",
"p",
",",
"v",
",",
"t",
",",
"observer_data",
"=",
... | Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
find how long it takes its light to arrive. Finally, the light
travel time is subtracted from `t` and the body is asked for a
series of increasingly exact positions to learn where it was
when it emitted the light that is now reaching this position.
>>> earth.at(t).observe(mars)
<Astrometric position and velocity at date t> | [
"Compute",
"the",
"Astrometric",
"position",
"of",
"a",
"body",
"from",
"this",
"location",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L349-L367 | train | 224,850 |
skyfielders/python-skyfield | skyfield/positionlib.py | Geocentric.subpoint | def subpoint(self):
"""Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
height of this position above the Earth's surface.
"""
if self.center != 399: # TODO: should an __init__() check this?
raise ValueError("you can only ask for the geographic subpoint"
" of a position measured from Earth's center")
t = self.t
xyz_au = einsum('ij...,j...->i...', t.M, self.position.au)
lat, lon, elevation_m = reverse_terra(xyz_au, t.gast)
# TODO. Move VectorFunction and Topos into this file, since the
# three kinds of class work together: Topos is-a VF; VF.at() can
# return a Geocentric position; and Geocentric.subpoint() should
# return a Topos. I'm deferring the refactoring for now, to get
# this new feature to users more quickly.
from .toposlib import Topos
return Topos(latitude=Angle(radians=lat),
longitude=Angle(radians=lon),
elevation_m=elevation_m) | python | def subpoint(self):
"""Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
height of this position above the Earth's surface.
"""
if self.center != 399: # TODO: should an __init__() check this?
raise ValueError("you can only ask for the geographic subpoint"
" of a position measured from Earth's center")
t = self.t
xyz_au = einsum('ij...,j...->i...', t.M, self.position.au)
lat, lon, elevation_m = reverse_terra(xyz_au, t.gast)
# TODO. Move VectorFunction and Topos into this file, since the
# three kinds of class work together: Topos is-a VF; VF.at() can
# return a Geocentric position; and Geocentric.subpoint() should
# return a Topos. I'm deferring the refactoring for now, to get
# this new feature to users more quickly.
from .toposlib import Topos
return Topos(latitude=Angle(radians=lat),
longitude=Angle(radians=lon),
elevation_m=elevation_m) | [
"def",
"subpoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"center",
"!=",
"399",
":",
"# TODO: should an __init__() check this?",
"raise",
"ValueError",
"(",
"\"you can only ask for the geographic subpoint\"",
"\" of a position measured from Earth's center\"",
")",
"t",
... | Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
height of this position above the Earth's surface. | [
"Return",
"the",
"latitude",
"and",
"longitude",
"directly",
"beneath",
"this",
"position",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L454-L478 | train | 224,851 |
skyfielders/python-skyfield | skyfield/charting.py | _plot_stars | def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25):
"""Experiment in progress, hence the underscore; expect changes."""
art = []
# from astropy import wcs
# w = wcs.WCS(naxis=2)
# w.wcs.crpix = [-234.75, 8.3393]
# w.wcs.cdelt = np.array([-0.066667, 0.066667])
# w.wcs.crval = [0, -90]
# w.wcs.ctype = ["RA---AIR", "DEC--AIR"]
# w.wcs.set_pv([(2, 1, 45.0)])
# import matplotlib.pyplot as plt
# plt.subplot(projection=wcs)
# #plt.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
# plt.grid(color='white', ls='solid')
# plt.xlabel('Galactic Longitude')
# plt.ylabel('Galactic Latitude')
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_xlim()
lim = max(abs(xmin), abs(xmax), abs(ymin), abs(ymax)) * margin
lims = (-lim, lim)
ax.set_xlim(lims)
ax.set_ylim(lims)
ax.set_aspect('equal')
o = observer[0]
# Dim stars: points of with varying gray levels.
c = catalog
c = c[c['magnitude'] > mag1]
c = c[c['magnitude'] <= mag2]
#print('Second star group:', len(c))
c = c.sort_values('magnitude', ascending=False)
s = Star(ra_hours=c.ra_hours, dec_degrees=c.dec_degrees)
spos = o.observe(s)
x, y = project(spos)
m = (mag2 - c['magnitude']) / (mag2 - mag1)
# Note that "gray_r" is white for 0.0 and black for 1.0
art.append(ax.scatter(
x, y, s=1.0,
c=1 - 0.8 * m, cmap='gray_r', vmin=0.0, vmax=1.0,
))
# Bright stars: black circles of varying radius, surrounded by a
# white gap in case stars are touching. Draw the brightest stars
# first to stop them from completely occluding smaller companions.
def mag_to_radius(m):
return (mag1 - m) * scale + 1.0
c = catalog
c = c[c['magnitude'] <= mag1]
c = c.sort_values('magnitude', ascending=True)
#print('First star group:', len(c))
s = Star(ra_hours=c.ra_hours, dec_degrees=c.dec_degrees)
spos = o.observe(s)
x, y = project(spos)
scale = 1.5
radius = mag_to_radius(c['magnitude'])
x2 = np.repeat(x, 2)
y2 = np.repeat(y, 2)
radius2 = (radius[:,None] + (3.0,0.0)).flatten()
c2 = ('w', 'k')
c2 = ('k', 'w')
art.append(ax.scatter(x2, y2, s=radius2 ** 2.0, c=c2))
return art, mag_to_radius | python | def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25):
"""Experiment in progress, hence the underscore; expect changes."""
art = []
# from astropy import wcs
# w = wcs.WCS(naxis=2)
# w.wcs.crpix = [-234.75, 8.3393]
# w.wcs.cdelt = np.array([-0.066667, 0.066667])
# w.wcs.crval = [0, -90]
# w.wcs.ctype = ["RA---AIR", "DEC--AIR"]
# w.wcs.set_pv([(2, 1, 45.0)])
# import matplotlib.pyplot as plt
# plt.subplot(projection=wcs)
# #plt.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
# plt.grid(color='white', ls='solid')
# plt.xlabel('Galactic Longitude')
# plt.ylabel('Galactic Latitude')
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_xlim()
lim = max(abs(xmin), abs(xmax), abs(ymin), abs(ymax)) * margin
lims = (-lim, lim)
ax.set_xlim(lims)
ax.set_ylim(lims)
ax.set_aspect('equal')
o = observer[0]
# Dim stars: points of with varying gray levels.
c = catalog
c = c[c['magnitude'] > mag1]
c = c[c['magnitude'] <= mag2]
#print('Second star group:', len(c))
c = c.sort_values('magnitude', ascending=False)
s = Star(ra_hours=c.ra_hours, dec_degrees=c.dec_degrees)
spos = o.observe(s)
x, y = project(spos)
m = (mag2 - c['magnitude']) / (mag2 - mag1)
# Note that "gray_r" is white for 0.0 and black for 1.0
art.append(ax.scatter(
x, y, s=1.0,
c=1 - 0.8 * m, cmap='gray_r', vmin=0.0, vmax=1.0,
))
# Bright stars: black circles of varying radius, surrounded by a
# white gap in case stars are touching. Draw the brightest stars
# first to stop them from completely occluding smaller companions.
def mag_to_radius(m):
return (mag1 - m) * scale + 1.0
c = catalog
c = c[c['magnitude'] <= mag1]
c = c.sort_values('magnitude', ascending=True)
#print('First star group:', len(c))
s = Star(ra_hours=c.ra_hours, dec_degrees=c.dec_degrees)
spos = o.observe(s)
x, y = project(spos)
scale = 1.5
radius = mag_to_radius(c['magnitude'])
x2 = np.repeat(x, 2)
y2 = np.repeat(y, 2)
radius2 = (radius[:,None] + (3.0,0.0)).flatten()
c2 = ('w', 'k')
c2 = ('k', 'w')
art.append(ax.scatter(x2, y2, s=radius2 ** 2.0, c=c2))
return art, mag_to_radius | [
"def",
"_plot_stars",
"(",
"catalog",
",",
"observer",
",",
"project",
",",
"ax",
",",
"mag1",
",",
"mag2",
",",
"margin",
"=",
"1.25",
")",
":",
"art",
"=",
"[",
"]",
"# from astropy import wcs",
"# w = wcs.WCS(naxis=2)",
"# w.wcs.crpix = [-234.75, 8.3393]",
"#... | Experiment in progress, hence the underscore; expect changes. | [
"Experiment",
"in",
"progress",
"hence",
"the",
"underscore",
";",
"expect",
"changes",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/charting.py#L9-L82 | train | 224,852 |
skyfielders/python-skyfield | skyfield/almanac.py | phase_angle | def phase_angle(ephemeris, body, t):
"""Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfield.units.Angle` object.
"""
earth = ephemeris['earth']
sun = ephemeris['sun']
body = ephemeris[body]
pe = earth.at(t).observe(body)
pe.position.au *= -1 # rotate 180 degrees to point back at Earth
t2 = t.ts.tt_jd(t.tt - pe.light_time)
ps = body.at(t2).observe(sun)
return pe.separation_from(ps) | python | def phase_angle(ephemeris, body, t):
"""Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfield.units.Angle` object.
"""
earth = ephemeris['earth']
sun = ephemeris['sun']
body = ephemeris[body]
pe = earth.at(t).observe(body)
pe.position.au *= -1 # rotate 180 degrees to point back at Earth
t2 = t.ts.tt_jd(t.tt - pe.light_time)
ps = body.at(t2).observe(sun)
return pe.separation_from(ps) | [
"def",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"body",
"=",
"ephemeris",
"[",
"body",
"]",
"pe",
"=",
"earth",
".",
"at",
"(",
"t"... | Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfield.units.Angle` object. | [
"Compute",
"the",
"phase",
"angle",
"of",
"a",
"body",
"viewed",
"from",
"Earth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L11-L27 | train | 224,853 |
skyfielders/python-skyfield | skyfield/almanac.py | fraction_illuminated | def fraction_illuminated(ephemeris, body, t):
"""Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
floating point number between zero and one. This simple routine
assumes that the body is a perfectly uniform sphere.
"""
a = phase_angle(ephemeris, body, t).radians
return 0.5 * (1.0 + cos(a)) | python | def fraction_illuminated(ephemeris, body, t):
"""Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
floating point number between zero and one. This simple routine
assumes that the body is a perfectly uniform sphere.
"""
a = phase_angle(ephemeris, body, t).radians
return 0.5 * (1.0 + cos(a)) | [
"def",
"fraction_illuminated",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"a",
"=",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
".",
"radians",
"return",
"0.5",
"*",
"(",
"1.0",
"+",
"cos",
"(",
"a",
")",
")"
] | Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
floating point number between zero and one. This simple routine
assumes that the body is a perfectly uniform sphere. | [
"Compute",
"the",
"illuminated",
"fraction",
"of",
"a",
"body",
"viewed",
"from",
"Earth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L29-L40 | train | 224,854 |
skyfielders/python-skyfield | skyfield/almanac.py | find_discrete | def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12):
"""Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search.
"""
ts = start_time.ts
jd0 = start_time.tt
jd1 = end_time.tt
if jd0 >= jd1:
raise ValueError('your start_time {0} is later than your end_time {1}'
.format(start_time, end_time))
periods = (jd1 - jd0) / f.rough_period
if periods < 1.0:
periods = 1.0
jd = linspace(jd0, jd1, periods * num // 1.0)
end_mask = linspace(0.0, 1.0, num)
start_mask = end_mask[::-1]
o = multiply.outer
while True:
t = ts.tt_jd(jd)
y = f(t)
indices = flatnonzero(diff(y))
if not len(indices):
return indices, y[0:0]
starts = jd.take(indices)
ends = jd.take(indices + 1)
# Since we start with equal intervals, they all should fall
# below epsilon at around the same time; so for efficiency we
# only test the first pair.
if ends[0] - starts[0] <= epsilon:
break
jd = o(starts, start_mask).flatten() + o(ends, end_mask).flatten()
return ts.tt_jd(ends), y.take(indices + 1) | python | def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12):
"""Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search.
"""
ts = start_time.ts
jd0 = start_time.tt
jd1 = end_time.tt
if jd0 >= jd1:
raise ValueError('your start_time {0} is later than your end_time {1}'
.format(start_time, end_time))
periods = (jd1 - jd0) / f.rough_period
if periods < 1.0:
periods = 1.0
jd = linspace(jd0, jd1, periods * num // 1.0)
end_mask = linspace(0.0, 1.0, num)
start_mask = end_mask[::-1]
o = multiply.outer
while True:
t = ts.tt_jd(jd)
y = f(t)
indices = flatnonzero(diff(y))
if not len(indices):
return indices, y[0:0]
starts = jd.take(indices)
ends = jd.take(indices + 1)
# Since we start with equal intervals, they all should fall
# below epsilon at around the same time; so for efficiency we
# only test the first pair.
if ends[0] - starts[0] <= epsilon:
break
jd = o(starts, start_mask).flatten() + o(ends, end_mask).flatten()
return ts.tt_jd(ends), y.take(indices + 1) | [
"def",
"find_discrete",
"(",
"start_time",
",",
"end_time",
",",
"f",
",",
"epsilon",
"=",
"EPSILON",
",",
"num",
"=",
"12",
")",
":",
"ts",
"=",
"start_time",
".",
"ts",
"jd0",
"=",
"start_time",
".",
"tt",
"jd1",
"=",
"end_time",
".",
"tt",
"if",
... | Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search. | [
"Find",
"the",
"times",
"when",
"a",
"function",
"changes",
"value",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L44-L101 | train | 224,855 |
skyfielders/python-skyfield | skyfield/almanac.py | seasons | def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris['earth']
sun = ephemeris['sun']
def season_at(t):
"""Return season 0 (Spring) through 3 (Winter) at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return (slon.radians // (tau / 4) % 4).astype(int)
season_at.rough_period = 90.0
return season_at | python | def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris['earth']
sun = ephemeris['sun']
def season_at(t):
"""Return season 0 (Spring) through 3 (Winter) at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return (slon.radians // (tau / 4) % 4).astype(int)
season_at.rough_period = 90.0
return season_at | [
"def",
"seasons",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"season_at",
"(",
"t",
")",
":",
"\"\"\"Return season 0 (Spring) through 3 (Winter) at time `t`.\"\"\"",
"t",
".",
"_... | Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"the",
"quarter",
"of",
"the",
"year",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L161-L180 | train | 224,856 |
skyfielders/python-skyfield | skyfield/almanac.py | sunrise_sunset | def sunrise_sunset(ephemeris, topos):
"""Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``.
"""
sun = ephemeris['sun']
topos_at = (ephemeris['earth'] + topos).at
def is_sun_up_at(t):
"""Return `True` if the sun has risen by time `t`."""
t._nutation_angles = iau2000b(t.tt)
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -0.8333
is_sun_up_at.rough_period = 0.5 # twice a day
return is_sun_up_at | python | def sunrise_sunset(ephemeris, topos):
"""Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``.
"""
sun = ephemeris['sun']
topos_at = (ephemeris['earth'] + topos).at
def is_sun_up_at(t):
"""Return `True` if the sun has risen by time `t`."""
t._nutation_angles = iau2000b(t.tt)
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -0.8333
is_sun_up_at.rough_period = 0.5 # twice a day
return is_sun_up_at | [
"def",
"sunrise_sunset",
"(",
"ephemeris",
",",
"topos",
")",
":",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"topos_at",
"=",
"(",
"ephemeris",
"[",
"'earth'",
"]",
"+",
"topos",
")",
".",
"at",
"def",
"is_sun_up_at",
"(",
"t",
")",
":",
"\"\"\"Retur... | Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"whether",
"the",
"sun",
"is",
"up",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L182-L200 | train | 224,857 |
skyfielders/python-skyfield | skyfield/almanac.py | moon_phases | def moon_phases(ephemeris):
"""Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
you want to give string names to each phase.
"""
earth = ephemeris['earth']
moon = ephemeris['moon']
sun = ephemeris['sun']
def moon_phase_at(t):
"""Return the phase of the moon 0 through 3 at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, mlon, _ = e.observe(moon).apparent().ecliptic_latlon('date')
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return ((mlon.radians - slon.radians) // (tau / 4) % 4).astype(int)
moon_phase_at.rough_period = 7.0 # one lunar phase per week
return moon_phase_at | python | def moon_phases(ephemeris):
"""Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
you want to give string names to each phase.
"""
earth = ephemeris['earth']
moon = ephemeris['moon']
sun = ephemeris['sun']
def moon_phase_at(t):
"""Return the phase of the moon 0 through 3 at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, mlon, _ = e.observe(moon).apparent().ecliptic_latlon('date')
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return ((mlon.radians - slon.radians) // (tau / 4) % 4).astype(int)
moon_phase_at.rough_period = 7.0 # one lunar phase per week
return moon_phase_at | [
"def",
"moon_phases",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"moon",
"=",
"ephemeris",
"[",
"'moon'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"moon_phase_at",
"(",
"t",
")",
":",
"\"\"\"Return the phase ... | Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
you want to give string names to each phase. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"the",
"moon",
"phase",
"0",
"through",
"3",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L209-L231 | train | 224,858 |
skyfielders/python-skyfield | skyfield/projections.py | _derive_stereographic | def _derive_stereographic():
"""Compute the formulae to cut-and-paste into the routine below."""
from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix
x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z')
# The angles we'll need to rotate through.
around_z = atan2(x_c, y_c)
around_x = acos(-z_c)
# Apply rotations to produce an "o" = output vector.
v = Matrix([x, y, z])
xo, yo, zo = rot_axis1(around_x) * rot_axis3(-around_z) * v
# Which we then use the stereographic projection to produce the
# final "p" = plotting coordinates.
xp = xo / (1 - zo)
yp = yo / (1 - zo)
return xp, yp | python | def _derive_stereographic():
"""Compute the formulae to cut-and-paste into the routine below."""
from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix
x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z')
# The angles we'll need to rotate through.
around_z = atan2(x_c, y_c)
around_x = acos(-z_c)
# Apply rotations to produce an "o" = output vector.
v = Matrix([x, y, z])
xo, yo, zo = rot_axis1(around_x) * rot_axis3(-around_z) * v
# Which we then use the stereographic projection to produce the
# final "p" = plotting coordinates.
xp = xo / (1 - zo)
yp = yo / (1 - zo)
return xp, yp | [
"def",
"_derive_stereographic",
"(",
")",
":",
"from",
"sympy",
"import",
"symbols",
",",
"atan2",
",",
"acos",
",",
"rot_axis1",
",",
"rot_axis3",
",",
"Matrix",
"x_c",
",",
"y_c",
",",
"z_c",
",",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"(",
"'x_c... | Compute the formulae to cut-and-paste into the routine below. | [
"Compute",
"the",
"formulae",
"to",
"cut",
"-",
"and",
"-",
"paste",
"into",
"the",
"routine",
"below",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/projections.py#L5-L23 | train | 224,859 |
reiinakano/scikit-plot | scikitplot/classifiers.py | classifier_factory | def classifier_factory(clf):
"""Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the instance methods
necessary for scikit-plot instance methods.
"""
required_methods = ['fit', 'score', 'predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you pass a '
'classifier instance?'.format(method))
optional_methods = ['predict_proba']
for method in optional_methods:
if not hasattr(clf, method):
warnings.warn('{} not in clf. Some plots may '
'not be possible to generate.'.format(method))
additional_methods = {
'plot_learning_curve': plot_learning_curve,
'plot_confusion_matrix': plot_confusion_matrix_with_cv,
'plot_roc_curve': plot_roc_curve_with_cv,
'plot_ks_statistic': plot_ks_statistic_with_cv,
'plot_precision_recall_curve': plot_precision_recall_curve_with_cv,
'plot_feature_importances': plot_feature_importances
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | python | def classifier_factory(clf):
"""Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the instance methods
necessary for scikit-plot instance methods.
"""
required_methods = ['fit', 'score', 'predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you pass a '
'classifier instance?'.format(method))
optional_methods = ['predict_proba']
for method in optional_methods:
if not hasattr(clf, method):
warnings.warn('{} not in clf. Some plots may '
'not be possible to generate.'.format(method))
additional_methods = {
'plot_learning_curve': plot_learning_curve,
'plot_confusion_matrix': plot_confusion_matrix_with_cv,
'plot_roc_curve': plot_roc_curve_with_cv,
'plot_ks_statistic': plot_ks_statistic_with_cv,
'plot_precision_recall_curve': plot_precision_recall_curve_with_cv,
'plot_feature_importances': plot_feature_importances
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | [
"def",
"classifier_factory",
"(",
"clf",
")",
":",
"required_methods",
"=",
"[",
"'fit'",
",",
"'score'",
",",
"'predict'",
"]",
"for",
"method",
"in",
"required_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"raise",
"TypeErro... | Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the instance methods
necessary for scikit-plot instance methods. | [
"Embeds",
"scikit",
"-",
"plot",
"instance",
"methods",
"in",
"an",
"sklearn",
"classifier",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L24-L67 | train | 224,860 |
reiinakano/scikit-plot | scikitplot/classifiers.py | plot_confusion_matrix_with_cv | def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None,
pred_labels=None, title=None,
normalize=False, hide_zeros=False,
x_tick_rotation=0, do_cv=True, cv=None,
shuffle=True, random_state=None, ax=None,
figsize=None, cmap='Blues',
title_fontsize="large",
text_fontsize="medium"):
"""Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
y = np.array(y)
if not do_cv:
y_pred = clf.predict(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict(X_test)
preds_list.append(preds)
trues_list.append(y_test)
y_pred = np.concatenate(preds_list)
y_true = np.concatenate(trues_list)
ax = plotters.plot_confusion_matrix(y_true=y_true, y_pred=y_pred,
labels=labels, true_labels=true_labels,
pred_labels=pred_labels,
title=title, normalize=normalize,
hide_zeros=hide_zeros,
x_tick_rotation=x_tick_rotation, ax=ax,
figsize=figsize, cmap=cmap,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | python | def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None,
pred_labels=None, title=None,
normalize=False, hide_zeros=False,
x_tick_rotation=0, do_cv=True, cv=None,
shuffle=True, random_state=None, ax=None,
figsize=None, cmap='Blues',
title_fontsize="large",
text_fontsize="medium"):
"""Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
y = np.array(y)
if not do_cv:
y_pred = clf.predict(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict(X_test)
preds_list.append(preds)
trues_list.append(y_test)
y_pred = np.concatenate(preds_list)
y_true = np.concatenate(trues_list)
ax = plotters.plot_confusion_matrix(y_true=y_true, y_pred=y_pred,
labels=labels, true_labels=true_labels,
pred_labels=pred_labels,
title=title, normalize=normalize,
hide_zeros=hide_zeros,
x_tick_rotation=x_tick_rotation, ax=ax,
figsize=figsize, cmap=cmap,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | [
"def",
"plot_confusion_matrix_with_cv",
"(",
"clf",
",",
"X",
",",
"y",
",",
"labels",
"=",
"None",
",",
"true_labels",
"=",
"None",
",",
"pred_labels",
"=",
"None",
",",
"title",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"hide_zeros",
"=",
"Fals... | Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix | [
"Generates",
"the",
"confusion",
"matrix",
"for",
"a",
"given",
"classifier",
"and",
"dataset",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L70-L219 | train | 224,861 |
reiinakano/scikit-plot | scikitplot/classifiers.py | plot_ks_statistic_with_cv | def plot_ks_statistic_with_cv(clf, X, y, title='KS Statistic Plot',
do_cv=True, cv=None, shuffle=True,
random_state=None, ax=None, figsize=None,
title_fontsize="large", text_fontsize="medium"):
"""Generates the KS Statistic plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
title (string, optional): Title of the generated plot. Defaults to
"KS Statistic Plot".
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> lr = classifier_factory(LogisticRegression())
>>> lr.plot_ks_statistic(X, y, random_state=1)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_ks_statistic.png
:align: center
:alt: KS Statistic
"""
y = np.array(y)
if not hasattr(clf, 'predict_proba'):
raise TypeError('"predict_proba" method not in classifier. '
'Cannot calculate ROC Curve.')
if not do_cv:
probas = clf.predict_proba(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict_proba(X_test)
preds_list.append(preds)
trues_list.append(y_test)
probas = np.concatenate(preds_list, axis=0)
y_true = np.concatenate(trues_list)
ax = plotters.plot_ks_statistic(y_true, probas, title=title,
ax=ax, figsize=figsize,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | python | def plot_ks_statistic_with_cv(clf, X, y, title='KS Statistic Plot',
do_cv=True, cv=None, shuffle=True,
random_state=None, ax=None, figsize=None,
title_fontsize="large", text_fontsize="medium"):
"""Generates the KS Statistic plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
title (string, optional): Title of the generated plot. Defaults to
"KS Statistic Plot".
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> lr = classifier_factory(LogisticRegression())
>>> lr.plot_ks_statistic(X, y, random_state=1)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_ks_statistic.png
:align: center
:alt: KS Statistic
"""
y = np.array(y)
if not hasattr(clf, 'predict_proba'):
raise TypeError('"predict_proba" method not in classifier. '
'Cannot calculate ROC Curve.')
if not do_cv:
probas = clf.predict_proba(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict_proba(X_test)
preds_list.append(preds)
trues_list.append(y_test)
probas = np.concatenate(preds_list, axis=0)
y_true = np.concatenate(trues_list)
ax = plotters.plot_ks_statistic(y_true, probas, title=title,
ax=ax, figsize=figsize,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | [
"def",
"plot_ks_statistic_with_cv",
"(",
"clf",
",",
"X",
",",
"y",
",",
"title",
"=",
"'KS Statistic Plot'",
",",
"do_cv",
"=",
"True",
",",
"cv",
"=",
"None",
",",
"shuffle",
"=",
"True",
",",
"random_state",
"=",
"None",
",",
"ax",
"=",
"None",
",",... | Generates the KS Statistic plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
title (string, optional): Title of the generated plot. Defaults to
"KS Statistic Plot".
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> lr = classifier_factory(LogisticRegression())
>>> lr.plot_ks_statistic(X, y, random_state=1)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_ks_statistic.png
:align: center
:alt: KS Statistic | [
"Generates",
"the",
"KS",
"Statistic",
"plot",
"for",
"a",
"given",
"classifier",
"and",
"dataset",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L352-L467 | train | 224,862 |
reiinakano/scikit-plot | scikitplot/plotters.py | plot_confusion_matrix | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
text_fontsize="medium"):
"""Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
cm = confusion_matrix(y_true, y_pred, labels=labels)
if labels is None:
classes = unique_labels(y_true, y_pred)
else:
classes = np.asarray(labels)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = np.around(cm, decimals=2)
cm[np.isnan(cm)] = 0.0
if true_labels is None:
true_classes = classes
else:
validate_labels(classes, true_labels, "true_labels")
true_label_indexes = np.in1d(classes, true_labels)
true_classes = classes[true_label_indexes]
cm = cm[true_label_indexes]
if pred_labels is None:
pred_classes = classes
else:
validate_labels(classes, pred_labels, "pred_labels")
pred_label_indexes = np.in1d(classes, pred_labels)
pred_classes = classes[pred_label_indexes]
cm = cm[:, pred_label_indexes]
if title:
ax.set_title(title, fontsize=title_fontsize)
elif normalize:
ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)
else:
ax.set_title('Confusion Matrix', fontsize=title_fontsize)
image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))
plt.colorbar(mappable=image)
x_tick_marks = np.arange(len(pred_classes))
y_tick_marks = np.arange(len(true_classes))
ax.set_xticks(x_tick_marks)
ax.set_xticklabels(pred_classes, fontsize=text_fontsize,
rotation=x_tick_rotation)
ax.set_yticks(y_tick_marks)
ax.set_yticklabels(true_classes, fontsize=text_fontsize)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if not (hide_zeros and cm[i, j] == 0):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
verticalalignment="center",
fontsize=text_fontsize,
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label', fontsize=text_fontsize)
ax.set_xlabel('Predicted label', fontsize=text_fontsize)
ax.grid('off')
return ax | python | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
text_fontsize="medium"):
"""Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
cm = confusion_matrix(y_true, y_pred, labels=labels)
if labels is None:
classes = unique_labels(y_true, y_pred)
else:
classes = np.asarray(labels)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = np.around(cm, decimals=2)
cm[np.isnan(cm)] = 0.0
if true_labels is None:
true_classes = classes
else:
validate_labels(classes, true_labels, "true_labels")
true_label_indexes = np.in1d(classes, true_labels)
true_classes = classes[true_label_indexes]
cm = cm[true_label_indexes]
if pred_labels is None:
pred_classes = classes
else:
validate_labels(classes, pred_labels, "pred_labels")
pred_label_indexes = np.in1d(classes, pred_labels)
pred_classes = classes[pred_label_indexes]
cm = cm[:, pred_label_indexes]
if title:
ax.set_title(title, fontsize=title_fontsize)
elif normalize:
ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)
else:
ax.set_title('Confusion Matrix', fontsize=title_fontsize)
image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))
plt.colorbar(mappable=image)
x_tick_marks = np.arange(len(pred_classes))
y_tick_marks = np.arange(len(true_classes))
ax.set_xticks(x_tick_marks)
ax.set_xticklabels(pred_classes, fontsize=text_fontsize,
rotation=x_tick_rotation)
ax.set_yticks(y_tick_marks)
ax.set_yticklabels(true_classes, fontsize=text_fontsize)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if not (hide_zeros and cm[i, j] == 0):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
verticalalignment="center",
fontsize=text_fontsize,
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label', fontsize=text_fontsize)
ax.set_xlabel('Predicted label', fontsize=text_fontsize)
ax.grid('off')
return ax | [
"def",
"plot_confusion_matrix",
"(",
"y_true",
",",
"y_pred",
",",
"labels",
"=",
"None",
",",
"true_labels",
"=",
"None",
",",
"pred_labels",
"=",
"None",
",",
"title",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"hide_zeros",
"=",
"False",
",",
"... | Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix | [
"Generates",
"confusion",
"matrix",
"plot",
"from",
"predictions",
"and",
"true",
"labels"
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L42-L181 | train | 224,863 |
reiinakano/scikit-plot | scikitplot/plotters.py | plot_feature_importances | def plot_feature_importances(clf, title='Feature Importance',
feature_names=None, max_num_features=20,
order='descending', x_tick_rotation=0, ax=None,
figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults to
"Feature importances".
feature_names (None, :obj:`list` of string, optional): Determines the
feature names used to plot the feature importances. If None,
feature names will be numbered.
max_num_features (int): Determines the maximum number of features to
plot. Defaults to 20.
order ('ascending', 'descending', or None, optional): Determines the
order in which the feature importances are plotted. Defaults to
'descending'.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf.fit(X, y)
>>> skplt.plot_feature_importances(
... rf, feature_names=['petal length', 'petal width',
... 'sepal length', 'sepal width'])
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_feature_importances.png
:align: center
:alt: Feature Importances
"""
if not hasattr(clf, 'feature_importances_'):
raise TypeError('"feature_importances_" attribute not in classifier. '
'Cannot plot feature importances.')
importances = clf.feature_importances_
if hasattr(clf, 'estimators_')\
and isinstance(clf.estimators_, list)\
and hasattr(clf.estimators_[0], 'feature_importances_'):
std = np.std([tree.feature_importances_ for tree in clf.estimators_],
axis=0)
else:
std = None
if order == 'descending':
indices = np.argsort(importances)[::-1]
elif order == 'ascending':
indices = np.argsort(importances)
elif order is None:
indices = np.array(range(len(importances)))
else:
raise ValueError('Invalid argument {} for "order"'.format(order))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if feature_names is None:
feature_names = indices
else:
feature_names = np.array(feature_names)[indices]
max_num_features = min(max_num_features, len(importances))
ax.set_title(title, fontsize=title_fontsize)
if std is not None:
ax.bar(range(max_num_features),
importances[indices][:max_num_features], color='r',
yerr=std[indices][:max_num_features], align='center')
else:
ax.bar(range(max_num_features),
importances[indices][:max_num_features],
color='r', align='center')
ax.set_xticks(range(max_num_features))
ax.set_xticklabels(feature_names[:max_num_features],
rotation=x_tick_rotation)
ax.set_xlim([-1, max_num_features])
ax.tick_params(labelsize=text_fontsize)
return ax | python | def plot_feature_importances(clf, title='Feature Importance',
feature_names=None, max_num_features=20,
order='descending', x_tick_rotation=0, ax=None,
figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults to
"Feature importances".
feature_names (None, :obj:`list` of string, optional): Determines the
feature names used to plot the feature importances. If None,
feature names will be numbered.
max_num_features (int): Determines the maximum number of features to
plot. Defaults to 20.
order ('ascending', 'descending', or None, optional): Determines the
order in which the feature importances are plotted. Defaults to
'descending'.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf.fit(X, y)
>>> skplt.plot_feature_importances(
... rf, feature_names=['petal length', 'petal width',
... 'sepal length', 'sepal width'])
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_feature_importances.png
:align: center
:alt: Feature Importances
"""
if not hasattr(clf, 'feature_importances_'):
raise TypeError('"feature_importances_" attribute not in classifier. '
'Cannot plot feature importances.')
importances = clf.feature_importances_
if hasattr(clf, 'estimators_')\
and isinstance(clf.estimators_, list)\
and hasattr(clf.estimators_[0], 'feature_importances_'):
std = np.std([tree.feature_importances_ for tree in clf.estimators_],
axis=0)
else:
std = None
if order == 'descending':
indices = np.argsort(importances)[::-1]
elif order == 'ascending':
indices = np.argsort(importances)
elif order is None:
indices = np.array(range(len(importances)))
else:
raise ValueError('Invalid argument {} for "order"'.format(order))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if feature_names is None:
feature_names = indices
else:
feature_names = np.array(feature_names)[indices]
max_num_features = min(max_num_features, len(importances))
ax.set_title(title, fontsize=title_fontsize)
if std is not None:
ax.bar(range(max_num_features),
importances[indices][:max_num_features], color='r',
yerr=std[indices][:max_num_features], align='center')
else:
ax.bar(range(max_num_features),
importances[indices][:max_num_features],
color='r', align='center')
ax.set_xticks(range(max_num_features))
ax.set_xticklabels(feature_names[:max_num_features],
rotation=x_tick_rotation)
ax.set_xlim([-1, max_num_features])
ax.tick_params(labelsize=text_fontsize)
return ax | [
"def",
"plot_feature_importances",
"(",
"clf",
",",
"title",
"=",
"'Feature Importance'",
",",
"feature_names",
"=",
"None",
",",
"max_num_features",
"=",
"20",
",",
"order",
"=",
"'descending'",
",",
"x_tick_rotation",
"=",
"0",
",",
"ax",
"=",
"None",
",",
... | Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults to
"Feature importances".
feature_names (None, :obj:`list` of string, optional): Determines the
feature names used to plot the feature importances. If None,
feature names will be numbered.
max_num_features (int): Determines the maximum number of features to
plot. Defaults to 20.
order ('ascending', 'descending', or None, optional): Determines the
order in which the feature importances are plotted. Defaults to
'descending'.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf.fit(X, y)
>>> skplt.plot_feature_importances(
... rf, feature_names=['petal length', 'petal width',
... 'sepal length', 'sepal width'])
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_feature_importances.png
:align: center
:alt: Feature Importances | [
"Generates",
"a",
"plot",
"of",
"a",
"classifier",
"s",
"feature",
"importances",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L546-L661 | train | 224,864 |
reiinakano/scikit-plot | scikitplot/plotters.py | plot_silhouette | def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean',
copy=True, ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
title (string, optional): Title of the generated plot. Defaults to
"Silhouette Analysis"
metric (string or callable, optional): The metric to use when
calculating distance between instances in a feature array.
If metric is a string, it must be one of the options allowed by
sklearn.metrics.pairwise.pairwise_distances. If X is
the distance array itself, use "precomputed" as the metric.
copy (boolean, optional): Determines whether ``fit`` is used on
**clf** or on a copy of **clf**.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> kmeans = KMeans(n_clusters=4, random_state=1)
>>> skplt.plot_silhouette(kmeans, X)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_silhouette.png
:align: center
:alt: Silhouette Plot
"""
if copy:
clf = clone(clf)
cluster_labels = clf.fit_predict(X)
n_clusters = len(set(cluster_labels))
silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
sample_silhouette_values = silhouette_samples(X, cluster_labels,
metric=metric)
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlim([-0.1, 1])
ax.set_ylim([0, len(X) + (n_clusters + 1) * 10 + 10])
ax.set_xlabel('Silhouette coefficient values', fontsize=text_fontsize)
ax.set_ylabel('Cluster label', fontsize=text_fontsize)
y_lower = 10
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[
cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = plt.cm.get_cmap(cmap)(float(i) / n_clusters)
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i),
fontsize=text_fontsize)
y_lower = y_upper + 10
ax.axvline(x=silhouette_avg, color="red", linestyle="--",
label='Silhouette score: {0:0.3f}'.format(silhouette_avg))
ax.set_yticks([]) # Clear the y-axis labels / ticks
ax.set_xticks(np.arange(-0.1, 1.0, 0.2))
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax | python | def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean',
copy=True, ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
title (string, optional): Title of the generated plot. Defaults to
"Silhouette Analysis"
metric (string or callable, optional): The metric to use when
calculating distance between instances in a feature array.
If metric is a string, it must be one of the options allowed by
sklearn.metrics.pairwise.pairwise_distances. If X is
the distance array itself, use "precomputed" as the metric.
copy (boolean, optional): Determines whether ``fit`` is used on
**clf** or on a copy of **clf**.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> kmeans = KMeans(n_clusters=4, random_state=1)
>>> skplt.plot_silhouette(kmeans, X)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_silhouette.png
:align: center
:alt: Silhouette Plot
"""
if copy:
clf = clone(clf)
cluster_labels = clf.fit_predict(X)
n_clusters = len(set(cluster_labels))
silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
sample_silhouette_values = silhouette_samples(X, cluster_labels,
metric=metric)
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlim([-0.1, 1])
ax.set_ylim([0, len(X) + (n_clusters + 1) * 10 + 10])
ax.set_xlabel('Silhouette coefficient values', fontsize=text_fontsize)
ax.set_ylabel('Cluster label', fontsize=text_fontsize)
y_lower = 10
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[
cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = plt.cm.get_cmap(cmap)(float(i) / n_clusters)
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i),
fontsize=text_fontsize)
y_lower = y_upper + 10
ax.axvline(x=silhouette_avg, color="red", linestyle="--",
label='Silhouette score: {0:0.3f}'.format(silhouette_avg))
ax.set_yticks([]) # Clear the y-axis labels / ticks
ax.set_xticks(np.arange(-0.1, 1.0, 0.2))
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax | [
"def",
"plot_silhouette",
"(",
"clf",
",",
"X",
",",
"title",
"=",
"'Silhouette Analysis'",
",",
"metric",
"=",
"'euclidean'",
",",
"copy",
"=",
"True",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
"=",
"'nipy_spectral'",
",",
"title... | Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
title (string, optional): Title of the generated plot. Defaults to
"Silhouette Analysis"
metric (string or callable, optional): The metric to use when
calculating distance between instances in a feature array.
If metric is a string, it must be one of the options allowed by
sklearn.metrics.pairwise.pairwise_distances. If X is
the distance array itself, use "precomputed" as the metric.
copy (boolean, optional): Determines whether ``fit`` is used on
**clf** or on a copy of **clf**.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> kmeans = KMeans(n_clusters=4, random_state=1)
>>> skplt.plot_silhouette(kmeans, X)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_silhouette.png
:align: center
:alt: Silhouette Plot | [
"Plots",
"silhouette",
"analysis",
"of",
"clusters",
"using",
"fit_predict",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L775-L888 | train | 224,865 |
reiinakano/scikit-plot | scikitplot/cluster.py | _clone_and_score_clusterer | def _clone_and_score_clusterer(clf, X, n_clusters):
"""Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
n_clusters (int): Number of clusters
Returns:
score: Score of clusters
time: Number of seconds it took to fit cluster
"""
start = time.time()
clf = clone(clf)
setattr(clf, 'n_clusters', n_clusters)
return clf.fit(X).score(X), time.time() - start | python | def _clone_and_score_clusterer(clf, X, n_clusters):
"""Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
n_clusters (int): Number of clusters
Returns:
score: Score of clusters
time: Number of seconds it took to fit cluster
"""
start = time.time()
clf = clone(clf)
setattr(clf, 'n_clusters', n_clusters)
return clf.fit(X).score(X), time.time() - start | [
"def",
"_clone_and_score_clusterer",
"(",
"clf",
",",
"X",
",",
"n_clusters",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"clf",
"=",
"clone",
"(",
"clf",
")",
"setattr",
"(",
"clf",
",",
"'n_clusters'",
",",
"n_clusters",
")",
"return",
"cl... | Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
n_clusters (int): Number of clusters
Returns:
score: Score of clusters
time: Number of seconds it took to fit cluster | [
"Clones",
"and",
"scores",
"clusterer",
"instance",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/cluster.py#L110-L132 | train | 224,866 |
reiinakano/scikit-plot | scikitplot/estimators.py | plot_learning_curve | def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification or regression;
None for unsupervised learning.
title (string, optional): Title of the generated plot. Defaults to
"Learning Curve"
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
train_sizes (iterable, optional): Determines the training sizes used to
plot the learning curve. If None, ``np.linspace(.1, 1.0, 5)`` is
used.
n_jobs (int, optional): Number of jobs to run in parallel. Defaults to
1.
scoring (string, callable or None, optional): default: None
A string (see scikit-learn model evaluation documentation) or a
scorerbcallable object / function with signature
scorer(estimator, X, y).
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> skplt.estimators.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if train_sizes is None:
train_sizes = np.linspace(.1, 1.0, 5)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel("Training examples", fontsize=text_fontsize)
ax.set_ylabel("Score", fontsize=text_fontsize)
train_sizes, train_scores, test_scores = learning_curve(
clf, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes,
scoring=scoring, shuffle=shuffle, random_state=random_state)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.grid()
ax.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1, color="r")
ax.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc="best", fontsize=text_fontsize)
return ax | python | def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification or regression;
None for unsupervised learning.
title (string, optional): Title of the generated plot. Defaults to
"Learning Curve"
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
train_sizes (iterable, optional): Determines the training sizes used to
plot the learning curve. If None, ``np.linspace(.1, 1.0, 5)`` is
used.
n_jobs (int, optional): Number of jobs to run in parallel. Defaults to
1.
scoring (string, callable or None, optional): default: None
A string (see scikit-learn model evaluation documentation) or a
scorerbcallable object / function with signature
scorer(estimator, X, y).
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> skplt.estimators.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if train_sizes is None:
train_sizes = np.linspace(.1, 1.0, 5)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel("Training examples", fontsize=text_fontsize)
ax.set_ylabel("Score", fontsize=text_fontsize)
train_sizes, train_scores, test_scores = learning_curve(
clf, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes,
scoring=scoring, shuffle=shuffle, random_state=random_state)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.grid()
ax.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1, color="r")
ax.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc="best", fontsize=text_fontsize)
return ax | [
"def",
"plot_learning_curve",
"(",
"clf",
",",
"X",
",",
"y",
",",
"title",
"=",
"'Learning Curve'",
",",
"cv",
"=",
"None",
",",
"shuffle",
"=",
"False",
",",
"random_state",
"=",
"None",
",",
"train_sizes",
"=",
"None",
",",
"n_jobs",
"=",
"1",
",",
... | Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification or regression;
None for unsupervised learning.
title (string, optional): Title of the generated plot. Defaults to
"Learning Curve"
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
train_sizes (iterable, optional): Determines the training sizes used to
plot the learning curve. If None, ``np.linspace(.1, 1.0, 5)`` is
used.
n_jobs (int, optional): Number of jobs to run in parallel. Defaults to
1.
scoring (string, callable or None, optional): default: None
A string (see scikit-learn model evaluation documentation) or a
scorerbcallable object / function with signature
scorer(estimator, X, y).
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> skplt.estimators.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve | [
"Generates",
"a",
"plot",
"of",
"the",
"train",
"and",
"test",
"learning",
"curves",
"for",
"a",
"classifier",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/estimators.py#L135-L247 | train | 224,867 |
reiinakano/scikit-plot | scikitplot/metrics.py | plot_calibration_curve | def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves
"""
y_true = np.asarray(y_true)
if not isinstance(probas_list, list):
raise ValueError('`probas_list` does not contain a list.')
classes = np.unique(y_true)
if len(classes) > 2:
raise ValueError('plot_calibration_curve only '
'works for binary classification')
if clf_names is None:
clf_names = ['Classifier {}'.format(x+1)
for x in range(len(probas_list))]
if len(clf_names) != len(probas_list):
raise ValueError('Length {} of `clf_names` does not match length {} of'
' `probas_list`'.format(len(clf_names),
len(probas_list)))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
for i, probas in enumerate(probas_list):
probas = np.asarray(probas)
if probas.ndim > 2:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
if probas.ndim == 2:
probas = probas[:, 1]
if probas.shape != y_true.shape:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
probas = (probas - probas.min()) / (probas.max() - probas.min())
fraction_of_positives, mean_predicted_value = \
calibration_curve(y_true, probas, n_bins=n_bins)
color = plt.cm.get_cmap(cmap)(float(i) / len(probas_list))
ax.plot(mean_predicted_value, fraction_of_positives, 's-',
label=clf_names[i], color=color)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel('Mean predicted value', fontsize=text_fontsize)
ax.set_ylabel('Fraction of positives', fontsize=text_fontsize)
ax.set_ylim([-0.05, 1.05])
ax.legend(loc='lower right')
return ax | python | def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves
"""
y_true = np.asarray(y_true)
if not isinstance(probas_list, list):
raise ValueError('`probas_list` does not contain a list.')
classes = np.unique(y_true)
if len(classes) > 2:
raise ValueError('plot_calibration_curve only '
'works for binary classification')
if clf_names is None:
clf_names = ['Classifier {}'.format(x+1)
for x in range(len(probas_list))]
if len(clf_names) != len(probas_list):
raise ValueError('Length {} of `clf_names` does not match length {} of'
' `probas_list`'.format(len(clf_names),
len(probas_list)))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
for i, probas in enumerate(probas_list):
probas = np.asarray(probas)
if probas.ndim > 2:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
if probas.ndim == 2:
probas = probas[:, 1]
if probas.shape != y_true.shape:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
probas = (probas - probas.min()) / (probas.max() - probas.min())
fraction_of_positives, mean_predicted_value = \
calibration_curve(y_true, probas, n_bins=n_bins)
color = plt.cm.get_cmap(cmap)(float(i) / len(probas_list))
ax.plot(mean_predicted_value, fraction_of_positives, 's-',
label=clf_names[i], color=color)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel('Mean predicted value', fontsize=text_fontsize)
ax.set_ylabel('Fraction of positives', fontsize=text_fontsize)
ax.set_ylim([-0.05, 1.05])
ax.legend(loc='lower right')
return ax | [
"def",
"plot_calibration_curve",
"(",
"y_true",
",",
"probas_list",
",",
"clf_names",
"=",
"None",
",",
"n_bins",
"=",
"10",
",",
"title",
"=",
"'Calibration plots (Reliability Curves)'",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
"=",
... | Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves | [
"Plots",
"calibration",
"curves",
"for",
"a",
"set",
"of",
"classifier",
"probability",
"estimates",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/metrics.py#L911-L1042 | train | 224,868 |
reiinakano/scikit-plot | scikitplot/clustering.py | clustering_factory | def clustering_factory(clf):
"""Embeds scikit-plot plotting methods in an sklearn clusterer instance.
Args:
clf: Scikit-learn clusterer instance
Returns:
The same scikit-learn clusterer instance passed in **clf** with
embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the instance methods necessary
for scikit-plot instance methods.
"""
required_methods = ['fit', 'fit_predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you '
'pass a clusterer instance?'.format(method))
additional_methods = {
'plot_silhouette': plot_silhouette,
'plot_elbow_curve': plot_elbow_curve
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | python | def clustering_factory(clf):
"""Embeds scikit-plot plotting methods in an sklearn clusterer instance.
Args:
clf: Scikit-learn clusterer instance
Returns:
The same scikit-learn clusterer instance passed in **clf** with
embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the instance methods necessary
for scikit-plot instance methods.
"""
required_methods = ['fit', 'fit_predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you '
'pass a clusterer instance?'.format(method))
additional_methods = {
'plot_silhouette': plot_silhouette,
'plot_elbow_curve': plot_elbow_curve
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | [
"def",
"clustering_factory",
"(",
"clf",
")",
":",
"required_methods",
"=",
"[",
"'fit'",
",",
"'fit_predict'",
"]",
"for",
"method",
"in",
"required_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"raise",
"TypeError",
"(",
"'\... | Embeds scikit-plot plotting methods in an sklearn clusterer instance.
Args:
clf: Scikit-learn clusterer instance
Returns:
The same scikit-learn clusterer instance passed in **clf** with
embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the instance methods necessary
for scikit-plot instance methods. | [
"Embeds",
"scikit",
"-",
"plot",
"plotting",
"methods",
"in",
"an",
"sklearn",
"clusterer",
"instance",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/clustering.py#L18-L50 | train | 224,869 |
reiinakano/scikit-plot | scikitplot/helpers.py | validate_labels | def validate_labels(known_classes, passed_labels, argument_name):
"""Validates the labels passed into the true_labels or pred_labels
arguments in the plot_confusion_matrix function.
Raises a ValueError exception if any of the passed labels are not in the
set of known classes or if there are duplicate labels. Otherwise returns
None.
Args:
known_classes (array-like):
The classes that are known to appear in the data.
passed_labels (array-like):
The labels that were passed in through the argument.
argument_name (str):
The name of the argument being validated.
Example:
>>> known_classes = ["A", "B", "C"]
>>> passed_labels = ["A", "B"]
>>> validate_labels(known_classes, passed_labels, "true_labels")
"""
known_classes = np.array(known_classes)
passed_labels = np.array(passed_labels)
unique_labels, unique_indexes = np.unique(passed_labels, return_index=True)
if len(passed_labels) != len(unique_labels):
indexes = np.arange(0, len(passed_labels))
duplicate_indexes = indexes[~np.in1d(indexes, unique_indexes)]
duplicate_labels = [str(x) for x in passed_labels[duplicate_indexes]]
msg = "The following duplicate labels were passed into {0}: {1}" \
.format(argument_name, ", ".join(duplicate_labels))
raise ValueError(msg)
passed_labels_absent = ~np.in1d(passed_labels, known_classes)
if np.any(passed_labels_absent):
absent_labels = [str(x) for x in passed_labels[passed_labels_absent]]
msg = ("The following labels "
"were passed into {0}, "
"but were not found in "
"labels: {1}").format(argument_name, ", ".join(absent_labels))
raise ValueError(msg)
return | python | def validate_labels(known_classes, passed_labels, argument_name):
"""Validates the labels passed into the true_labels or pred_labels
arguments in the plot_confusion_matrix function.
Raises a ValueError exception if any of the passed labels are not in the
set of known classes or if there are duplicate labels. Otherwise returns
None.
Args:
known_classes (array-like):
The classes that are known to appear in the data.
passed_labels (array-like):
The labels that were passed in through the argument.
argument_name (str):
The name of the argument being validated.
Example:
>>> known_classes = ["A", "B", "C"]
>>> passed_labels = ["A", "B"]
>>> validate_labels(known_classes, passed_labels, "true_labels")
"""
known_classes = np.array(known_classes)
passed_labels = np.array(passed_labels)
unique_labels, unique_indexes = np.unique(passed_labels, return_index=True)
if len(passed_labels) != len(unique_labels):
indexes = np.arange(0, len(passed_labels))
duplicate_indexes = indexes[~np.in1d(indexes, unique_indexes)]
duplicate_labels = [str(x) for x in passed_labels[duplicate_indexes]]
msg = "The following duplicate labels were passed into {0}: {1}" \
.format(argument_name, ", ".join(duplicate_labels))
raise ValueError(msg)
passed_labels_absent = ~np.in1d(passed_labels, known_classes)
if np.any(passed_labels_absent):
absent_labels = [str(x) for x in passed_labels[passed_labels_absent]]
msg = ("The following labels "
"were passed into {0}, "
"but were not found in "
"labels: {1}").format(argument_name, ", ".join(absent_labels))
raise ValueError(msg)
return | [
"def",
"validate_labels",
"(",
"known_classes",
",",
"passed_labels",
",",
"argument_name",
")",
":",
"known_classes",
"=",
"np",
".",
"array",
"(",
"known_classes",
")",
"passed_labels",
"=",
"np",
".",
"array",
"(",
"passed_labels",
")",
"unique_labels",
",",
... | Validates the labels passed into the true_labels or pred_labels
arguments in the plot_confusion_matrix function.
Raises a ValueError exception if any of the passed labels are not in the
set of known classes or if there are duplicate labels. Otherwise returns
None.
Args:
known_classes (array-like):
The classes that are known to appear in the data.
passed_labels (array-like):
The labels that were passed in through the argument.
argument_name (str):
The name of the argument being validated.
Example:
>>> known_classes = ["A", "B", "C"]
>>> passed_labels = ["A", "B"]
>>> validate_labels(known_classes, passed_labels, "true_labels") | [
"Validates",
"the",
"labels",
"passed",
"into",
"the",
"true_labels",
"or",
"pred_labels",
"arguments",
"in",
"the",
"plot_confusion_matrix",
"function",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L108-L154 | train | 224,870 |
reiinakano/scikit-plot | scikitplot/helpers.py | cumulative_gain_curve | def cumulative_gain_curve(y_true, y_score, pos_label=None):
"""This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary classification task.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_score (array-like, shape (n_samples)): Target scores, can either be
probability estimates of the positive class, confidence values, or
non-thresholded measure of decisions (as returned by
decision_function on some classifiers).
pos_label (int or str, default=None): Label considered as positive and
others are considered negative
Returns:
percentages (numpy.ndarray): An array containing the X-axis values for
plotting the Cumulative Gains chart.
gains (numpy.ndarray): An array containing the Y-axis values for one
curve of the Cumulative Gains chart.
Raises:
ValueError: If `y_true` is not composed of 2 classes. The Cumulative
Gain Chart is only relevant in binary classification.
"""
y_true, y_score = np.asarray(y_true), np.asarray(y_score)
# ensure binary classification if pos_label is not specified
classes = np.unique(y_true)
if (pos_label is None and
not (np.array_equal(classes, [0, 1]) or
np.array_equal(classes, [-1, 1]) or
np.array_equal(classes, [0]) or
np.array_equal(classes, [-1]) or
np.array_equal(classes, [1]))):
raise ValueError("Data is not binary and pos_label is not specified")
elif pos_label is None:
pos_label = 1.
# make y_true a boolean vector
y_true = (y_true == pos_label)
sorted_indices = np.argsort(y_score)[::-1]
y_true = y_true[sorted_indices]
gains = np.cumsum(y_true)
percentages = np.arange(start=1, stop=len(y_true) + 1)
gains = gains / float(np.sum(y_true))
percentages = percentages / float(len(y_true))
gains = np.insert(gains, 0, [0])
percentages = np.insert(percentages, 0, [0])
return percentages, gains | python | def cumulative_gain_curve(y_true, y_score, pos_label=None):
"""This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary classification task.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_score (array-like, shape (n_samples)): Target scores, can either be
probability estimates of the positive class, confidence values, or
non-thresholded measure of decisions (as returned by
decision_function on some classifiers).
pos_label (int or str, default=None): Label considered as positive and
others are considered negative
Returns:
percentages (numpy.ndarray): An array containing the X-axis values for
plotting the Cumulative Gains chart.
gains (numpy.ndarray): An array containing the Y-axis values for one
curve of the Cumulative Gains chart.
Raises:
ValueError: If `y_true` is not composed of 2 classes. The Cumulative
Gain Chart is only relevant in binary classification.
"""
y_true, y_score = np.asarray(y_true), np.asarray(y_score)
# ensure binary classification if pos_label is not specified
classes = np.unique(y_true)
if (pos_label is None and
not (np.array_equal(classes, [0, 1]) or
np.array_equal(classes, [-1, 1]) or
np.array_equal(classes, [0]) or
np.array_equal(classes, [-1]) or
np.array_equal(classes, [1]))):
raise ValueError("Data is not binary and pos_label is not specified")
elif pos_label is None:
pos_label = 1.
# make y_true a boolean vector
y_true = (y_true == pos_label)
sorted_indices = np.argsort(y_score)[::-1]
y_true = y_true[sorted_indices]
gains = np.cumsum(y_true)
percentages = np.arange(start=1, stop=len(y_true) + 1)
gains = gains / float(np.sum(y_true))
percentages = percentages / float(len(y_true))
gains = np.insert(gains, 0, [0])
percentages = np.insert(percentages, 0, [0])
return percentages, gains | [
"def",
"cumulative_gain_curve",
"(",
"y_true",
",",
"y_score",
",",
"pos_label",
"=",
"None",
")",
":",
"y_true",
",",
"y_score",
"=",
"np",
".",
"asarray",
"(",
"y_true",
")",
",",
"np",
".",
"asarray",
"(",
"y_score",
")",
"# ensure binary classification i... | This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary classification task.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_score (array-like, shape (n_samples)): Target scores, can either be
probability estimates of the positive class, confidence values, or
non-thresholded measure of decisions (as returned by
decision_function on some classifiers).
pos_label (int or str, default=None): Label considered as positive and
others are considered negative
Returns:
percentages (numpy.ndarray): An array containing the X-axis values for
plotting the Cumulative Gains chart.
gains (numpy.ndarray): An array containing the Y-axis values for one
curve of the Cumulative Gains chart.
Raises:
ValueError: If `y_true` is not composed of 2 classes. The Cumulative
Gain Chart is only relevant in binary classification. | [
"This",
"function",
"generates",
"the",
"points",
"necessary",
"to",
"plot",
"the",
"Cumulative",
"Gain"
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L157-L213 | train | 224,871 |
allure-framework/allure-python | allure-python-commons/src/utils.py | getargspec | def getargspec(func):
"""
Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
Like inspect.getargspec but supports functools.partial as well.
"""
# noqa: E731 type: (Any) -> Any
if inspect.ismethod(func):
func = func.__func__
parts = 0, () # noqa: E731 type: Tuple[int, Tuple[unicode, ...]]
if type(func) is partial:
keywords = func.keywords
if keywords is None:
keywords = {}
parts = len(func.args), keywords.keys()
func = func.func
if not inspect.isfunction(func):
raise TypeError('%r is not a Python function' % func)
args, varargs, varkw = inspect.getargs(func.__code__)
func_defaults = func.__defaults__
if func_defaults is None:
func_defaults = []
else:
func_defaults = list(func_defaults)
if parts[0]:
args = args[parts[0]:]
if parts[1]:
for arg in parts[1]:
i = args.index(arg) - len(args) # type: ignore
del args[i]
try:
del func_defaults[i]
except IndexError:
pass
return inspect.ArgSpec(args, varargs, varkw, func_defaults) | python | def getargspec(func):
"""
Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
Like inspect.getargspec but supports functools.partial as well.
"""
# noqa: E731 type: (Any) -> Any
if inspect.ismethod(func):
func = func.__func__
parts = 0, () # noqa: E731 type: Tuple[int, Tuple[unicode, ...]]
if type(func) is partial:
keywords = func.keywords
if keywords is None:
keywords = {}
parts = len(func.args), keywords.keys()
func = func.func
if not inspect.isfunction(func):
raise TypeError('%r is not a Python function' % func)
args, varargs, varkw = inspect.getargs(func.__code__)
func_defaults = func.__defaults__
if func_defaults is None:
func_defaults = []
else:
func_defaults = list(func_defaults)
if parts[0]:
args = args[parts[0]:]
if parts[1]:
for arg in parts[1]:
i = args.index(arg) - len(args) # type: ignore
del args[i]
try:
del func_defaults[i]
except IndexError:
pass
return inspect.ArgSpec(args, varargs, varkw, func_defaults) | [
"def",
"getargspec",
"(",
"func",
")",
":",
"# noqa: E731 type: (Any) -> Any",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"parts",
"=",
"0",
",",
"(",
")",
"# noqa: E731 type: Tuple[int, Tuple[unicode, ...]]",
... | Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
Like inspect.getargspec but supports functools.partial as well. | [
"Used",
"because",
"getargspec",
"for",
"python",
"2",
".",
"7",
"does",
"not",
"accept",
"functools",
".",
"partial",
"which",
"is",
"the",
"type",
"for",
"pytest",
"fixtures",
"."
] | 070fdcc093e8743cc5e58f5f108b21f12ec8ddaf | https://github.com/allure-framework/allure-python/blob/070fdcc093e8743cc5e58f5f108b21f12ec8ddaf/allure-python-commons/src/utils.py#L18-L61 | train | 224,872 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.querystring | def querystring(self):
"""Return original querystring but containing only managed keys
:return dict: dict of managed querystring parameter
"""
return {key: value for (key, value) in self.qs.items()
if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')} | python | def querystring(self):
"""Return original querystring but containing only managed keys
:return dict: dict of managed querystring parameter
"""
return {key: value for (key, value) in self.qs.items()
if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')} | [
"def",
"querystring",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"qs",
".",
"items",
"(",
")",
"if",
"key",
".",
"startswith",
"(",
"self",
".",
"MANAGED_KEYS",
")",
"or",
"... | Return original querystring but containing only managed keys
:return dict: dict of managed querystring parameter | [
"Return",
"original",
"querystring",
"but",
"containing",
"only",
"managed",
"keys"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L68-L74 | train | 224,873 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.filters | def filters(self):
"""Return filters from query string.
:return list: filter information
"""
results = []
filters = self.qs.get('filter')
if filters is not None:
try:
results.extend(json.loads(filters))
except (ValueError, TypeError):
raise InvalidFilters("Parse error")
if self._get_key_values('filter['):
results.extend(self._simple_filters(self._get_key_values('filter[')))
return results | python | def filters(self):
"""Return filters from query string.
:return list: filter information
"""
results = []
filters = self.qs.get('filter')
if filters is not None:
try:
results.extend(json.loads(filters))
except (ValueError, TypeError):
raise InvalidFilters("Parse error")
if self._get_key_values('filter['):
results.extend(self._simple_filters(self._get_key_values('filter[')))
return results | [
"def",
"filters",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"filters",
"=",
"self",
".",
"qs",
".",
"get",
"(",
"'filter'",
")",
"if",
"filters",
"is",
"not",
"None",
":",
"try",
":",
"results",
".",
"extend",
"(",
"json",
".",
"loads",
"(... | Return filters from query string.
:return list: filter information | [
"Return",
"filters",
"from",
"query",
"string",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L77-L91 | train | 224,874 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.pagination | def pagination(self):
"""Return all page parameters as a dict.
:return dict: a dict of pagination information
To allow multiples strategies, all parameters starting with `page` will be included. e.g::
{
"number": '25',
"size": '150',
}
Example with number strategy::
>>> query_string = {'page[number]': '25', 'page[size]': '10'}
>>> parsed_query.pagination
{'number': '25', 'size': '10'}
"""
# check values type
result = self._get_key_values('page')
for key, value in result.items():
if key not in ('number', 'size'):
raise BadRequest("{} is not a valid parameter of pagination".format(key), source={'parameter': 'page'})
try:
int(value)
except ValueError:
raise BadRequest("Parse error", source={'parameter': 'page[{}]'.format(key)})
if current_app.config.get('ALLOW_DISABLE_PAGINATION', True) is False and int(result.get('size', 1)) == 0:
raise BadRequest("You are not allowed to disable pagination", source={'parameter': 'page[size]'})
if current_app.config.get('MAX_PAGE_SIZE') is not None and 'size' in result:
if int(result['size']) > current_app.config['MAX_PAGE_SIZE']:
raise BadRequest("Maximum page size is {}".format(current_app.config['MAX_PAGE_SIZE']),
source={'parameter': 'page[size]'})
return result | python | def pagination(self):
"""Return all page parameters as a dict.
:return dict: a dict of pagination information
To allow multiples strategies, all parameters starting with `page` will be included. e.g::
{
"number": '25',
"size": '150',
}
Example with number strategy::
>>> query_string = {'page[number]': '25', 'page[size]': '10'}
>>> parsed_query.pagination
{'number': '25', 'size': '10'}
"""
# check values type
result = self._get_key_values('page')
for key, value in result.items():
if key not in ('number', 'size'):
raise BadRequest("{} is not a valid parameter of pagination".format(key), source={'parameter': 'page'})
try:
int(value)
except ValueError:
raise BadRequest("Parse error", source={'parameter': 'page[{}]'.format(key)})
if current_app.config.get('ALLOW_DISABLE_PAGINATION', True) is False and int(result.get('size', 1)) == 0:
raise BadRequest("You are not allowed to disable pagination", source={'parameter': 'page[size]'})
if current_app.config.get('MAX_PAGE_SIZE') is not None and 'size' in result:
if int(result['size']) > current_app.config['MAX_PAGE_SIZE']:
raise BadRequest("Maximum page size is {}".format(current_app.config['MAX_PAGE_SIZE']),
source={'parameter': 'page[size]'})
return result | [
"def",
"pagination",
"(",
"self",
")",
":",
"# check values type",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'page'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'number'",
",... | Return all page parameters as a dict.
:return dict: a dict of pagination information
To allow multiples strategies, all parameters starting with `page` will be included. e.g::
{
"number": '25',
"size": '150',
}
Example with number strategy::
>>> query_string = {'page[number]': '25', 'page[size]': '10'}
>>> parsed_query.pagination
{'number': '25', 'size': '10'} | [
"Return",
"all",
"page",
"parameters",
"as",
"a",
"dict",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L94-L130 | train | 224,875 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.fields | def fields(self):
"""Return fields wanted by client.
:return dict: a dict of sparse fieldsets information
Return value will be a dict containing all fields by resource, for example::
{
"user": ['name', 'email'],
}
"""
result = self._get_key_values('fields')
for key, value in result.items():
if not isinstance(value, list):
result[key] = [value]
for key, value in result.items():
schema = get_schema_from_type(key)
for obj in value:
if obj not in schema._declared_fields:
raise InvalidField("{} has no attribute {}".format(schema.__name__, obj))
return result | python | def fields(self):
"""Return fields wanted by client.
:return dict: a dict of sparse fieldsets information
Return value will be a dict containing all fields by resource, for example::
{
"user": ['name', 'email'],
}
"""
result = self._get_key_values('fields')
for key, value in result.items():
if not isinstance(value, list):
result[key] = [value]
for key, value in result.items():
schema = get_schema_from_type(key)
for obj in value:
if obj not in schema._declared_fields:
raise InvalidField("{} has no attribute {}".format(schema.__name__, obj))
return result | [
"def",
"fields",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'fields'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"r... | Return fields wanted by client.
:return dict: a dict of sparse fieldsets information
Return value will be a dict containing all fields by resource, for example::
{
"user": ['name', 'email'],
} | [
"Return",
"fields",
"wanted",
"by",
"client",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L133-L156 | train | 224,876 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.sorting | def sorting(self):
"""Return fields to sort by including sort name for SQLAlchemy and row
sort parameter for other ORMs
:return list: a list of sorting information
Example of return value::
[
{'field': 'created_at', 'order': 'desc'},
]
"""
if self.qs.get('sort'):
sorting_results = []
for sort_field in self.qs['sort'].split(','):
field = sort_field.replace('-', '')
if field not in self.schema._declared_fields:
raise InvalidSort("{} has no attribute {}".format(self.schema.__name__, field))
if field in get_relationships(self.schema):
raise InvalidSort("You can't sort on {} because it is a relationship field".format(field))
field = get_model_field(self.schema, field)
order = 'desc' if sort_field.startswith('-') else 'asc'
sorting_results.append({'field': field, 'order': order})
return sorting_results
return [] | python | def sorting(self):
"""Return fields to sort by including sort name for SQLAlchemy and row
sort parameter for other ORMs
:return list: a list of sorting information
Example of return value::
[
{'field': 'created_at', 'order': 'desc'},
]
"""
if self.qs.get('sort'):
sorting_results = []
for sort_field in self.qs['sort'].split(','):
field = sort_field.replace('-', '')
if field not in self.schema._declared_fields:
raise InvalidSort("{} has no attribute {}".format(self.schema.__name__, field))
if field in get_relationships(self.schema):
raise InvalidSort("You can't sort on {} because it is a relationship field".format(field))
field = get_model_field(self.schema, field)
order = 'desc' if sort_field.startswith('-') else 'asc'
sorting_results.append({'field': field, 'order': order})
return sorting_results
return [] | [
"def",
"sorting",
"(",
"self",
")",
":",
"if",
"self",
".",
"qs",
".",
"get",
"(",
"'sort'",
")",
":",
"sorting_results",
"=",
"[",
"]",
"for",
"sort_field",
"in",
"self",
".",
"qs",
"[",
"'sort'",
"]",
".",
"split",
"(",
"','",
")",
":",
"field"... | Return fields to sort by including sort name for SQLAlchemy and row
sort parameter for other ORMs
:return list: a list of sorting information
Example of return value::
[
{'field': 'created_at', 'order': 'desc'},
] | [
"Return",
"fields",
"to",
"sort",
"by",
"including",
"sort",
"name",
"for",
"SQLAlchemy",
"and",
"row",
"sort",
"parameter",
"for",
"other",
"ORMs"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L159-L185 | train | 224,877 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.include | def include(self):
"""Return fields to include
:return list: a list of include information
"""
include_param = self.qs.get('include', [])
if current_app.config.get('MAX_INCLUDE_DEPTH') is not None:
for include_path in include_param:
if len(include_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:
raise InvalidInclude("You can't use include through more than {} relationships"
.format(current_app.config['MAX_INCLUDE_DEPTH']))
return include_param.split(',') if include_param else [] | python | def include(self):
"""Return fields to include
:return list: a list of include information
"""
include_param = self.qs.get('include', [])
if current_app.config.get('MAX_INCLUDE_DEPTH') is not None:
for include_path in include_param:
if len(include_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:
raise InvalidInclude("You can't use include through more than {} relationships"
.format(current_app.config['MAX_INCLUDE_DEPTH']))
return include_param.split(',') if include_param else [] | [
"def",
"include",
"(",
"self",
")",
":",
"include_param",
"=",
"self",
".",
"qs",
".",
"get",
"(",
"'include'",
",",
"[",
"]",
")",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'MAX_INCLUDE_DEPTH'",
")",
"is",
"not",
"None",
":",
"for",
"inc... | Return fields to include
:return list: a list of include information | [
"Return",
"fields",
"to",
"include"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L188-L201 | train | 224,878 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/exceptions.py | JsonApiException.to_dict | def to_dict(self):
"""Return values of each fields of an jsonapi error"""
error_dict = {}
for field in ('status', 'source', 'title', 'detail', 'id', 'code', 'links', 'meta'):
if getattr(self, field, None):
error_dict.update({field: getattr(self, field)})
return error_dict | python | def to_dict(self):
"""Return values of each fields of an jsonapi error"""
error_dict = {}
for field in ('status', 'source', 'title', 'detail', 'id', 'code', 'links', 'meta'):
if getattr(self, field, None):
error_dict.update({field: getattr(self, field)})
return error_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"error_dict",
"=",
"{",
"}",
"for",
"field",
"in",
"(",
"'status'",
",",
"'source'",
",",
"'title'",
",",
"'detail'",
",",
"'id'",
",",
"'code'",
",",
"'links'",
",",
"'meta'",
")",
":",
"if",
"getattr",
"(",
... | Return values of each fields of an jsonapi error | [
"Return",
"values",
"of",
"each",
"fields",
"of",
"an",
"jsonapi",
"error"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/exceptions.py#L30-L37 | train | 224,879 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | Resource.dispatch_request | def dispatch_request(self, *args, **kwargs):
"""Logic of how to handle a request"""
method = getattr(self, request.method.lower(), None)
if method is None and request.method == 'HEAD':
method = getattr(self, 'get', None)
assert method is not None, 'Unimplemented method {}'.format(request.method)
headers = {'Content-Type': 'application/vnd.api+json'}
response = method(*args, **kwargs)
if isinstance(response, Response):
response.headers.add('Content-Type', 'application/vnd.api+json')
return response
if not isinstance(response, tuple):
if isinstance(response, dict):
response.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)
try:
data, status_code, headers = response
headers.update({'Content-Type': 'application/vnd.api+json'})
except ValueError:
pass
try:
data, status_code = response
except ValueError:
pass
if isinstance(data, dict):
data.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(data, cls=JSONEncoder), status_code, headers) | python | def dispatch_request(self, *args, **kwargs):
"""Logic of how to handle a request"""
method = getattr(self, request.method.lower(), None)
if method is None and request.method == 'HEAD':
method = getattr(self, 'get', None)
assert method is not None, 'Unimplemented method {}'.format(request.method)
headers = {'Content-Type': 'application/vnd.api+json'}
response = method(*args, **kwargs)
if isinstance(response, Response):
response.headers.add('Content-Type', 'application/vnd.api+json')
return response
if not isinstance(response, tuple):
if isinstance(response, dict):
response.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)
try:
data, status_code, headers = response
headers.update({'Content-Type': 'application/vnd.api+json'})
except ValueError:
pass
try:
data, status_code = response
except ValueError:
pass
if isinstance(data, dict):
data.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(data, cls=JSONEncoder), status_code, headers) | [
"def",
"dispatch_request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"request",
".",
"method",
".",
"lower",
"(",
")",
",",
"None",
")",
"if",
"method",
"is",
"None",
"and",
"reque... | Logic of how to handle a request | [
"Logic",
"of",
"how",
"to",
"handle",
"a",
"request"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L62-L96 | train | 224,880 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceList.get | def get(self, *args, **kwargs):
"""Retrieve a collection of objects"""
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
objects_count, objects = self.get_collection(qs, kwargs)
schema_kwargs = getattr(self, 'get_schema_kwargs', dict())
schema_kwargs.update({'many': True})
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
result = schema.dump(objects).data
view_kwargs = request.view_args if getattr(self, 'view_kwargs', None) is True else dict()
add_pagination_links(result,
objects_count,
qs,
url_for(self.view, _external=True, **view_kwargs))
result.update({'meta': {'count': objects_count}})
final_result = self.after_get(result)
return final_result | python | def get(self, *args, **kwargs):
"""Retrieve a collection of objects"""
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
objects_count, objects = self.get_collection(qs, kwargs)
schema_kwargs = getattr(self, 'get_schema_kwargs', dict())
schema_kwargs.update({'many': True})
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
result = schema.dump(objects).data
view_kwargs = request.view_args if getattr(self, 'view_kwargs', None) is True else dict()
add_pagination_links(result,
objects_count,
qs,
url_for(self.view, _external=True, **view_kwargs))
result.update({'meta': {'count': objects_count}})
final_result = self.after_get(result)
return final_result | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_get",
"(",
"args",
",",
"kwargs",
")",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"objects_count",
",",
... | Retrieve a collection of objects | [
"Retrieve",
"a",
"collection",
"of",
"objects"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L103-L133 | train | 224,881 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceList.post | def post(self, *args, **kwargs):
"""Create an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema = compute_schema(self.schema,
getattr(self, 'post_schema_kwargs', dict()),
qs,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
self.before_post(args, kwargs, data=data)
obj = self.create_object(data, kwargs)
result = schema.dump(obj).data
if result['data'].get('links', {}).get('self'):
final_result = (result, 201, {'Location': result['data']['links']['self']})
else:
final_result = (result, 201)
result = self.after_post(final_result)
return result | python | def post(self, *args, **kwargs):
"""Create an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema = compute_schema(self.schema,
getattr(self, 'post_schema_kwargs', dict()),
qs,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
self.before_post(args, kwargs, data=data)
obj = self.create_object(data, kwargs)
result = schema.dump(obj).data
if result['data'].get('links', {}).get('self'):
final_result = (result, 201, {'Location': result['data']['links']['self']})
else:
final_result = (result, 201)
result = self.after_post(final_result)
return result | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"schema... | Create an object | [
"Create",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L136-L181 | train | 224,882 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.get | def get(self, *args, **kwargs):
"""Get object details"""
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
obj = self.get_object(kwargs, qs)
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
getattr(self, 'get_schema_kwargs', dict()),
qs,
qs.include)
result = schema.dump(obj).data
final_result = self.after_get(result)
return final_result | python | def get(self, *args, **kwargs):
"""Get object details"""
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
obj = self.get_object(kwargs, qs)
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
getattr(self, 'get_schema_kwargs', dict()),
qs,
qs.include)
result = schema.dump(obj).data
final_result = self.after_get(result)
return final_result | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_get",
"(",
"args",
",",
"kwargs",
")",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"obj",
"=",
"self",
... | Get object details | [
"Get",
"object",
"details"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L213-L232 | train | 224,883 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.patch | def patch(self, *args, **kwargs):
"""Update an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema_kwargs = getattr(self, 'patch_schema_kwargs', dict())
schema_kwargs.update({'partial': True})
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node',
source={'pointer': '/data/id'})
if (str(json_data['data']['id']) != str(kwargs[getattr(self._data_layer, 'url_field', 'id')])):
raise BadRequest('Value of id does not match the resource identifier in url',
source={'pointer': '/data/id'})
self.before_patch(args, kwargs, data=data)
obj = self.update_object(data, qs, kwargs)
result = schema.dump(obj).data
final_result = self.after_patch(result)
return final_result | python | def patch(self, *args, **kwargs):
"""Update an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema_kwargs = getattr(self, 'patch_schema_kwargs', dict())
schema_kwargs.update({'partial': True})
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node',
source={'pointer': '/data/id'})
if (str(json_data['data']['id']) != str(kwargs[getattr(self._data_layer, 'url_field', 'id')])):
raise BadRequest('Value of id does not match the resource identifier in url',
source={'pointer': '/data/id'})
self.before_patch(args, kwargs, data=data)
obj = self.update_object(data, qs, kwargs)
result = schema.dump(obj).data
final_result = self.after_patch(result)
return final_result | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"schem... | Update an object | [
"Update",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L235-L286 | train | 224,884 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.delete | def delete(self, *args, **kwargs):
"""Delete an object"""
self.before_delete(args, kwargs)
self.delete_object(kwargs)
result = {'meta': {'message': 'Object successfully deleted'}}
final_result = self.after_delete(result)
return final_result | python | def delete(self, *args, **kwargs):
"""Delete an object"""
self.before_delete(args, kwargs)
self.delete_object(kwargs)
result = {'meta': {'message': 'Object successfully deleted'}}
final_result = self.after_delete(result)
return final_result | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_delete",
"(",
"args",
",",
"kwargs",
")",
"self",
".",
"delete_object",
"(",
"kwargs",
")",
"result",
"=",
"{",
"'meta'",
":",
"{",
"'message'",
... | Delete an object | [
"Delete",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L289-L299 | train | 224,885 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship.get | def get(self, *args, **kwargs):
"""Get a relationship details"""
self.before_get(args, kwargs)
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
obj, data = self._data_layer.get_relationship(model_relationship_field,
related_type_,
related_id_field,
kwargs)
result = {'links': {'self': request.path,
'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
'data': data}
qs = QSManager(request.args, self.schema)
if qs.include:
schema = compute_schema(self.schema, dict(), qs, qs.include)
serialized_obj = schema.dump(obj)
result['included'] = serialized_obj.data.get('included', dict())
final_result = self.after_get(result)
return final_result | python | def get(self, *args, **kwargs):
"""Get a relationship details"""
self.before_get(args, kwargs)
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
obj, data = self._data_layer.get_relationship(model_relationship_field,
related_type_,
related_id_field,
kwargs)
result = {'links': {'self': request.path,
'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
'data': data}
qs = QSManager(request.args, self.schema)
if qs.include:
schema = compute_schema(self.schema, dict(), qs, qs.include)
serialized_obj = schema.dump(obj)
result['included'] = serialized_obj.data.get('included', dict())
final_result = self.after_get(result)
return final_result | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_get",
"(",
"args",
",",
"kwargs",
")",
"relationship_field",
",",
"model_relationship_field",
",",
"related_type_",
",",
"related_id_field",
"=",
"self",
"... | Get a relationship details | [
"Get",
"a",
"relationship",
"details"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L346-L370 | train | 224,886 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship.patch | def patch(self, *args, **kwargs):
"""Update a relationship"""
json_data = request.get_json() or {}
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
if 'data' not in json_data:
raise BadRequest('You must provide data with a "data" route node', source={'pointer': '/data'})
if isinstance(json_data['data'], dict):
if 'type' not in json_data['data']:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if json_data['data']['type'] != related_type_:
raise InvalidType('The type field does not match the resource type', source={'pointer': '/data/type'})
if isinstance(json_data['data'], list):
for obj in json_data['data']:
if 'type' not in obj:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in obj:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if obj['type'] != related_type_:
raise InvalidType('The type provided does not match the resource type',
source={'pointer': '/data/type'})
self.before_patch(args, kwargs, json_data=json_data)
obj_, updated = self._data_layer.update_relationship(json_data,
model_relationship_field,
related_id_field,
kwargs)
status_code = 200
result = {'meta': {'message': 'Relationship successfully updated'}}
if updated is False:
result = ''
status_code = 204
final_result = self.after_patch(result, status_code)
return final_result | python | def patch(self, *args, **kwargs):
"""Update a relationship"""
json_data = request.get_json() or {}
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
if 'data' not in json_data:
raise BadRequest('You must provide data with a "data" route node', source={'pointer': '/data'})
if isinstance(json_data['data'], dict):
if 'type' not in json_data['data']:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if json_data['data']['type'] != related_type_:
raise InvalidType('The type field does not match the resource type', source={'pointer': '/data/type'})
if isinstance(json_data['data'], list):
for obj in json_data['data']:
if 'type' not in obj:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in obj:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if obj['type'] != related_type_:
raise InvalidType('The type provided does not match the resource type',
source={'pointer': '/data/type'})
self.before_patch(args, kwargs, json_data=json_data)
obj_, updated = self._data_layer.update_relationship(json_data,
model_relationship_field,
related_id_field,
kwargs)
status_code = 200
result = {'meta': {'message': 'Relationship successfully updated'}}
if updated is False:
result = ''
status_code = 204
final_result = self.after_patch(result, status_code)
return final_result | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"relationship_field",
",",
"model_relationship_field",
",",
"related_type_",
",",
"related_id_field",
... | Update a relationship | [
"Update",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L417-L458 | train | 224,887 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship._get_relationship_data | def _get_relationship_data(self):
"""Get useful data for relationship management"""
relationship_field = request.path.split('/')[-1].replace('-', '_')
if relationship_field not in get_relationships(self.schema):
raise RelationNotFound("{} has no attribute {}".format(self.schema.__name__, relationship_field))
related_type_ = self.schema._declared_fields[relationship_field].type_
related_id_field = self.schema._declared_fields[relationship_field].id_field
model_relationship_field = get_model_field(self.schema, relationship_field)
return relationship_field, model_relationship_field, related_type_, related_id_field | python | def _get_relationship_data(self):
"""Get useful data for relationship management"""
relationship_field = request.path.split('/')[-1].replace('-', '_')
if relationship_field not in get_relationships(self.schema):
raise RelationNotFound("{} has no attribute {}".format(self.schema.__name__, relationship_field))
related_type_ = self.schema._declared_fields[relationship_field].type_
related_id_field = self.schema._declared_fields[relationship_field].id_field
model_relationship_field = get_model_field(self.schema, relationship_field)
return relationship_field, model_relationship_field, related_type_, related_id_field | [
"def",
"_get_relationship_data",
"(",
"self",
")",
":",
"relationship_field",
"=",
"request",
".",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"relationship_field",
"not",
"in",
"get_relat... | Get useful data for relationship management | [
"Get",
"useful",
"data",
"for",
"relationship",
"management"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L504-L515 | train | 224,888 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | compute_schema | def compute_schema(schema_cls, default_kwargs, qs, include):
"""Compute a schema around compound documents and sparse fieldsets
:param Schema schema_cls: the schema class
:param dict default_kwargs: the schema default kwargs
:param QueryStringManager qs: qs
:param list include: the relation field to include data from
:return Schema schema: the schema computed
"""
# manage include_data parameter of the schema
schema_kwargs = default_kwargs
schema_kwargs['include_data'] = tuple()
# collect sub-related_includes
related_includes = {}
if include:
for include_path in include:
field = include_path.split('.')[0]
if field not in schema_cls._declared_fields:
raise InvalidInclude("{} has no attribute {}".format(schema_cls.__name__, field))
elif not isinstance(schema_cls._declared_fields[field], Relationship):
raise InvalidInclude("{} is not a relationship attribute of {}".format(field, schema_cls.__name__))
schema_kwargs['include_data'] += (field, )
if field not in related_includes:
related_includes[field] = []
if '.' in include_path:
related_includes[field] += ['.'.join(include_path.split('.')[1:])]
# make sure id field is in only parameter unless marshamllow will raise an Exception
if schema_kwargs.get('only') is not None and 'id' not in schema_kwargs['only']:
schema_kwargs['only'] += ('id',)
# create base schema instance
schema = schema_cls(**schema_kwargs)
# manage sparse fieldsets
if schema.opts.type_ in qs.fields:
tmp_only = set(schema.declared_fields.keys()) & set(qs.fields[schema.opts.type_])
if schema.only:
tmp_only &= set(schema.only)
schema.only = tuple(tmp_only)
# make sure again that id field is in only parameter unless marshamllow will raise an Exception
if schema.only is not None and 'id' not in schema.only:
schema.only += ('id',)
# manage compound documents
if include:
for include_path in include:
field = include_path.split('.')[0]
relation_field = schema.declared_fields[field]
related_schema_cls = schema.declared_fields[field].__dict__['_Relationship__schema']
related_schema_kwargs = {}
if 'context' in default_kwargs:
related_schema_kwargs['context'] = default_kwargs['context']
if isinstance(related_schema_cls, SchemaABC):
related_schema_kwargs['many'] = related_schema_cls.many
related_schema_cls = related_schema_cls.__class__
if isinstance(related_schema_cls, str):
related_schema_cls = class_registry.get_class(related_schema_cls)
related_schema = compute_schema(related_schema_cls,
related_schema_kwargs,
qs,
related_includes[field] or None)
relation_field.__dict__['_Relationship__schema'] = related_schema
return schema | python | def compute_schema(schema_cls, default_kwargs, qs, include):
"""Compute a schema around compound documents and sparse fieldsets
:param Schema schema_cls: the schema class
:param dict default_kwargs: the schema default kwargs
:param QueryStringManager qs: qs
:param list include: the relation field to include data from
:return Schema schema: the schema computed
"""
# manage include_data parameter of the schema
schema_kwargs = default_kwargs
schema_kwargs['include_data'] = tuple()
# collect sub-related_includes
related_includes = {}
if include:
for include_path in include:
field = include_path.split('.')[0]
if field not in schema_cls._declared_fields:
raise InvalidInclude("{} has no attribute {}".format(schema_cls.__name__, field))
elif not isinstance(schema_cls._declared_fields[field], Relationship):
raise InvalidInclude("{} is not a relationship attribute of {}".format(field, schema_cls.__name__))
schema_kwargs['include_data'] += (field, )
if field not in related_includes:
related_includes[field] = []
if '.' in include_path:
related_includes[field] += ['.'.join(include_path.split('.')[1:])]
# make sure id field is in only parameter unless marshamllow will raise an Exception
if schema_kwargs.get('only') is not None and 'id' not in schema_kwargs['only']:
schema_kwargs['only'] += ('id',)
# create base schema instance
schema = schema_cls(**schema_kwargs)
# manage sparse fieldsets
if schema.opts.type_ in qs.fields:
tmp_only = set(schema.declared_fields.keys()) & set(qs.fields[schema.opts.type_])
if schema.only:
tmp_only &= set(schema.only)
schema.only = tuple(tmp_only)
# make sure again that id field is in only parameter unless marshamllow will raise an Exception
if schema.only is not None and 'id' not in schema.only:
schema.only += ('id',)
# manage compound documents
if include:
for include_path in include:
field = include_path.split('.')[0]
relation_field = schema.declared_fields[field]
related_schema_cls = schema.declared_fields[field].__dict__['_Relationship__schema']
related_schema_kwargs = {}
if 'context' in default_kwargs:
related_schema_kwargs['context'] = default_kwargs['context']
if isinstance(related_schema_cls, SchemaABC):
related_schema_kwargs['many'] = related_schema_cls.many
related_schema_cls = related_schema_cls.__class__
if isinstance(related_schema_cls, str):
related_schema_cls = class_registry.get_class(related_schema_cls)
related_schema = compute_schema(related_schema_cls,
related_schema_kwargs,
qs,
related_includes[field] or None)
relation_field.__dict__['_Relationship__schema'] = related_schema
return schema | [
"def",
"compute_schema",
"(",
"schema_cls",
",",
"default_kwargs",
",",
"qs",
",",
"include",
")",
":",
"# manage include_data parameter of the schema",
"schema_kwargs",
"=",
"default_kwargs",
"schema_kwargs",
"[",
"'include_data'",
"]",
"=",
"tuple",
"(",
")",
"# col... | Compute a schema around compound documents and sparse fieldsets
:param Schema schema_cls: the schema class
:param dict default_kwargs: the schema default kwargs
:param QueryStringManager qs: qs
:param list include: the relation field to include data from
:return Schema schema: the schema computed | [
"Compute",
"a",
"schema",
"around",
"compound",
"documents",
"and",
"sparse",
"fieldsets"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L12-L82 | train | 224,889 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_model_field | def get_model_field(schema, field):
"""Get the model field of a schema field
:param Schema schema: a marshmallow schema
:param str field: the name of the schema field
:return str: the name of the field in the model
"""
if schema._declared_fields.get(field) is None:
raise Exception("{} has no attribute {}".format(schema.__name__, field))
if schema._declared_fields[field].attribute is not None:
return schema._declared_fields[field].attribute
return field | python | def get_model_field(schema, field):
"""Get the model field of a schema field
:param Schema schema: a marshmallow schema
:param str field: the name of the schema field
:return str: the name of the field in the model
"""
if schema._declared_fields.get(field) is None:
raise Exception("{} has no attribute {}".format(schema.__name__, field))
if schema._declared_fields[field].attribute is not None:
return schema._declared_fields[field].attribute
return field | [
"def",
"get_model_field",
"(",
"schema",
",",
"field",
")",
":",
"if",
"schema",
".",
"_declared_fields",
".",
"get",
"(",
"field",
")",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"schema",
".",
"__name__"... | Get the model field of a schema field
:param Schema schema: a marshmallow schema
:param str field: the name of the schema field
:return str: the name of the field in the model | [
"Get",
"the",
"model",
"field",
"of",
"a",
"schema",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L85-L97 | train | 224,890 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_nested_fields | def get_nested_fields(schema, model_field=False):
"""Return nested fields of a schema to support a join
:param Schema schema: a marshmallow schema
:param boolean model_field: whether to extract the model field for the nested fields
:return list: list of nested fields of the schema
"""
nested_fields = []
for (key, value) in schema._declared_fields.items():
if isinstance(value, List) and isinstance(value.container, Nested):
nested_fields.append(key)
elif isinstance(value, Nested):
nested_fields.append(key)
if model_field is True:
nested_fields = [get_model_field(schema, key) for key in nested_fields]
return nested_fields | python | def get_nested_fields(schema, model_field=False):
"""Return nested fields of a schema to support a join
:param Schema schema: a marshmallow schema
:param boolean model_field: whether to extract the model field for the nested fields
:return list: list of nested fields of the schema
"""
nested_fields = []
for (key, value) in schema._declared_fields.items():
if isinstance(value, List) and isinstance(value.container, Nested):
nested_fields.append(key)
elif isinstance(value, Nested):
nested_fields.append(key)
if model_field is True:
nested_fields = [get_model_field(schema, key) for key in nested_fields]
return nested_fields | [
"def",
"get_nested_fields",
"(",
"schema",
",",
"model_field",
"=",
"False",
")",
":",
"nested_fields",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
... | Return nested fields of a schema to support a join
:param Schema schema: a marshmallow schema
:param boolean model_field: whether to extract the model field for the nested fields
:return list: list of nested fields of the schema | [
"Return",
"nested",
"fields",
"of",
"a",
"schema",
"to",
"support",
"a",
"join"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L99-L117 | train | 224,891 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_relationships | def get_relationships(schema, model_field=False):
"""Return relationship fields of a schema
:param Schema schema: a marshmallow schema
:param list: list of relationship fields of a schema
"""
relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)]
if model_field is True:
relationships = [get_model_field(schema, key) for key in relationships]
return relationships | python | def get_relationships(schema, model_field=False):
"""Return relationship fields of a schema
:param Schema schema: a marshmallow schema
:param list: list of relationship fields of a schema
"""
relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)]
if model_field is True:
relationships = [get_model_field(schema, key) for key in relationships]
return relationships | [
"def",
"get_relationships",
"(",
"schema",
",",
"model_field",
"=",
"False",
")",
":",
"relationships",
"=",
"[",
"key",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"valu... | Return relationship fields of a schema
:param Schema schema: a marshmallow schema
:param list: list of relationship fields of a schema | [
"Return",
"relationship",
"fields",
"of",
"a",
"schema"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L119-L130 | train | 224,892 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_schema_from_type | def get_schema_from_type(resource_type):
"""Retrieve a schema from the registry by his type
:param str type_: the type of the resource
:return Schema: the schema class
"""
for cls_name, cls in class_registry._registry.items():
try:
if cls[0].opts.type_ == resource_type:
return cls[0]
except Exception:
pass
raise Exception("Couldn't find schema for type: {}".format(resource_type)) | python | def get_schema_from_type(resource_type):
"""Retrieve a schema from the registry by his type
:param str type_: the type of the resource
:return Schema: the schema class
"""
for cls_name, cls in class_registry._registry.items():
try:
if cls[0].opts.type_ == resource_type:
return cls[0]
except Exception:
pass
raise Exception("Couldn't find schema for type: {}".format(resource_type)) | [
"def",
"get_schema_from_type",
"(",
"resource_type",
")",
":",
"for",
"cls_name",
",",
"cls",
"in",
"class_registry",
".",
"_registry",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"cls",
"[",
"0",
"]",
".",
"opts",
".",
"type_",
"==",
"resource_type",... | Retrieve a schema from the registry by his type
:param str type_: the type of the resource
:return Schema: the schema class | [
"Retrieve",
"a",
"schema",
"from",
"the",
"registry",
"by",
"his",
"type"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L143-L156 | train | 224,893 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_schema_field | def get_schema_field(schema, field):
"""Get the schema field of a model field
:param Schema schema: a marshmallow schema
:param str field: the name of the model field
:return str: the name of the field in the schema
"""
schema_fields_to_model = {key: get_model_field(schema, key) for (key, value) in schema._declared_fields.items()}
for key, value in schema_fields_to_model.items():
if value == field:
return key
raise Exception("Couldn't find schema field from {}".format(field)) | python | def get_schema_field(schema, field):
"""Get the schema field of a model field
:param Schema schema: a marshmallow schema
:param str field: the name of the model field
:return str: the name of the field in the schema
"""
schema_fields_to_model = {key: get_model_field(schema, key) for (key, value) in schema._declared_fields.items()}
for key, value in schema_fields_to_model.items():
if value == field:
return key
raise Exception("Couldn't find schema field from {}".format(field)) | [
"def",
"get_schema_field",
"(",
"schema",
",",
"field",
")",
":",
"schema_fields_to_model",
"=",
"{",
"key",
":",
"get_model_field",
"(",
"schema",
",",
"key",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items"... | Get the schema field of a model field
:param Schema schema: a marshmallow schema
:param str field: the name of the model field
:return str: the name of the field in the schema | [
"Get",
"the",
"schema",
"field",
"of",
"a",
"model",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L159-L171 | train | 224,894 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/base.py | BaseDataLayer.bound_rewritable_methods | def bound_rewritable_methods(self, methods):
"""Bound additional methods to current instance
:param class meta: information from Meta class used to configure the data layer instance
"""
for key, value in methods.items():
if key in self.REWRITABLE_METHODS:
setattr(self, key, types.MethodType(value, self)) | python | def bound_rewritable_methods(self, methods):
"""Bound additional methods to current instance
:param class meta: information from Meta class used to configure the data layer instance
"""
for key, value in methods.items():
if key in self.REWRITABLE_METHODS:
setattr(self, key, types.MethodType(value, self)) | [
"def",
"bound_rewritable_methods",
"(",
"self",
",",
"methods",
")",
":",
"for",
"key",
",",
"value",
"in",
"methods",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"REWRITABLE_METHODS",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"typ... | Bound additional methods to current instance
:param class meta: information from Meta class used to configure the data layer instance | [
"Bound",
"additional",
"methods",
"to",
"current",
"instance"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/base.py#L318-L325 | train | 224,895 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | create_filters | def create_filters(model, filter_info, resource):
"""Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource
"""
filters = []
for filter_ in filter_info:
filters.append(Node(model, filter_, resource, resource.schema).resolve())
return filters | python | def create_filters(model, filter_info, resource):
"""Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource
"""
filters = []
for filter_ in filter_info:
filters.append(Node(model, filter_, resource, resource.schema).resolve())
return filters | [
"def",
"create_filters",
"(",
"model",
",",
"filter_info",
",",
"resource",
")",
":",
"filters",
"=",
"[",
"]",
"for",
"filter_",
"in",
"filter_info",
":",
"filters",
".",
"append",
"(",
"Node",
"(",
"model",
",",
"filter_",
",",
"resource",
",",
"resour... | Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource | [
"Apply",
"filters",
"from",
"filters",
"information",
"to",
"base",
"query"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L11-L22 | train | 224,896 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.resolve | def resolve(self):
"""Create filter for a particular node of the filter tree"""
if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_:
value = self.value
if isinstance(value, dict):
value = Node(self.related_model, value, self.resource, self.related_schema).resolve()
if '__' in self.filter_.get('name', ''):
value = {self.filter_['name'].split('__')[1]: value}
if isinstance(value, dict):
return getattr(self.column, self.operator)(**value)
else:
return getattr(self.column, self.operator)(value)
if 'or' in self.filter_:
return or_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['or'])
if 'and' in self.filter_:
return and_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['and'])
if 'not' in self.filter_:
return not_(Node(self.model, self.filter_['not'], self.resource, self.schema).resolve()) | python | def resolve(self):
"""Create filter for a particular node of the filter tree"""
if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_:
value = self.value
if isinstance(value, dict):
value = Node(self.related_model, value, self.resource, self.related_schema).resolve()
if '__' in self.filter_.get('name', ''):
value = {self.filter_['name'].split('__')[1]: value}
if isinstance(value, dict):
return getattr(self.column, self.operator)(**value)
else:
return getattr(self.column, self.operator)(value)
if 'or' in self.filter_:
return or_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['or'])
if 'and' in self.filter_:
return and_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['and'])
if 'not' in self.filter_:
return not_(Node(self.model, self.filter_['not'], self.resource, self.schema).resolve()) | [
"def",
"resolve",
"(",
"self",
")",
":",
"if",
"'or'",
"not",
"in",
"self",
".",
"filter_",
"and",
"'and'",
"not",
"in",
"self",
".",
"filter_",
"and",
"'not'",
"not",
"in",
"self",
".",
"filter_",
":",
"value",
"=",
"self",
".",
"value",
"if",
"is... | Create filter for a particular node of the filter tree | [
"Create",
"filter",
"for",
"a",
"particular",
"node",
"of",
"the",
"filter",
"tree"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L41-L62 | train | 224,897 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.name | def name(self):
"""Return the name of the node or raise a BadRequest exception
:return str: the name of the field to filter on
"""
name = self.filter_.get('name')
if name is None:
raise InvalidFilters("Can't find name of a filter")
if '__' in name:
name = name.split('__')[0]
if name not in self.schema._declared_fields:
raise InvalidFilters("{} has no attribute {}".format(self.schema.__name__, name))
return name | python | def name(self):
"""Return the name of the node or raise a BadRequest exception
:return str: the name of the field to filter on
"""
name = self.filter_.get('name')
if name is None:
raise InvalidFilters("Can't find name of a filter")
if '__' in name:
name = name.split('__')[0]
if name not in self.schema._declared_fields:
raise InvalidFilters("{} has no attribute {}".format(self.schema.__name__, name))
return name | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"filter_",
".",
"get",
"(",
"'name'",
")",
"if",
"name",
"is",
"None",
":",
"raise",
"InvalidFilters",
"(",
"\"Can't find name of a filter\"",
")",
"if",
"'__'",
"in",
"name",
":",
"name",
... | Return the name of the node or raise a BadRequest exception
:return str: the name of the field to filter on | [
"Return",
"the",
"name",
"of",
"the",
"node",
"or",
"raise",
"a",
"BadRequest",
"exception"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L65-L81 | train | 224,898 |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.column | def column(self):
"""Get the column object
:param DeclarativeMeta model: the model
:param str field: the field
:return InstrumentedAttribute: the column to filter on
"""
field = self.name
model_field = get_model_field(self.schema, field)
try:
return getattr(self.model, model_field)
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, model_field)) | python | def column(self):
"""Get the column object
:param DeclarativeMeta model: the model
:param str field: the field
:return InstrumentedAttribute: the column to filter on
"""
field = self.name
model_field = get_model_field(self.schema, field)
try:
return getattr(self.model, model_field)
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, model_field)) | [
"def",
"column",
"(",
"self",
")",
":",
"field",
"=",
"self",
".",
"name",
"model_field",
"=",
"get_model_field",
"(",
"self",
".",
"schema",
",",
"field",
")",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"model",
",",
"model_field",
")",
"excep... | Get the column object
:param DeclarativeMeta model: the model
:param str field: the field
:return InstrumentedAttribute: the column to filter on | [
"Get",
"the",
"column",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L95-L109 | train | 224,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.