idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
35,900
def _AnsiCmd ( command_list ) : if not isinstance ( command_list , list ) : raise ValueError ( 'Invalid list: %s' % command_list ) for sgr in command_list : if sgr . lower ( ) not in SGR : raise ValueError ( 'Invalid or unsupported SGR name: %s' % sgr ) command_str = [ str ( SGR [ x . lower ( ) ] ) for x in command_lis...
Takes a list of SGR values and formats them as an ANSI escape sequence .
35,901
def TerminalSize ( ) : try : with open ( os . ctermid ( ) , 'r' ) as tty_instance : length_width = struct . unpack ( 'hh' , fcntl . ioctl ( tty_instance . fileno ( ) , termios . TIOCGWINSZ , '1234' ) ) except ( IOError , OSError ) : try : length_width = ( int ( os . environ [ 'LINES' ] ) , int ( os . environ [ 'COLUMNS...
Returns terminal length and width as a tuple .
35,902
def main ( argv = None ) : if argv is None : argv = sys . argv try : opts , args = getopt . getopt ( argv [ 1 : ] , 'dhs' , [ 'nodelay' , 'help' , 'size' ] ) except getopt . error as msg : raise Usage ( msg ) for opt , _ in opts : if opt in ( '-h' , '--help' ) : print ( __doc__ ) print ( help_msg ) return 0 isdelay = F...
Routine to page text or determine window size via command line .
35,903
def Reset ( self ) : self . _displayed = 0 self . _currentpagelines = 0 self . _lastscroll = 1 self . _lines_to_show = self . _cli_lines
Reset the pager to the top of the text .
35,904
def SetLines ( self , lines ) : ( self . _cli_lines , self . _cli_cols ) = TerminalSize ( ) if lines : self . _cli_lines = int ( lines )
Set number of screen lines .
35,905
def Page ( self , text = None , show_percent = None ) : if text is not None : self . _text += text if show_percent is None : show_percent = text is None self . _show_percent = show_percent text = LineWrap ( self . _text ) . splitlines ( ) while True : self . _newlines = text [ self . _displayed : self . _displayed + se...
Page text .
35,906
def _Scroll ( self , lines = None ) : if lines is None : lines = self . _cli_lines if lines < 0 : self . _displayed -= self . _cli_lines self . _displayed += lines if self . _displayed < 0 : self . _displayed = 0 self . _lines_to_show = self . _cli_lines else : self . _lines_to_show = lines self . _lastscroll = lines
Set attributes to scroll the buffer correctly .
35,907
def _AskUser ( self ) : if self . _show_percent : progress = int ( self . _displayed * 100 / ( len ( self . _text . splitlines ( ) ) ) ) progress_text = ' (%d%%)' % progress else : progress_text = '' question = AnsiText ( 'Enter: next line, Space: next page, ' 'b: prev page, q: quit.%s' % progress_text , [ 'green' ] ) ...
Prompt the user for the next action .
35,908
def _GetCh ( self ) : fd = self . _tty . fileno ( ) old = termios . tcgetattr ( fd ) try : tty . setraw ( fd ) ch = self . _tty . read ( 1 ) if ord ( ch ) == 27 : ch += self . _tty . read ( 2 ) finally : termios . tcsetattr ( fd , termios . TCSADRAIN , old ) return ch
Read a single character from the user .
35,909
def add_deflection ( position , observer , ephemeris , t , include_earth_deflection , count = 3 ) : tlt = length_of ( position ) / C_AUDAY jd_tdb = t . tdb ts = t . ts for name in deflectors [ : count ] : try : deflector = ephemeris [ name ] except KeyError : deflector = ephemeris [ name + ' barycenter' ] bposition = d...
Update position for how solar system masses will deflect its light .
35,910
def _add_deflection ( position , observer , deflector , rmass ) : pq = observer + position - deflector pe = observer - deflector pmag = length_of ( position ) qmag = length_of ( pq ) emag = length_of ( pe ) phat = position / where ( pmag , pmag , 1.0 ) qhat = pq / where ( qmag , qmag , 1.0 ) ehat = pe / where ( emag , ...
Correct a position vector for how one particular mass deflects light .
35,911
def add_aberration ( position , velocity , light_time ) : p1mag = light_time * C_AUDAY vemag = length_of ( velocity ) beta = vemag / C_AUDAY dot = dots ( position , velocity ) cosd = dot / ( p1mag * vemag ) gammai = sqrt ( 1.0 - beta * beta ) p = beta * cosd q = ( 1.0 + p / ( 1.0 + gammai ) ) * light_time r = 1.0 + p p...
Correct a relative position vector for aberration of light .
35,912
def _center ( code , segment_dict ) : while code in segment_dict : segment = segment_dict [ code ] yield segment code = segment . center
Starting with code follow segments from target to center .
35,913
def names ( self ) : d = defaultdict ( list ) for code , name in target_name_pairs : if code in self . codes : d [ code ] . append ( name ) return dict ( d )
Return all target names that are valid with this kernel .
35,914
def decode ( self , name ) : if isinstance ( name , int ) : code = name else : name = name . upper ( ) code = _targets . get ( name ) if code is None : raise ValueError ( 'unknown SPICE target {0!r}' . format ( name ) ) if code not in self . codes : targets = ', ' . join ( _format_code_and_name ( c ) for c in self . co...
Translate a target name into its integer code .
35,915
def _search ( mapping , filename ) : result = mapping . get ( filename ) if result is not None : return result name , ext = os . path . splitext ( filename ) result = mapping . get ( ext ) if result is not None : for pattern , result2 in result : if fnmatch ( filename , pattern ) : return result2 return None
Search a Loader data structure for a filename .
35,916
def load_file ( path ) : path = os . path . expanduser ( path ) base , ext = os . path . splitext ( path ) if ext == '.bsp' : return SpiceKernel ( path ) raise ValueError ( 'unrecognized file extension: {}' . format ( path ) )
Open a file on your local drive using its extension to guess its type .
35,917
def parse_deltat_data ( fileobj ) : array = np . loadtxt ( fileobj ) year , month , day = array [ - 1 , : 3 ] . astype ( int ) expiration_date = date ( year + 1 , month , day ) year , month , day , delta_t = array . T data = np . array ( ( julian_date ( year , month , day ) , delta_t ) ) return expiration_date , data
Parse the United States Naval Observatory deltat . data file .
35,918
def parse_deltat_preds ( fileobj ) : lines = iter ( fileobj ) header = next ( lines ) if header . startswith ( b'YEAR' ) : next ( lines ) year_float , delta_t = np . loadtxt ( lines , usecols = [ 0 , 1 ] ) . T else : year_float , delta_t = np . loadtxt ( lines , usecols = [ 1 , 2 ] ) . T year = year_float . astype ( in...
Parse the United States Naval Observatory deltat . preds file .
35,919
def parse_leap_seconds ( fileobj ) : lines = iter ( fileobj ) for line in lines : if line . startswith ( b'# File expires on' ) : break else : raise ValueError ( 'Leap_Second.dat is missing its expiration date' ) line = line . decode ( 'ascii' ) with _lock : original_locale = locale . setlocale ( locale . LC_ALL ) loc...
Parse the IERS file Leap_Second . dat .
35,920
def parse_tle ( fileobj ) : b0 = b1 = b'' for b2 in fileobj : if ( b1 . startswith ( b'1 ' ) and len ( b1 ) >= 69 and b2 . startswith ( b'2 ' ) and len ( b2 ) >= 69 ) : b0 = b0 . rstrip ( b'\n\r' ) if len ( b0 ) == 24 : name = b0 . decode ( 'ascii' ) . rstrip ( ) names = [ name ] elif b0 . startswith ( b'0 ' ) : name =...
Parse a file of TLE satellite element sets .
35,921
def download ( url , path , verbose = None , blocksize = 128 * 1024 ) : tempname = path + '.download' try : connection = urlopen ( url ) except Exception as e : raise IOError ( 'cannot get {0} because {1}' . format ( url , e ) ) if verbose is None : verbose = sys . stderr . isatty ( ) bar = None if verbose : if _runnin...
Download a file from a URL possibly displaying a progress bar .
35,922
def tle ( self , url , reload = False , filename = None ) : d = { } with self . open ( url , reload = reload , filename = filename ) as f : for names , sat in parse_tle ( f ) : d [ sat . model . satnum ] = sat for name in names : d [ name ] = sat return d
Load and parse a satellite TLE file .
35,923
def open ( self , url , mode = 'rb' , reload = False , filename = None ) : if '://' not in url : path_that_might_be_relative = url path = os . path . join ( self . directory , path_that_might_be_relative ) return open ( path , mode ) if filename is None : filename = urlparse ( url ) . path . split ( '/' ) [ - 1 ] path ...
Open a file downloading it first if it does not yet exist .
35,924
def timescale ( self , delta_t = None ) : if delta_t is not None : delta_t_recent = np . array ( ( ( - 1e99 , 1e99 ) , ( delta_t , delta_t ) ) ) else : data = self ( 'deltat.data' ) preds = self ( 'deltat.preds' ) data_end_time = data [ 0 , - 1 ] i = np . searchsorted ( preds [ 0 ] , data_end_time , side = 'right' ) de...
Open or download three time scale files returning a Timescale .
35,925
def get_summary ( url , spk = True ) : bspurl = urllib2 . urlopen ( url ) bsptip = bspurl . read ( 10 ** 5 ) bspstr = StringIO ( bsptip ) daf = DAF ( bspstr ) if spk : spk = SPK ( daf ) return spk else : return daf
simple function to retrieve the header of a BSP file and return SPK object
35,926
def _correct_for_light_travel_time ( observer , target ) : t = observer . t ts = t . ts cposition = observer . position . au cvelocity = observer . velocity . au_per_d tposition , tvelocity , gcrs_position , message = target . _at ( t ) distance = length_of ( tposition - cposition ) light_time0 = 0.0 t_tdb = t . tdb fo...
Return a light - time corrected astrometric position and velocity .
35,927
def at ( self , t ) : if not isinstance ( t , Time ) : raise ValueError ( 'please provide the at() method with a Time' ' instance as its argument, instead of the' ' value {0!r}' . format ( t ) ) observer_data = ObserverData ( ) observer_data . ephemeris = self . ephemeris p , v , observer_data . gcrs_position , message...
At time t compute the target s position relative to the center .
35,928
def _to_array ( value ) : if hasattr ( value , 'shape' ) : return value elif hasattr ( value , '__len__' ) : return array ( value ) else : return float_ ( value )
When value is a plain Python sequence return it as a NumPy array .
35,929
def julian_day ( year , month = 1 , day = 1 ) : janfeb = month < 3 return ( day + 1461 * ( year + 4800 - janfeb ) // 4 + 367 * ( month - 2 + janfeb * 12 ) // 12 - 3 * ( ( year + 4900 - janfeb ) // 100 ) // 4 - 32075 )
Given a proleptic Gregorian calendar date return a Julian day int .
35,930
def julian_date ( year , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 ) : return julian_day ( year , month , day ) - 0.5 + ( second + minute * 60.0 + hour * 3600.0 ) / DAY_S
Given a proleptic Gregorian calendar date return a Julian date float .
35,931
def tdb_minus_tt ( jd_tdb ) : t = ( jd_tdb - T0 ) / 36525.0 return ( 0.001657 * sin ( 628.3076 * t + 6.2401 ) + 0.000022 * sin ( 575.3385 * t + 4.2970 ) + 0.000014 * sin ( 1256.6152 * t + 6.1969 ) + 0.000005 * sin ( 606.9777 * t + 4.0212 ) + 0.000005 * sin ( 52.9691 * t + 0.4444 ) + 0.000002 * sin ( 21.3299 * t + 5.543...
Computes how far TDB is in advance of TT given TDB .
35,932
def interpolate_delta_t ( delta_t_table , tt ) : tt_array , delta_t_array = delta_t_table delta_t = _to_array ( interp ( tt , tt_array , delta_t_array , nan , nan ) ) missing = isnan ( delta_t ) if missing . any ( ) : if missing . shape : tt = tt [ missing ] delta_t [ missing ] = delta_t_formula_morrison_and_stephenson...
Return interpolated Delta T values for the times in tt .
35,933
def build_delta_t_table ( delta_t_recent ) : ancient = load_bundled_npy ( 'morrison_stephenson_deltat.npy' ) historic = load_bundled_npy ( 'historic_deltat.npy' ) historic_start_time = historic [ 0 , 0 ] i = searchsorted ( ancient [ 0 ] , historic_start_time ) bundled = concatenate ( [ ancient [ : , : i ] , historic ] ...
Build a table for interpolating Delta T .
35,934
def utc ( self , year , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 ) : if isinstance ( year , datetime ) : dt = year tai = _utc_datetime_to_tai ( self . leap_dates , self . leap_offsets , dt ) elif isinstance ( year , date ) : d = year tai = _utc_date_to_tai ( self . leap_dates , self . leap_offsets , d...
Build a Time from a UTC calendar date .
35,935
def tai ( self , year = None , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 , jd = None ) : 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...
Build a Time from a TAI calendar date .
35,936
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 .
35,937
def tt ( self , year = None , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 , jd = None ) : 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 ...
Build a Time from a TT calendar date .
35,938
def tdb ( self , year = None , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 , jd = None ) : 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...
Build a Time from a TDB calendar date .
35,939
def tdb_jd ( self , jd ) : tdb = _to_array ( jd ) tt = tdb - tdb_minus_tt ( tdb ) / DAY_S t = Time ( self , tt ) t . tdb = tdb return t
Build a Time from a TDB Julian date .
35,940
def ut1 ( self , year = None , month = 1 , day = 1 , hour = 0 , minute = 0 , second = 0.0 , jd = None ) : 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...
Build a Time from a UT1 calendar date .
35,941
def ut1_jd ( self , jd ) : ut1 = _to_array ( jd ) tt_approx = ut1 delta_t_approx = interpolate_delta_t ( self . delta_t_table , tt_approx ) tt_approx = ut1 + delta_t_approx / DAY_S delta_t_approx = interpolate_delta_t ( self . delta_t_table , tt_approx ) tt = ut1 + delta_t_approx / DAY_S t = Time ( self , tt ) t . ut1 ...
Build a Time from UT1 a Julian date .
35,942
def astimezone_and_leap_second ( self , tz ) : 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 ...
Convert to a Python datetime and leap second in a timezone .
35,943
def utc_datetime_and_leap_second ( self ) : 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 . sh...
Convert to a Python datetime in UTC plus a leap second value .
35,944
def utc_strftime ( self , format ) : 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...
Format the UTC time using a Python date formatting string .
35,945
def _utc_year ( self ) : d = self . _utc_float ( ) - 1721059.5 C = 365 * 100 + 24 d -= 365 d += d // C - d // ( 4 * C ) d += 365 K = 365 * 3 + 366 d -= ( d + K * 7 // 8 ) // K return d / 365.0
Return a fractional UTC year for convenience when plotting .
35,946
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 / DAY_S i = searchsorted ( leap_reverse_dates , tai , 'right' ) return tai - leap_offsets [ i ] / DAY_S
Return UTC as a floating point Julian date .
35,947
def terra ( latitude , longitude , elevation , gast ) : 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 ...
Compute the position and velocity of a terrestrial observer .
35,948
def compute_limb_angle ( position_au , observer_au ) : disobj = sqrt ( dots ( position_au , position_au ) ) disobs = sqrt ( dots ( observer_au , observer_au ) ) aprad = arcsin ( minimum ( earth_radius_au / disobs , 1.0 ) ) zdlim = pi - aprad coszd = dots ( position_au , observer_au ) / ( disobj * disobs ) coszd = clip ...
Determine the angle of an object above or below the Earth s limb .
35,949
def sidereal_time ( t ) : theta = earth_rotation_angle ( t . ut1 ) t = ( t . tdb - T0 ) / 36525.0 st = ( 0.014506 + ( ( ( ( - 0.0000000368 * t - 0.000029956 ) * t - 0.00000044 ) * t + 1.3915817 ) * t + 4612.156534 ) * t ) return ( st / 54000.0 + theta * 24.0 ) % 24.0
Compute Greenwich sidereal time at the given Time .
35,950
def refraction ( alt_degrees , temperature_C , pressure_mbar ) : 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 )
Given an observed altitude return how much the image is refracted .
35,951
def refract ( alt_degrees , temperature_C , pressure_mbar ) : 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
Given an unrefracted alt determine where it will appear in the sky .
35,952
def compute_precession ( jd_tdb ) : eps0 = 84381.406 t = ( jd_tdb - T0 ) / 36525.0 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 = ( ...
Return the rotation matrices for precessing to an array of epochs .
35,953
def compute_nutation ( t ) : 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 ) , ( ...
Generate the nutation rotations for Time t .
35,954
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_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_p...
Return a tuple of information about the earth s axis and position .
35,955
def mean_obliquity ( jd_tdb ) : t = ( jd_tdb - T0 ) / 36525.0 epsilon = ( ( ( ( - 0.0000000434 * t - 0.000000576 ) * t + 0.00200340 ) * t - 0.0001831 ) * t - 46.836769 ) * t + 84381.406 return epsilon
Return the mean obliquity of the ecliptic in arcseconds .
35,956
def equation_of_the_equinoxes_complimentary_terms ( jd_tt ) : t = ( jd_tt - T0 ) / 36525.0 shape = getattr ( jd_tt , 'shape' , ( ) ) fa = zeros ( ( 14 , ) if shape == ( ) else ( 14 , shape [ 0 ] ) ) fa [ 0 ] = ( ( 485868.249036 + ( 715923.2178 + ( 31.8792 + ( 0.051635 + ( - 0.00024470 ) * t ) * t ) * t ) * t ) * ASEC2R...
Compute the complementary terms of the equation of the equinoxes .
35,957
def iau2000a ( jd_tt ) : t = ( jd_tt - T0 ) / 36525.0 a = fundamental_arguments ( t ) 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_longitud...
Compute Earth nutation based on the IAU 2000A nutation model .
35,958
def iau2000b ( jd_tt ) : dpplan = - 0.000135 * 1e7 deplan = 0.000388 * 1e7 t = ( jd_tt - T0 ) / 36525.0 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 = ...
Compute Earth nutation based on the faster IAU 2000B nutation model .
35,959
def load_dataframe ( fobj , compression = 'gzip' ) : 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 , ...
Given an open file for hip_main . dat . gz return a parsed dataframe .
35,960
def _altaz_rotation ( self , t ) : 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 )
Compute the rotation from the ICRF into the alt - az system .
35,961
def _at ( self , 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...' ,...
Compute the GCRS position and velocity of this Topos at time t .
35,962
def osculating_elements_of ( position , reference_frame = None ) : 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 ( posi...
Produce the osculating orbital elements for a position .
35,963
def theta_GMST1982 ( jd_ut1 ) : 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 ...
Return the angle of Greenwich Mean Standard Time 1982 given the JD .
35,964
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 = array ( [ zero , zero , - theta_dot ] ) R = rot_z ( - theta ) if len ( rTEME . shape ) == 1 : rPEF = ( R ) . dot ( rTEME ) vPEF = ( R ) . dot ( vTEME ) + cross ( an...
Convert TEME position and velocity into standard ITRS coordinates .
35,965
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 , vITRF = TEME_to_ITRF ( t . ut1 , rTEME , vTEME ) return rITRF , vITRF , error
Return the ITRF position velocity and error at time t .
35,966
def _at ( self , t ) : rITRF , vITRF , error = self . ITRF_position_velocity_error ( t ) rGCRS , vGCRS = ITRF_to_GCRS2 ( t , rITRF , vITRF ) return rGCRS , vGCRS , rGCRS , error
Compute this satellite s GCRS position and velocity at time t .
35,967
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 ( ) ) df = tables [ 0 ] return pd . DataFrame ( { 'year' : df [ 0 ] , 'delta_t' : df [ 1 ] } )
Table of smoothed Delta T values from Morrison and Stephenson 2004 .
35,968
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 * v_vec return 2 * arctan2 ( length_of ( num ) , length_of ( denom ) )
Given 2 vectors in v and u return the angle separating them .
35,969
def _compute_vectors ( self ) : parallax = self . parallax_mas if parallax <= 0.0 : parallax = 1.0e-6 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...
Compute the star s position as an ICRF position and velocity .
35,970
def _to_array ( value ) : if isinstance ( value , ( tuple , list ) ) : return array ( value ) elif isinstance ( value , ( float , int ) ) : return np . float64 ( value ) else : return value
As a convenience turn Python lists and tuples into NumPy arrays .
35,971
def _sexagesimalize_to_float ( value ) : 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
Decompose value into units minutes and seconds .
35,972
def _sexagesimalize_to_int ( value , places = 0 ) : 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
Decompose value into units minutes seconds and second fractions .
35,973
def _hstr ( hours , places = 2 ) : 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 )
Convert floating point hours into a sexagesimal string .
35,974
def _dstr ( degrees , places = 1 , signed = False ) : r 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 )
r Convert floating point degrees into a sexagesimal string .
35,975
def _interpret_angle ( name , angle_object , angle_float , unit = 'degrees' ) : 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}...
Return an angle in radians from one of two arguments .
35,976
def _interpret_ltude ( value , name , psuffix , nsuffix ) : 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}...
Interpret a string float or tuple as a latitude or longitude angle .
35,977
def to ( self , unit ) : from astropy . units import au return ( self . au * au ) . to ( unit )
Convert this distance to the given AstroPy unit .
35,978
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 .
35,979
def hstr ( self , places = 2 , warn = True ) : 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...
Convert to a string like 12h 07m 30 . 00s .
35,980
def dstr ( self , places = 1 , warn = True ) : 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 ...
Convert to a string like 181deg 52 \ 30 . 0 .
35,981
def to ( self , unit ) : from astropy . units import rad return ( self . radians * rad ) . to ( unit ) from astropy . coordinates import Angle from astropy . units import rad return Angle ( self . radians , rad ) . to ( unit )
Convert this angle to the given AstroPy unit .
35,982
def separation_from ( self , another_icrf ) : 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 ( cli...
Return the angle between this position and another .
35,983
def to_skycoord ( self , unit = None ) : 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 )
Convert this distance to an AstroPy SkyCoord object .
35,984
def from_altaz ( self , alt = None , az = None , alt_degrees = None , az_degrees = None , distance = Distance ( au = 0.1 ) ) : 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 horizo...
Generate an Apparent position from an altitude and azimuth .
35,985
def observe ( self , body ) : 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
Compute the Astrometric position of a body from this location .
35,986
def subpoint ( self ) : if self . center != 399 : 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 ) from . topo...
Return the latitude and longitude directly beneath this position .
35,987
def _plot_stars ( catalog , observer , project , ax , mag1 , mag2 , margin = 1.25 ) : art = [ ] 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_a...
Experiment in progress hence the underscore ; expect changes .
35,988
def phase_angle ( ephemeris , body , t ) : earth = ephemeris [ 'earth' ] sun = ephemeris [ 'sun' ] body = ephemeris [ body ] pe = earth . at ( t ) . observe ( body ) pe . position . au *= - 1 t2 = t . ts . tt_jd ( t . tt - pe . light_time ) ps = body . at ( t2 ) . observe ( sun ) return pe . separation_from ( ps )
Compute the phase angle of a body viewed from Earth .
35,989
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 .
35,990
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 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 peri...
Find the times when a function changes value .
35,991
def seasons ( ephemeris ) : earth = ephemeris [ 'earth' ] sun = ephemeris [ 'sun' ] def season_at ( 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...
Build a function of time that returns the quarter of the year .
35,992
def sunrise_sunset ( ephemeris , topos ) : sun = ephemeris [ 'sun' ] topos_at = ( ephemeris [ 'earth' ] + topos ) . at def is_sun_up_at ( 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 retur...
Build a function of time that returns whether the sun is up .
35,993
def moon_phases ( ephemeris ) : earth = ephemeris [ 'earth' ] moon = ephemeris [ 'moon' ] sun = ephemeris [ 'sun' ] def moon_phase_at ( t ) : t . _nutation_angles = iau2000b ( t . tt ) e = earth . at ( t ) _ , mlon , _ = e . observe ( moon ) . apparent ( ) . ecliptic_latlon ( 'date' ) _ , slon , _ = e . observe ( sun )...
Build a function of time that returns the moon phase 0 through 3 .
35,994
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 y_c z_c x y z' ) around_z = atan2 ( x_c , y_c ) around_x = acos ( - z_c ) v = Matrix ( [ x , y , z ] ) xo , yo , zo = rot_axis1 ( around_x ) * rot_axis3 ( - around_z ) *...
Compute the formulae to cut - and - paste into the routine below .
35,995
def classifier_factory ( clf ) : 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_method...
Embeds scikit - plot instance methods in an sklearn classifier .
35,996
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 = "larg...
Generates the confusion matrix for a given classifier and dataset .
35,997
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" ) : y = np . array ( y ) if not hasattr ( clf , 'predict_proba' ) : raise TypeError ( '"predict_p...
Generates the KS Statistic plot for a given classifier and dataset .
35,998
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" ) : if ax is None : fig , ax = plt . sub...
Generates confusion matrix plot from predictions and true labels
35,999
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" ) : if not hasattr ( clf , 'feature_importances_' ) : raise TypeError ( '"featu...
Generates a plot of a classifier s feature importances .