idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
21,900
def code ( self , value ) : if value not in list ( defines . Codes . LIST . keys ( ) ) and value is not None : raise AttributeError self . _code = value
Set the code of the message .
21,901
def acknowledged ( self , value ) : assert ( isinstance ( value , bool ) ) self . _acknowledged = value if value : self . _timeouted = False self . _rejected = False self . _cancelled = False
Marks this message as acknowledged .
21,902
def rejected ( self , value ) : assert ( isinstance ( value , bool ) ) self . _rejected = value if value : self . _timeouted = False self . _acknowledged = False self . _cancelled = True
Marks this message as rejected .
21,903
def _already_in ( self , option ) : for opt in self . _options : if option . number == opt . number : return True return False
Check if an option is already in the message .
21,904
def add_option ( self , option ) : assert isinstance ( option , Option ) repeatable = defines . OptionRegistry . LIST [ option . number ] . repeatable if not repeatable : ret = self . _already_in ( option ) if ret : raise TypeError ( "Option : %s is not repeatable" , option . name ) else : self . _options . append ( option ) else : self . _options . append ( option )
Add an option to the message .
21,905
def del_option ( self , option ) : assert isinstance ( option , Option ) while option in list ( self . _options ) : self . _options . remove ( option )
Delete an option from the message
21,906
def del_option_by_name ( self , name ) : for o in list ( self . _options ) : assert isinstance ( o , Option ) if o . name == name : self . _options . remove ( o )
Delete an option from the message by name
21,907
def del_option_by_number ( self , number ) : for o in list ( self . _options ) : assert isinstance ( o , Option ) if o . number == number : self . _options . remove ( o )
Delete an option from the message by number
21,908
def etag ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . ETAG . number : value . append ( option . value ) return value
Get the ETag option of the message .
21,909
def etag ( self , etag ) : if not isinstance ( etag , list ) : etag = [ etag ] for e in etag : option = Option ( ) option . number = defines . OptionRegistry . ETAG . number if not isinstance ( e , bytes ) : e = bytes ( e , "utf-8" ) option . value = e self . add_option ( option )
Add an ETag option to the message .
21,910
def content_type ( self ) : value = 0 for option in self . options : if option . number == defines . OptionRegistry . CONTENT_TYPE . number : value = int ( option . value ) return value
Get the Content - Type option of a response .
21,911
def content_type ( self , content_type ) : option = Option ( ) option . number = defines . OptionRegistry . CONTENT_TYPE . number option . value = int ( content_type ) self . add_option ( option )
Set the Content - Type option of a response .
21,912
def observe ( self ) : for option in self . options : if option . number == defines . OptionRegistry . OBSERVE . number : if option . value is None : return 0 return option . value return None
Check if the request is an observing request .
21,913
def observe ( self , ob ) : option = Option ( ) option . number = defines . OptionRegistry . OBSERVE . number option . value = ob self . del_option_by_number ( defines . OptionRegistry . OBSERVE . number ) self . add_option ( option )
Add the Observe option .
21,914
def block1 ( self ) : value = None for option in self . options : if option . number == defines . OptionRegistry . BLOCK1 . number : value = parse_blockwise ( option . value ) return value
Get the Block1 option .
21,915
def block1 ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . BLOCK1 . number num , m , size = value if size > 512 : szx = 6 elif 256 < size <= 512 : szx = 5 elif 128 < size <= 256 : szx = 4 elif 64 < size <= 128 : szx = 3 elif 32 < size <= 64 : szx = 2 elif 16 < size <= 32 : szx = 1 else : szx = 0 value = ( num << 4 ) value |= ( m << 3 ) value |= szx option . value = value self . add_option ( option )
Set the Block1 option .
21,916
def block2 ( self ) : value = None for option in self . options : if option . number == defines . OptionRegistry . BLOCK2 . number : value = parse_blockwise ( option . value ) return value
Get the Block2 option .
21,917
def block2 ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . BLOCK2 . number num , m , size = value if size > 512 : szx = 6 elif 256 < size <= 512 : szx = 5 elif 128 < size <= 256 : szx = 4 elif 64 < size <= 128 : szx = 3 elif 32 < size <= 64 : szx = 2 elif 16 < size <= 32 : szx = 1 else : szx = 0 value = ( num << 4 ) value |= ( m << 3 ) value |= szx option . value = value self . add_option ( option )
Set the Block2 option .
21,918
def line_print ( self ) : inv_types = { v : k for k , v in defines . Types . items ( ) } if self . _code is None : self . _code = defines . Codes . EMPTY . number msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, [" . format ( source = self . _source , destination = self . _destination , type = inv_types [ self . _type ] , mid = self . _mid , code = defines . Codes . LIST [ self . _code ] . name , token = self . _token ) for opt in self . _options : msg += "{name}: {value}, " . format ( name = opt . name , value = opt . value ) msg += "]" if self . payload is not None : if isinstance ( self . payload , dict ) : tmp = list ( self . payload . values ( ) ) [ 0 ] [ 0 : 20 ] else : tmp = self . payload [ 0 : 20 ] msg += " {payload}...{length} bytes" . format ( payload = tmp , length = len ( self . payload ) ) else : msg += " No payload" return msg
Return the message as a one - line string .
21,919
def pretty_print ( self ) : msg = "Source: " + str ( self . _source ) + "\n" msg += "Destination: " + str ( self . _destination ) + "\n" inv_types = { v : k for k , v in defines . Types . items ( ) } msg += "Type: " + str ( inv_types [ self . _type ] ) + "\n" msg += "MID: " + str ( self . _mid ) + "\n" if self . _code is None : self . _code = 0 msg += "Code: " + str ( defines . Codes . LIST [ self . _code ] . name ) + "\n" msg += "Token: " + str ( self . _token ) + "\n" for opt in self . _options : msg += str ( opt ) msg += "Payload: " + "\n" msg += str ( self . _payload ) + "\n" return msg
Return the message as a formatted string .
21,920
def interp_box ( x , y , z , box , values ) : val = 0 norm = 0 for i in range ( 8 ) : distance = sqrt ( ( x - box [ i , 0 ] ) ** 2 + ( y - box [ i , 1 ] ) ** 2 + ( z - box [ i , 2 ] ) ** 2 ) if distance == 0 : val = values [ i ] norm = 1. break w = 1. / distance val += w * values [ i ] norm += w return val / norm
box is 8x3 array though not really a box
21,921
def get_photometry ( self , brightest = False , min_unc = 0.02 , convert = True ) : if brightest : row = self . brightest else : row = self . closest if not hasattr ( self , 'conversions' ) : convert = False if convert : bands = self . conversions else : bands = self . bands . keys ( ) d = { } for b in bands : if convert : key = b mag , dmag = getattr ( self , b ) ( brightest = brightest ) else : key = self . bands [ b ] mag , dmag = row [ b ] , row [ 'e_{}' . format ( b ) ] d [ key ] = mag , max ( dmag , min_unc ) return d
Returns dictionary of photometry of closest match
21,922
def get_ichrone ( models , bands = None , default = False , ** kwargs ) : if isinstance ( models , Isochrone ) : return models def actual ( bands , ictype ) : if bands is None : return list ( ictype . default_bands ) elif default : return list ( set ( bands ) . union ( set ( ictype . default_bands ) ) ) else : return bands if type ( models ) is type ( type ) : ichrone = models ( actual ( bands , models ) ) elif models == 'dartmouth' : from isochrones . dartmouth import Dartmouth_Isochrone ichrone = Dartmouth_Isochrone ( bands = actual ( bands , Dartmouth_Isochrone ) , ** kwargs ) elif models == 'dartmouthfast' : from isochrones . dartmouth import Dartmouth_FastIsochrone ichrone = Dartmouth_FastIsochrone ( bands = actual ( bands , Dartmouth_FastIsochrone ) , ** kwargs ) elif models == 'mist' : from isochrones . mist import MIST_Isochrone ichrone = MIST_Isochrone ( bands = actual ( bands , MIST_Isochrone ) , ** kwargs ) elif models == 'padova' : from isochrones . padova import Padova_Isochrone ichrone = Padova_Isochrone ( bands = actual ( bands , Padova_Isochrone ) , ** kwargs ) elif models == 'basti' : from isochrones . basti import Basti_Isochrone ichrone = Basti_Isochrone ( bands = actual ( bands , Basti_Isochrone ) , ** kwargs ) else : raise ValueError ( 'Unknown stellar models: {}' . format ( models ) ) return ichrone
Gets Isochrone Object by name or type with the right bands
21,923
def delta_nu ( self , * args ) : return 134.88 * np . sqrt ( self . mass ( * args ) / self . radius ( * args ) ** 3 )
Returns asteroseismic delta_nu in uHz
21,924
def nu_max ( self , * args ) : return 3120. * ( self . mass ( * args ) / ( self . radius ( * args ) ** 2 * np . sqrt ( self . Teff ( * args ) / 5777. ) ) )
Returns asteroseismic nu_max in uHz
21,925
def agerange ( self , m , feh = 0.0 ) : ages = np . arange ( self . minage , self . maxage , 0.01 ) rs = self . radius ( m , ages , feh ) w = np . where ( np . isfinite ( rs ) ) [ 0 ] return ages [ w [ 0 ] ] , ages [ w [ - 1 ] ]
For a given mass and feh returns the min and max allowed ages .
21,926
def evtrack ( self , m , feh = 0.0 , minage = None , maxage = None , dage = 0.02 , return_df = True ) : if minage is None : minage = self . minage if maxage is None : maxage = self . maxage ages = np . arange ( minage , maxage , dage ) Ms = self . mass ( m , ages , feh ) Rs = self . radius ( m , ages , feh ) logLs = self . logL ( m , ages , feh ) loggs = self . logg ( m , ages , feh ) Teffs = self . Teff ( m , ages , feh ) mags = { band : self . mag [ band ] ( m , ages , feh ) for band in self . bands } props = { 'age' : ages , 'mass' : Ms , 'radius' : Rs , 'logL' : logLs , 'logg' : loggs , 'Teff' : Teffs , 'mag' : mags } if not return_df : return props else : d = { } for key in props . keys ( ) : if key == 'mag' : for m in props [ 'mag' ] . keys ( ) : d [ '{}_mag' . format ( m ) ] = props [ 'mag' ] [ m ] else : d [ key ] = props [ key ] try : df = pd . DataFrame ( d ) except ValueError : df = pd . DataFrame ( d , index = [ 0 ] ) return df
Returns evolution track for a single initial mass and feh .
21,927
def isochrone ( self , age , feh = 0.0 , minm = None , maxm = None , dm = 0.02 , return_df = True , distance = None , AV = 0.0 ) : if minm is None : minm = self . minmass if maxm is None : maxm = self . maxmass ms = np . arange ( minm , maxm , dm ) ages = np . ones ( ms . shape ) * age Ms = self . mass ( ms , ages , feh ) Rs = self . radius ( ms , ages , feh ) logLs = self . logL ( ms , ages , feh ) loggs = self . logg ( ms , ages , feh ) Teffs = self . Teff ( ms , ages , feh ) mags = { band : self . mag [ band ] ( ms , ages , feh ) for band in self . bands } if distance is not None : dm = 5 * np . log10 ( distance ) - 5 for band in mags : A = AV * EXTINCTION [ band ] mags [ band ] = mags [ band ] + dm + A props = { 'M' : Ms , 'R' : Rs , 'logL' : logLs , 'logg' : loggs , 'Teff' : Teffs , 'mag' : mags } if not return_df : return props else : d = { } for key in props . keys ( ) : if key == 'mag' : for m in props [ 'mag' ] . keys ( ) : d [ '{}_mag' . format ( m ) ] = props [ 'mag' ] [ m ] else : d [ key ] = props [ key ] try : df = pd . DataFrame ( d ) except ValueError : df = pd . DataFrame ( d , index = [ 0 ] ) return df
Returns stellar models at constant age and feh for a range of masses
21,928
def random_points ( self , n , minmass = None , maxmass = None , minage = None , maxage = None , minfeh = None , maxfeh = None ) : if minmass is None : minmass = self . minmass if maxmass is None : maxmass = self . maxmass if minage is None : minage = self . minage if maxage is None : maxage = self . maxage if minfeh is None : minfeh = self . minfeh if maxfeh is None : maxfeh = self . maxfeh ms = rand . uniform ( minmass , maxmass , size = n ) ages = rand . uniform ( minage , maxage , size = n ) fehs = rand . uniform ( minage , maxage , size = n ) Rs = self . radius ( ms , ages , fehs ) bad = np . isnan ( Rs ) nbad = bad . sum ( ) while nbad > 0 : ms [ bad ] = rand . uniform ( minmass , maxmass , size = nbad ) ages [ bad ] = rand . uniform ( minage , maxage , size = nbad ) fehs [ bad ] = rand . uniform ( minfeh , maxfeh , size = nbad ) Rs = self . radius ( ms , ages , fehs ) bad = np . isnan ( Rs ) nbad = bad . sum ( ) return ms , ages , fehs
Returns n random mass age feh points none of which are out of range .
21,929
def _parse_band ( cls , kw ) : m = re . search ( '([a-zA-Z0-9]+)(_\d+)?' , kw ) if m : if m . group ( 1 ) in cls . _not_a_band : return None else : return m . group ( 1 )
Returns photometric band from inifile keyword
21,930
def _build_obs ( self , ** kwargs ) : logging . debug ( 'Building ObservationTree...' ) tree = ObservationTree ( ) for k , v in kwargs . items ( ) : if k in self . ic . bands : if np . size ( v ) != 2 : logging . warning ( '{}={} ignored.' . format ( k , v ) ) v = [ v , np . nan ] o = Observation ( '' , k , 99 ) s = Source ( v [ 0 ] , v [ 1 ] ) o . add_source ( s ) logging . debug ( 'Adding {} ({})' . format ( s , o ) ) tree . add_observation ( o ) self . obs = tree
Builds ObservationTree out of keyword arguments
21,931
def _add_properties ( self , ** kwargs ) : for k , v in kwargs . items ( ) : if k == 'parallax' : self . obs . add_parallax ( v ) elif k in [ 'Teff' , 'logg' , 'feh' , 'density' ] : par = { k : v } self . obs . add_spectroscopy ( ** par ) elif re . search ( '_' , k ) : m = re . search ( '^(\w+)_(\w+)$' , k ) prop = m . group ( 1 ) tag = m . group ( 2 ) self . obs . add_spectroscopy ( ** { prop : v , 'label' : '0_{}' . format ( tag ) } )
Adds non - photometry properties to ObservationTree
21,932
def mnest_basename ( self ) : if not hasattr ( self , '_mnest_basename' ) : s = self . labelstring if s == '0_0' : s = 'single' elif s == '0_0-0_1' : s = 'binary' elif s == '0_0-0_1-0_2' : s = 'triple' s = '{}-{}' . format ( self . ic . name , s ) self . _mnest_basename = os . path . join ( 'chains' , s + '-' ) if os . path . isabs ( self . _mnest_basename ) : return self . _mnest_basename else : return os . path . join ( self . directory , self . _mnest_basename )
Full path to basename
21,933
def samples ( self ) : if not hasattr ( self , 'sampler' ) and self . _samples is None : raise AttributeError ( 'Must run MCMC (or load from file) ' + 'before accessing samples' ) if self . _samples is not None : df = self . _samples else : self . _make_samples ( ) df = self . _samples return df
Dataframe with samples drawn from isochrone according to posterior
21,934
def random_samples ( self , n ) : samples = self . samples inds = rand . randint ( len ( samples ) , size = int ( n ) ) newsamples = samples . iloc [ inds ] newsamples . reset_index ( inplace = True ) return newsamples
Returns a random sampling of given size from the existing samples .
21,935
def corner_observed ( self , ** kwargs ) : tot_mags = [ ] names = [ ] truths = [ ] rng = [ ] for n in self . obs . get_obs_nodes ( ) : labels = [ l . label for l in n . get_model_nodes ( ) ] band = n . band mags = [ self . samples [ '{}_mag_{}' . format ( band , l ) ] for l in labels ] tot_mag = addmags ( * mags ) if n . relative : name = '{} $\Delta${}' . format ( n . instrument , n . band ) ref = n . reference if ref is None : continue ref_labels = [ l . label for l in ref . get_model_nodes ( ) ] ref_mags = [ self . samples [ '{}_mag_{}' . format ( band , l ) ] for l in ref_labels ] tot_ref_mag = addmags ( * ref_mags ) tot_mags . append ( tot_mag - tot_ref_mag ) truths . append ( n . value [ 0 ] - ref . value [ 0 ] ) else : name = '{} {}' . format ( n . instrument , n . band ) tot_mags . append ( tot_mag ) truths . append ( n . value [ 0 ] ) names . append ( name ) rng . append ( ( min ( truths [ - 1 ] , np . percentile ( tot_mags [ - 1 ] , 0.5 ) ) , max ( truths [ - 1 ] , np . percentile ( tot_mags [ - 1 ] , 99.5 ) ) ) ) tot_mags = np . array ( tot_mags ) . T return corner . corner ( tot_mags , labels = names , truths = truths , range = rng , ** kwargs )
Makes corner plot for each observed node magnitude
21,936
def _get_df ( self ) : grids = { } df = pd . DataFrame ( ) for bnd in self . bands : s , b = self . get_band ( bnd , ** self . kwargs ) logging . debug ( 'loading {} band from {}' . format ( b , s ) ) if s not in grids : grids [ s ] = self . get_hdf ( s ) if self . common_columns [ 0 ] not in df : df [ list ( self . common_columns ) ] = grids [ s ] [ list ( self . common_columns ) ] col = grids [ s ] [ b ] n_nan = np . isnan ( col ) . sum ( ) if n_nan > 0 : logging . debug ( '{} NANs in {} column' . format ( n_nan , b ) ) df . loc [ : , bnd ] = col . values return df
Returns stellar model grid with desired bandpasses and with standard column names
21,937
def extract_master_tarball ( cls ) : if not os . path . exists ( cls . master_tarball_file ) : cls . download_grids ( ) with tarfile . open ( os . path . join ( ISOCHRONES , cls . master_tarball_file ) ) as tar : logging . info ( 'Extracting {}...' . format ( cls . master_tarball_file ) ) tar . extractall ( ISOCHRONES )
Unpack tarball of tarballs
21,938
def df_all ( self , phot ) : df = pd . concat ( [ self . to_df ( f ) for f in self . get_filenames ( phot ) ] ) return df
Subclasses may want to sort this
21,939
def get_band ( cls , b , ** kwargs ) : phot = None if b in [ 'u' , 'g' , 'r' , 'i' , 'z' ] : phot = 'SDSS' band = 'SDSS_{}' . format ( b ) elif b in [ 'U' , 'B' , 'V' , 'R' , 'I' ] : phot = 'UBVRIplus' band = 'Bessell_{}' . format ( b ) elif b in [ 'J' , 'H' , 'Ks' ] : phot = 'UBVRIplus' band = '2MASS_{}' . format ( b ) elif b == 'K' : phot = 'UBVRIplus' band = '2MASS_Ks' elif b in [ 'kep' , 'Kepler' , 'Kp' ] : phot = 'UBVRIplus' band = 'Kepler_Kp' elif b == 'TESS' : phot = 'UBVRIplus' band = 'TESS' elif b in [ 'W1' , 'W2' , 'W3' , 'W4' ] : phot = 'WISE' band = 'WISE_{}' . format ( b ) elif b in ( 'G' , 'BP' , 'RP' ) : phot = 'UBVRIplus' band = 'Gaia_{}' . format ( b ) if 'version' in kwargs : if kwargs [ 'version' ] == '1.1' : band += '_DR2Rev' else : m = re . match ( '([a-zA-Z]+)_([a-zA-Z_]+)' , b ) if m : if m . group ( 1 ) in cls . phot_systems : phot = m . group ( 1 ) if phot == 'PanSTARRS' : band = 'PS_{}' . format ( m . group ( 2 ) ) else : band = m . group ( 0 ) elif m . group ( 1 ) in [ 'UK' , 'UKIRT' ] : phot = 'UKIDSS' band = 'UKIDSS_{}' . format ( m . group ( 2 ) ) if phot is None : for system , bands in cls . phot_bands . items ( ) : if b in bands : phot = system band = b break if phot is None : raise ValueError ( 'MIST grids cannot resolve band {}!' . format ( b ) ) return phot , band
Defines what a shortcut band name refers to . Returns phot_system band
21,940
def remove_child ( self , label ) : ind = None for i , c in enumerate ( self . children ) : if c . label == label : ind = i if ind is None : logging . warning ( 'No child labeled {}.' . format ( label ) ) return self . children . pop ( ind ) self . _clear_all_leaves ( )
Removes node by label
21,941
def select_leaves ( self , name ) : if self . is_leaf : return [ self ] if re . search ( name , self . label ) else [ ] else : leaves = [ ] if re . search ( name , self . label ) : for c in self . children : leaves += c . _get_leaves ( ) else : for c in self . children : leaves += c . select_leaves ( name ) return leaves
Returns all leaves under all nodes matching name
21,942
def get_obs_leaves ( self ) : obs_leaves = [ ] for n in self : if n . is_leaf : if isinstance ( n , ModelNode ) : l = n . parent else : l = n if l not in obs_leaves : obs_leaves . append ( l ) return obs_leaves
Returns the last obs nodes that are leaves
21,943
def distance ( self , other ) : return distance ( ( self . separation , self . pa ) , ( other . separation , other . pa ) )
Coordinate distance from another ObsNode
21,944
def Nstars ( self ) : if self . _Nstars is None : N = { } for n in self . get_model_nodes ( ) : if n . index not in N : N [ n . index ] = 1 else : N [ n . index ] += 1 self . _Nstars = N return self . _Nstars
dictionary of number of stars per system
21,945
def add_model ( self , ic , N = 1 , index = 0 ) : if type ( index ) in [ list , tuple ] : if len ( index ) != N : raise ValueError ( 'If a list, index must be of length N.' ) else : index = [ index ] * N for idx in index : existing = self . get_system ( idx ) tag = len ( existing ) self . add_child ( ModelNode ( ic , index = idx , tag = tag ) )
Should only be able to do this to a leaf node .
21,946
def model_mag ( self , pardict , use_cache = True ) : if pardict == self . _cache_key and use_cache : return self . _cache_val self . _cache_key = pardict p = [ ] for l in self . leaf_labels : p . extend ( pardict [ l ] ) assert len ( p ) == self . n_params tot = np . inf for i , m in enumerate ( self . leaves ) : mag = m . evaluate ( p [ i * 5 : ( i + 1 ) * 5 ] , self . band ) tot = addmags ( tot , mag ) self . _cache_val = tot return tot
pardict is a dictionary of parameters for all leaves gets converted back to traditional parameter vector
21,947
def lnlike ( self , pardict , use_cache = True ) : mag , dmag = self . value if np . isnan ( dmag ) : return 0 if self . relative : if self . reference is None : return 0 mod = ( self . model_mag ( pardict , use_cache = use_cache ) - self . reference . model_mag ( pardict , use_cache = use_cache ) ) mag -= self . reference . value [ 0 ] else : mod = self . model_mag ( pardict , use_cache = use_cache ) lnl = - 0.5 * ( mag - mod ) ** 2 / dmag ** 2 return lnl
returns log - likelihood of this observation
21,948
def from_df ( cls , df , ** kwargs ) : tree = cls ( ** kwargs ) for ( n , b ) , g in df . groupby ( [ 'name' , 'band' ] ) : sources = [ Source ( ** s [ [ 'mag' , 'e_mag' , 'separation' , 'pa' , 'relative' ] ] ) for _ , s in g . iterrows ( ) ] obs = Observation ( n , b , g . resolution . mean ( ) , sources = sources , relative = g . relative . any ( ) ) tree . add_observation ( obs ) return tree
DataFrame must have the right columns .
21,949
def to_df ( self ) : df = pd . DataFrame ( ) name = [ ] band = [ ] resolution = [ ] mag = [ ] e_mag = [ ] separation = [ ] pa = [ ] relative = [ ] for o in self . _observations : for s in o . sources : name . append ( o . name ) band . append ( o . band ) resolution . append ( o . resolution ) mag . append ( s . mag ) e_mag . append ( s . e_mag ) separation . append ( s . separation ) pa . append ( s . pa ) relative . append ( s . relative ) return pd . DataFrame ( { 'name' : name , 'band' : band , 'resolution' : resolution , 'mag' : mag , 'e_mag' : e_mag , 'separation' : separation , 'pa' : pa , 'relative' : relative } )
Returns DataFrame with photometry from observations organized .
21,950
def save_hdf ( self , filename , path = '' , overwrite = False , append = False ) : if os . path . exists ( filename ) : store = pd . HDFStore ( filename ) if path in store : store . close ( ) if overwrite : os . remove ( filename ) elif not append : raise IOError ( '{} in {} exists. Set either overwrite or append option.' . format ( path , filename ) ) else : store . close ( ) df = self . to_df ( ) df . to_hdf ( filename , path + '/df' ) with pd . HDFStore ( filename ) as store : attrs = store . get_storer ( path + '/df' ) . attrs attrs . spectroscopy = self . spectroscopy attrs . parallax = self . parallax attrs . N = self . _N attrs . index = self . _index store . close ( )
Writes all info necessary to recreate object to HDF file
21,951
def load_hdf ( cls , filename , path = '' , ic = None ) : store = pd . HDFStore ( filename ) try : samples = store [ path + '/df' ] attrs = store . get_storer ( path + '/df' ) . attrs except : store . close ( ) raise df = store [ path + '/df' ] new = cls . from_df ( df ) if ic is None : ic = get_ichrone ( 'mist' ) new . define_models ( ic , N = attrs . N , index = attrs . index ) new . spectroscopy = attrs . spectroscopy new . parallax = attrs . parallax store . close ( ) return new
Loads stored ObservationTree from file .
21,952
def add_observation ( self , obs ) : if len ( self . _observations ) == 0 : self . _observations . append ( obs ) else : res = obs . resolution ind = 0 for o in self . _observations : if res > o . resolution : break ind += 1 self . _observations . insert ( ind , obs ) self . _build_tree ( ) self . _clear_cache ( )
Adds an observation to observation list keeping proper order
21,953
def add_limit ( self , label = '0_0' , ** props ) : if label not in self . leaf_labels : raise ValueError ( 'No model node named {} (must be in {}). Maybe define models first?' . format ( label , self . leaf_labels ) ) for k , v in props . items ( ) : if k not in self . spec_props : raise ValueError ( 'Illegal property {} (only {} allowed).' . format ( k , self . spec_props ) ) if len ( v ) != 2 : raise ValueError ( 'Must provide (min, max) for {}. (`None` is allowed value)' . format ( k ) ) if label not in self . limits : self . limits [ label ] = { } for k , v in props . items ( ) : vmin , vmax = v if vmin is None : vmin = - np . inf if vmax is None : vmax = np . inf self . limits [ label ] [ k ] = ( vmin , vmax ) self . _clear_cache ( )
Define limits to spectroscopic property of particular stars .
21,954
def define_models ( self , ic , leaves = None , N = 1 , index = 0 ) : self . clear_models ( ) if leaves is None : leaves = self . _get_leaves ( ) elif type ( leaves ) == type ( '' ) : leaves = self . select_leaves ( leaves ) if np . isscalar ( N ) : N = ( np . ones ( len ( leaves ) ) * N ) N = np . array ( N ) . astype ( int ) if np . isscalar ( index ) : index = ( np . ones_like ( N ) * index ) index = np . array ( index ) . astype ( int ) for s , n , i in zip ( leaves , N , index ) : s . remove_children ( ) s . add_model ( ic , n , i ) self . _fix_labels ( ) self . _N = N self . _index = index self . _clear_all_leaves ( )
N index are either integers or lists of integers .
21,955
def _fix_labels ( self ) : for s in self . systems : mag0 = np . inf n0 = None for n in self . get_system ( s ) : if isinstance ( n . parent , DummyObsNode ) : continue mag , _ = n . parent . value if mag < mag0 : mag0 = mag n0 = n if n0 is not None and n0 . tag != 0 : n_other = self . get_leaf ( '{}_{}' . format ( s , 0 ) ) n_other . tag = n0 . tag n0 . tag = 0
For each system make sure tag _0 is the brightest and make sure system 0 contains the brightest star in the highest - resolution image
21,956
def select_observations ( self , name ) : return [ n for n in self . get_obs_nodes ( ) if n . obsname == name ]
Returns nodes whose instrument - band matches name
21,957
def trim ( self ) : return for l in self . _levels [ - 2 : : - 1 ] : for n in l : if n . is_leaf : n . parent . remove_child ( n . label ) self . _clear_all_leaves ( )
Trims leaves from tree that are not observed at highest - resolution level
21,958
def p2pardict ( self , p ) : d = { } N = self . Nstars i = 0 for s in self . systems : age , feh , dist , AV = p [ i + N [ s ] : i + N [ s ] + 4 ] for j in xrange ( N [ s ] ) : l = '{}_{}' . format ( s , j ) mass = p [ i + j ] d [ l ] = [ mass , age , feh , dist , AV ] i += N [ s ] + 4 return d
Given leaf labels turns parameter vector into pardict
21,959
def lnlike ( self , p , use_cache = True ) : if use_cache and self . _cache_key is not None and np . all ( p == self . _cache_key ) : return self . _cache_val self . _cache_key = p pardict = self . p2pardict ( p ) lnl = 0 for n in self : if n is not self : lnl += n . lnlike ( pardict , use_cache = use_cache ) if not np . isfinite ( lnl ) : self . _cache_val = - np . inf return - np . inf for l in self . spectroscopy : for prop , ( val , err ) in self . spectroscopy [ l ] . items ( ) : mod = self . get_leaf ( l ) . evaluate ( pardict [ l ] , prop ) lnl += - 0.5 * ( val - mod ) ** 2 / err ** 2 if not np . isfinite ( lnl ) : self . _cache_val = - np . inf return - np . inf for l in self . limits : for prop , ( vmin , vmax ) in self . limits [ l ] . items ( ) : mod = self . get_leaf ( l ) . evaluate ( pardict [ l ] , prop ) if mod < vmin or mod > vmax or not np . isfinite ( mod ) : self . _cache_val = - np . inf return - np . inf for s , ( val , err ) in self . parallax . items ( ) : dist = pardict [ '{}_0' . format ( s ) ] [ 3 ] mod = 1. / dist * 1000. lnl += - 0.5 * ( val - mod ) ** 2 / err ** 2 if not np . isfinite ( lnl ) : self . _cache_val = - np . inf return - np . inf self . _cache_val = lnl return lnl
takes parameter vector constructs pardict returns sum of lnlikes of non - leaf nodes
21,960
def _find_closest ( self , n0 ) : dmin = np . inf nclose = None ds = [ ] nodes = [ ] ds . append ( np . inf ) nodes . append ( self ) for n in self : if n is n0 : continue try : if n . _in_same_observation ( n0 ) : continue ds . append ( n . distance ( n0 ) ) nodes . append ( n ) except AttributeError : pass inds = np . argsort ( ds ) ds = [ ds [ i ] for i in inds ] nodes = [ nodes [ i ] for i in inds ] for d , n in zip ( ds , nodes ) : try : if d < n . resolution or n . resolution == - 1 : return n except AttributeError : pass return self
returns the node in the tree that is closest to n0 but not in the same observation
21,961
def q_prior ( q , m = 1 , gamma = 0.3 , qmin = 0.1 ) : if q < qmin or q > 1 : return 0 C = 1 / ( 1 / ( gamma + 1 ) * ( 1 - qmin ** ( gamma + 1 ) ) ) return C * q ** gamma
Default prior on mass ratio q ~ q^gamma
21,962
def _clean_props ( self ) : remove = [ ] for p in self . properties . keys ( ) : if not hasattr ( self . ic , p ) and p not in self . ic . bands and p not in [ 'parallax' , 'feh' , 'age' , 'mass_B' , 'mass_C' ] and not re . search ( 'delta_' , p ) : remove . append ( p ) for p in remove : del self . properties [ p ] if len ( remove ) > 0 : logging . warning ( 'Properties removed from Model because ' + 'not present in {}: {}' . format ( type ( self . ic ) , remove ) ) remove = [ ] for p in self . properties . keys ( ) : try : val = self . properties [ p ] [ 0 ] if not np . isfinite ( val ) : remove . append ( p ) except : pass for p in remove : del self . properties [ p ] if len ( remove ) > 0 : logging . warning ( 'Properties removed from Model because ' + 'value is nan or inf: {}' . format ( remove ) ) self . _props_cleaned = True
Makes sure all properties are legit for isochrone .
21,963
def add_props ( self , ** kwargs ) : for kw , val in kwargs . iteritems ( ) : self . properties [ kw ] = val
Adds observable properties to self . properties .
21,964
def remove_props ( self , * args ) : for arg in args : if arg in self . properties : del self . properties [ arg ]
Removes desired properties from self . properties .
21,965
def fit_for_distance ( self ) : for prop in self . properties . keys ( ) : if prop in self . ic . bands : return True return False
True if any of the properties are apparent magnitudes .
21,966
def lnlike ( self , p ) : if not self . _props_cleaned : self . _clean_props ( ) if not self . use_emcee : fit_for_distance = True mass , age , feh , dist , AV = ( p [ 0 ] , p [ 1 ] , p [ 2 ] , p [ 3 ] , p [ 4 ] ) else : if len ( p ) == 5 : fit_for_distance = True mass , age , feh , dist , AV = p elif len ( p ) == 3 : fit_for_distance = False mass , age , feh = p if mass < self . ic . minmass or mass > self . ic . maxmass or age < self . ic . minage or age > self . ic . maxage or feh < self . ic . minfeh or feh > self . ic . maxfeh : return - np . inf if fit_for_distance : if dist < 0 or AV < 0 or dist > self . max_distance : return - np . inf if AV > self . maxAV : return - np . inf if self . min_logg is not None : logg = self . ic . logg ( mass , age , feh ) if logg < self . min_logg : return - np . inf logl = 0 for prop in self . properties . keys ( ) : try : val , err = self . properties [ prop ] except TypeError : continue if prop in self . ic . bands : if not fit_for_distance : raise ValueError ( 'must fit for mass, age, feh, dist, A_V if apparent magnitudes provided.' ) mod = self . ic . mag [ prop ] ( mass , age , feh ) + 5 * np . log10 ( dist ) - 5 A = AV * EXTINCTION [ prop ] mod += A elif re . search ( 'delta_' , prop ) : continue elif prop == 'feh' : mod = feh elif prop == 'parallax' : mod = 1. / dist * 1000 else : mod = getattr ( self . ic , prop ) ( mass , age , feh ) logl += - ( val - mod ) ** 2 / ( 2 * err ** 2 ) + np . log ( 1 / ( err * np . sqrt ( 2 * np . pi ) ) ) if np . isnan ( logl ) : logl = - np . inf return logl
Log - likelihood of model at given parameters
21,967
def lnprior ( self , mass , age , feh , distance = None , AV = None , use_local_fehprior = True ) : mass_prior = salpeter_prior ( mass ) if mass_prior == 0 : mass_lnprior = - np . inf else : mass_lnprior = np . log ( mass_prior ) if np . isnan ( mass_lnprior ) : logging . warning ( 'mass prior is nan at {}' . format ( mass ) ) age_lnprior = np . log ( age * ( 2 / ( self . ic . maxage ** 2 - self . ic . minage ** 2 ) ) ) if np . isnan ( age_lnprior ) : logging . warning ( 'age prior is nan at {}' . format ( age ) ) if use_local_fehprior : fehdist = local_fehdist ( feh ) else : fehdist = 1 / ( self . ic . maxfeh - self . ic . minfeh ) feh_lnprior = np . log ( fehdist ) if np . isnan ( feh_lnprior ) : logging . warning ( 'feh prior is nan at {}' . format ( feh ) ) if distance is not None : if distance <= 0 : distance_lnprior = - np . inf else : distance_lnprior = np . log ( 3 / self . max_distance ** 3 * distance ** 2 ) else : distance_lnprior = 0 if np . isnan ( distance_lnprior ) : logging . warning ( 'distance prior is nan at {}' . format ( distance ) ) if AV is not None : AV_lnprior = np . log ( 1 / self . maxAV ) else : AV_lnprior = 0 if np . isnan ( AV_lnprior ) : logging . warning ( 'AV prior is nan at {}' . format ( AV ) ) lnprior = ( mass_lnprior + age_lnprior + feh_lnprior + distance_lnprior + AV_lnprior ) return lnprior
log - prior for model parameters
21,968
def triangle_plots ( self , basename = None , format = 'png' , ** kwargs ) : if self . fit_for_distance : fig1 = self . triangle ( plot_datapoints = False , params = [ 'mass' , 'radius' , 'Teff' , 'logg' , 'feh' , 'age' , 'distance' , 'AV' ] , ** kwargs ) else : fig1 = self . triangle ( plot_datapoints = False , params = [ 'mass' , 'radius' , 'Teff' , 'feh' , 'age' ] , ** kwargs ) if basename is not None : plt . savefig ( '{}_physical.{}' . format ( basename , format ) ) plt . close ( ) fig2 = self . prop_triangle ( ** kwargs ) if basename is not None : plt . savefig ( '{}_observed.{}' . format ( basename , format ) ) plt . close ( ) return fig1 , fig2
Returns two triangle plots one with physical params one observational
21,969
def prop_triangle ( self , ** kwargs ) : truths = [ ] params = [ ] for p in self . properties : try : val , err = self . properties [ p ] except : continue if p in self . ic . bands : params . append ( '{}_mag' . format ( p ) ) truths . append ( val ) elif p == 'parallax' : params . append ( 'distance' ) truths . append ( 1 / ( val / 1000. ) ) else : params . append ( p ) truths . append ( val ) return self . triangle ( params , truths = truths , ** kwargs )
Makes corner plot of only observable properties .
21,970
def prop_samples ( self , prop , return_values = True , conf = 0.683 ) : samples = self . samples [ prop ] . values if return_values : sorted = np . sort ( samples ) med = np . median ( samples ) n = len ( samples ) lo_ind = int ( n * ( 0.5 - conf / 2 ) ) hi_ind = int ( n * ( 0.5 + conf / 2 ) ) lo = med - sorted [ lo_ind ] hi = sorted [ hi_ind ] - med return samples , ( med , lo , hi ) else : return samples
Returns samples of given property based on MCMC sampling
21,971
def plot_samples ( self , prop , fig = None , label = True , histtype = 'step' , bins = 50 , lw = 3 , ** kwargs ) : setfig ( fig ) samples , stats = self . prop_samples ( prop ) fig = plt . hist ( samples , bins = bins , normed = True , histtype = histtype , lw = lw , ** kwargs ) plt . xlabel ( prop ) plt . ylabel ( 'Normalized count' ) if label : med , lo , hi = stats plt . annotate ( '$%.2f^{+%.2f}_{-%.2f}$' % ( med , hi , lo ) , xy = ( 0.7 , 0.8 ) , xycoords = 'axes fraction' , fontsize = 20 ) return fig
Plots histogram of samples of desired property .
21,972
def get_band ( cls , b , ** kwargs ) : phot = None if b in [ 'u' , 'g' , 'r' , 'i' , 'z' ] : phot = 'SDSSugriz' band = 'sdss_{}' . format ( b ) elif b in [ 'U' , 'B' , 'V' , 'R' , 'I' , 'J' , 'H' , 'Ks' ] : phot = 'UBVRIJHKsKp' band = b elif b == 'K' : phot = 'UBVRIJHKsKp' band = 'Ks' elif b in [ 'kep' , 'Kepler' , 'Kp' ] : phot = 'UBVRIJHKsKp' band = 'Kp' elif b in [ 'W1' , 'W2' , 'W3' , 'W4' ] : phot = 'WISE' band = b elif re . match ( 'uvf' , b ) or re . match ( 'irf' , b ) : phot = 'HST_WFC3' band = b else : m = re . match ( '([a-zA-Z]+)_([a-zA-Z_]+)' , b ) if m : if m . group ( 1 ) in cls . phot_systems : phot = m . group ( 1 ) if phot == 'LSST' : band = b else : band = m . group ( 2 ) elif m . group ( 1 ) in [ 'UK' , 'UKIRT' ] : phot = 'UKIDSS' band = m . group ( 2 ) if phot is None : raise ValueError ( 'Dartmouth Models cannot resolve band {}!' . format ( b ) ) return phot , band
Defines what a shortcut band name refers to .
21,973
def searchsorted ( arr , N , x ) : L = 0 R = N - 1 done = False m = ( L + R ) // 2 while not done : if arr [ m ] < x : L = m + 1 elif arr [ m ] > x : R = m - 1 elif arr [ m ] == x : done = True m = ( L + R ) // 2 if L > R : done = True return L
N is length of arr
21,974
def wrap_flask_restful_resource ( fun : Callable , flask_restful_api : FlaskRestfulApi , injector : Injector ) -> Callable : @ functools . wraps ( fun ) def wrapper ( * args : Any , ** kwargs : Any ) -> Any : resp = fun ( * args , ** kwargs ) if isinstance ( resp , Response ) : return resp data , code , headers = flask_response_unpack ( resp ) return flask_restful_api . make_response ( data , code , headers = headers ) return wrapper
This is needed because of how flask_restful views are registered originally .
21,975
def complete_url ( self , url ) : if self . base_url : return urlparse . urljoin ( self . base_url , url ) else : return url
Completes a given URL with this instance s URL base .
21,976
def interact ( self , ** local ) : import code code . interact ( local = dict ( sess = self , ** local ) )
Drops the user into an interactive Python session with the sess variable set to the current session instance . If keyword arguments are supplied these names will also be available within the session .
21,977
def wait_for ( self , condition , interval = DEFAULT_WAIT_INTERVAL , timeout = DEFAULT_WAIT_TIMEOUT ) : start = time . time ( ) while True : res = condition ( ) if res : return res if time . time ( ) - start > timeout : break time . sleep ( interval ) raise WaitTimeoutError ( "wait_for timed out" )
Wait until a condition holds by checking it in regular intervals . Raises WaitTimeoutError on timeout .
21,978
def wait_while ( self , condition , * args , ** kw ) : return self . wait_for ( lambda : not condition ( ) , * args , ** kw )
Wait while a condition holds .
21,979
def at_css ( self , css , timeout = DEFAULT_AT_TIMEOUT , ** kw ) : return self . wait_for_safe ( lambda : super ( WaitMixin , self ) . at_css ( css ) , timeout = timeout , ** kw )
Returns the first node matching the given CSSv3 expression or None if a timeout occurs .
21,980
def at_xpath ( self , xpath , timeout = DEFAULT_AT_TIMEOUT , ** kw ) : return self . wait_for_safe ( lambda : super ( WaitMixin , self ) . at_xpath ( xpath ) , timeout = timeout , ** kw )
Returns the first node matching the given XPath 2 . 0 expression or None if a timeout occurs .
21,981
def switch_axis_limits ( ax , which_axis ) : for a in which_axis : assert a in ( 'x' , 'y' ) ax_limits = ax . axis ( ) if a == 'x' : ax . set_xlim ( ax_limits [ 1 ] , ax_limits [ 0 ] ) else : ax . set_ylim ( ax_limits [ 3 ] , ax_limits [ 2 ] )
Switch the axis limits of either x or y . Or both!
21,982
def remove_chartjunk ( ax , spines , grid = None , ticklabels = None , show_ticks = False , xkcd = False ) : all_spines = [ 'top' , 'bottom' , 'right' , 'left' , 'polar' ] for spine in spines : try : ax . spines [ spine ] . set_visible ( False ) except KeyError : pass if not xkcd : for spine in set ( all_spines ) . difference ( set ( spines ) ) : try : ax . spines [ spine ] . set_linewidth ( 0.5 ) except KeyError : pass x_pos = set ( [ 'top' , 'bottom' ] ) y_pos = set ( [ 'left' , 'right' ] ) xy_pos = [ x_pos , y_pos ] xy_ax_names = [ 'xaxis' , 'yaxis' ] for ax_name , pos in zip ( xy_ax_names , xy_pos ) : axis = ax . __dict__ [ ax_name ] if show_ticks or axis . get_scale ( ) == 'log' : for p in pos . difference ( spines ) : axis . set_tick_params ( direction = 'out' ) axis . set_ticks_position ( p ) else : axis . set_ticks_position ( 'none' ) if grid is not None : for g in grid : assert g in ( 'x' , 'y' ) ax . grid ( axis = grid , color = 'white' , linestyle = '-' , linewidth = 0.5 ) if ticklabels is not None : if type ( ticklabels ) is str : assert ticklabels in set ( ( 'x' , 'y' ) ) if ticklabels == 'x' : ax . set_xticklabels ( [ ] ) if ticklabels == 'y' : ax . set_yticklabels ( [ ] ) else : assert set ( ticklabels ) | set ( ( 'x' , 'y' ) ) > 0 if 'x' in ticklabels : ax . set_xticklabels ( [ ] ) elif 'y' in ticklabels : ax . set_yticklabels ( [ ] )
Removes chartjunk such as extra lines of axes and tick marks .
21,983
def maybe_get_ax ( * args , ** kwargs ) : if 'ax' in kwargs : ax = kwargs . pop ( 'ax' ) elif len ( args ) == 0 : fig = plt . gcf ( ) ax = plt . gca ( ) elif isinstance ( args [ 0 ] , mpl . axes . Axes ) : ax = args [ 0 ] args = args [ 1 : ] else : ax = plt . gca ( ) return ax , args , dict ( kwargs )
It used to be that the first argument of prettyplotlib had to be the ax object but that s not the case anymore .
21,984
def maybe_get_fig_ax ( * args , ** kwargs ) : if 'ax' in kwargs : ax = kwargs . pop ( 'ax' ) if 'fig' in kwargs : fig = kwargs . pop ( 'fig' ) else : fig = plt . gcf ( ) elif len ( args ) == 0 : fig = plt . gcf ( ) ax = plt . gca ( ) elif isinstance ( args [ 0 ] , mpl . figure . Figure ) and isinstance ( args [ 1 ] , mpl . axes . Axes ) : fig = args [ 0 ] ax = args [ 1 ] args = args [ 2 : ] else : fig , ax = plt . subplots ( 1 ) return fig , ax , args , dict ( kwargs )
It used to be that the first argument of prettyplotlib had to be the ax object but that s not the case anymore . This is specially made for pcolormesh .
21,985
def scatter ( * args , ** kwargs ) : ax , args , kwargs = utils . maybe_get_ax ( * args , ** kwargs ) if 'color' not in kwargs : color_cycle = ax . _get_lines . color_cycle kwargs [ 'color' ] = next ( color_cycle ) kwargs . setdefault ( 'edgecolor' , almost_black ) kwargs . setdefault ( 'alpha' , 0.5 ) lw = utils . maybe_get_linewidth ( ** kwargs ) kwargs [ 'lw' ] = lw show_ticks = kwargs . pop ( 'show_ticks' , False ) scatterpoints = ax . scatter ( * args , ** kwargs ) utils . remove_chartjunk ( ax , [ 'top' , 'right' ] , show_ticks = show_ticks ) return scatterpoints
This will plot a scatterplot of x and y iterating over the ColorBrewer Set2 color cycle unless a color is specified . The symbols produced are empty circles with the outline in the color specified by either color or edgecolor . If you want to fill the circle specify facecolor .
21,986
def boxplot ( * args , ** kwargs ) : ax , args , kwargs = maybe_get_ax ( * args , ** kwargs ) xticklabels = kwargs . pop ( 'xticklabels' , None ) fontsize = kwargs . pop ( 'fontsize' , 10 ) kwargs . setdefault ( 'widths' , 0.15 ) bp = ax . boxplot ( * args , ** kwargs ) if xticklabels : ax . xaxis . set_ticklabels ( xticklabels , fontsize = fontsize ) show_caps = kwargs . pop ( 'show_caps' , True ) show_ticks = kwargs . pop ( 'show_ticks' , False ) remove_chartjunk ( ax , [ 'top' , 'right' , 'bottom' ] , show_ticks = show_ticks ) linewidth = 0.75 blue = colors . set1 [ 1 ] red = colors . set1 [ 0 ] plt . setp ( bp [ 'boxes' ] , color = blue , linewidth = linewidth ) plt . setp ( bp [ 'medians' ] , color = red ) plt . setp ( bp [ 'whiskers' ] , color = blue , linestyle = 'solid' , linewidth = linewidth ) plt . setp ( bp [ 'fliers' ] , color = blue ) if show_caps : plt . setp ( bp [ 'caps' ] , color = blue , linewidth = linewidth ) else : plt . setp ( bp [ 'caps' ] , color = 'none' ) ax . spines [ 'left' ] . _linewidth = 0.5 return bp
Create a box - and - whisker plot showing the mean 25th percentile and 75th percentile . The difference from matplotlib is only the left axis line is shown and ticklabels labeling each category of data can be added .
21,987
def hist ( * args , ** kwargs ) : ax , args , kwargs = maybe_get_ax ( * args , ** kwargs ) color_cycle = ax . _get_lines . color_cycle if iterable ( args [ 0 ] ) : if isinstance ( args [ 0 ] , list ) : ncolors = len ( args [ 0 ] ) else : if len ( args [ 0 ] . shape ) == 2 : ncolors = args [ 0 ] . shape [ 1 ] else : ncolors = 1 kwargs . setdefault ( 'color' , [ next ( color_cycle ) for _ in range ( ncolors ) ] ) else : kwargs . setdefault ( 'color' , next ( color_cycle ) ) kwargs . setdefault ( 'edgecolor' , 'white' ) show_ticks = kwargs . pop ( 'show_ticks' , False ) grid = kwargs . pop ( 'grid' , None ) patches = ax . hist ( * args , ** kwargs ) remove_chartjunk ( ax , [ 'top' , 'right' ] , grid = grid , show_ticks = show_ticks ) return patches
Plots a histogram of the provided data . Can provide optional argument grid = x or grid = y to draw a white grid over the histogram . Almost like erasing some of the plot but it adds more information!
21,988
def beeswarm ( * args , ** kwargs ) : ax , args , kwargs = maybe_get_ax ( * args , ** kwargs ) xticklabels = kwargs . pop ( 'xticklabels' , None ) colors = kwargs . pop ( 'colors' , None ) fontsize = kwargs . pop ( 'fontsize' , 10 ) gray = _colors . set1 [ 8 ] red = _colors . set1 [ 0 ] blue = kwargs . pop ( 'color' , _colors . set1 [ 1 ] ) kwargs . setdefault ( 'widths' , 0.25 ) kwargs . setdefault ( 'sym' , "o" ) bp = _beeswarm ( ax , * args , ** kwargs ) kwargs . setdefault ( "median_color" , gray ) kwargs . setdefault ( "median_linewidth" , 2 ) if xticklabels : ax . xaxis . set_ticklabels ( xticklabels , fontsize = fontsize ) show_caps = kwargs . pop ( 'show_caps' , True ) show_ticks = kwargs . pop ( 'show_ticks' , False ) remove_chartjunk ( ax , [ 'top' , 'right' , 'bottom' ] , show_ticks = show_ticks ) linewidth = 0.75 plt . setp ( bp [ 'boxes' ] , color = blue , linewidth = linewidth ) plt . setp ( bp [ 'medians' ] , color = kwargs . pop ( "median_color" ) , linewidth = kwargs . pop ( "median_linewidth" ) ) for color , flier in zip ( colors , bp [ 'fliers' ] ) : plt . setp ( flier , color = color ) ax . spines [ 'left' ] . _linewidth = 0.5 return bp
Create a R - like beeswarm plot showing the mean and datapoints . The difference from matplotlib is only the left axis line is shown and ticklabels labeling each category of data can be added .
21,989
def tags ( self ) : if self . _tags is None : LOG . debug ( 'need to build tags' ) self . _tags = { } if hasattr ( self . Meta , 'tags_spec' ) and ( self . Meta . tags_spec is not None ) : LOG . debug ( 'have a tags_spec' ) method , path , param_name , param_value = self . Meta . tags_spec [ : 4 ] kwargs = { } filter_type = getattr ( self . Meta , 'filter_type' , None ) if filter_type == 'arn' : kwargs = { param_name : [ getattr ( self , param_value ) ] } elif filter_type == 'list' : kwargs = { param_name : [ getattr ( self , param_value ) ] } else : kwargs = { param_name : getattr ( self , param_value ) } if len ( self . Meta . tags_spec ) > 4 : kwargs . update ( self . Meta . tags_spec [ 4 ] ) LOG . debug ( 'fetching tags' ) self . data [ 'Tags' ] = self . _client . call ( method , query = path , ** kwargs ) LOG . debug ( self . data [ 'Tags' ] ) if 'Tags' in self . data : _tags = self . data [ 'Tags' ] if isinstance ( _tags , list ) : for kvpair in _tags : if kvpair [ 'Key' ] in self . _tags : if not isinstance ( self . _tags [ kvpair [ 'Key' ] ] , list ) : self . _tags [ kvpair [ 'Key' ] ] = [ self . _tags [ kvpair [ 'Key' ] ] ] self . _tags [ kvpair [ 'Key' ] ] . append ( kvpair [ 'Value' ] ) else : self . _tags [ kvpair [ 'Key' ] ] = kvpair [ 'Value' ] elif isinstance ( _tags , dict ) : self . _tags = _tags return self . _tags
Convert the ugly Tags JSON into a real dictionary and memorize the result .
21,990
def get_metric_data ( self , metric_name = None , metric = None , days = None , hours = 1 , minutes = None , statistics = None , period = None ) : if not statistics : statistics = [ 'Average' ] if days : delta = datetime . timedelta ( days = days ) elif hours : delta = datetime . timedelta ( hours = hours ) else : delta = datetime . timedelta ( minutes = minutes ) if not period : period = max ( 60 , self . _total_seconds ( delta ) // 1440 ) if not metric : metric = self . find_metric ( metric_name ) if metric and self . _cloudwatch : end = datetime . datetime . utcnow ( ) start = end - delta data = self . _cloudwatch . call ( 'get_metric_statistics' , Dimensions = metric [ 'Dimensions' ] , Namespace = metric [ 'Namespace' ] , MetricName = metric [ 'MetricName' ] , StartTime = start . isoformat ( ) , EndTime = end . isoformat ( ) , Statistics = statistics , Period = period ) return MetricData ( jmespath . search ( 'Datapoints' , data ) , period ) else : raise ValueError ( 'Metric (%s) not available' % metric_name )
Get metric data for this resource . You can specify the time frame for the data as either the number of days or number of hours . The maximum window is 14 days . Based on the time frame this method will calculate the correct period to return the maximum number of data points up to the CloudWatch max of 1440 .
21,991
def fit ( self ) : r for distribution in self . distributions : try : dist = eval ( "scipy.stats." + distribution ) param = self . _timed_run ( dist . fit , distribution , args = self . _data ) pdf_fitted = dist . pdf ( self . x , * param ) self . fitted_param [ distribution ] = param [ : ] self . fitted_pdf [ distribution ] = pdf_fitted sq_error = pylab . sum ( ( self . fitted_pdf [ distribution ] - self . y ) ** 2 ) if self . verbose : print ( "Fitted {} distribution with error={})" . format ( distribution , sq_error ) ) self . _fitted_errors [ distribution ] = sq_error except Exception as err : if self . verbose : print ( "SKIPPED {} distribution (taking more than {} seconds)" . format ( distribution , self . timeout ) ) self . _fitted_errors [ distribution ] = 1e6 self . df_errors = pd . DataFrame ( { 'sumsquare_error' : self . _fitted_errors } )
r Loop over distributions and find best parameter to fit the data for each
21,992
def plot_pdf ( self , names = None , Nbest = 5 , lw = 2 ) : assert Nbest > 0 if Nbest > len ( self . distributions ) : Nbest = len ( self . distributions ) if isinstance ( names , list ) : for name in names : pylab . plot ( self . x , self . fitted_pdf [ name ] , lw = lw , label = name ) elif names : pylab . plot ( self . x , self . fitted_pdf [ names ] , lw = lw , label = names ) else : try : names = self . df_errors . sort_values ( by = "sumsquare_error" ) . index [ 0 : Nbest ] except : names = self . df_errors . sort ( "sumsquare_error" ) . index [ 0 : Nbest ] for name in names : if name in self . fitted_pdf . keys ( ) : pylab . plot ( self . x , self . fitted_pdf [ name ] , lw = lw , label = name ) else : print ( "%s was not fitted. no parameters available" % name ) pylab . grid ( True ) pylab . legend ( )
Plots Probability density functions of the distributions
21,993
def get_best ( self ) : name = self . df_errors . sort_values ( 'sumsquare_error' ) . iloc [ 0 ] . name params = self . fitted_param [ name ] return { name : params }
Return best fitted distribution and its parameters
21,994
def summary ( self , Nbest = 5 , lw = 2 , plot = True ) : if plot : pylab . clf ( ) self . hist ( ) self . plot_pdf ( Nbest = Nbest , lw = lw ) pylab . grid ( True ) Nbest = min ( Nbest , len ( self . distributions ) ) try : names = self . df_errors . sort_values ( by = "sumsquare_error" ) . index [ 0 : Nbest ] except : names = self . df_errors . sort ( "sumsquare_error" ) . index [ 0 : Nbest ] return self . df_errors . loc [ names ]
Plots the distribution of the data and Nbest distribution
21,995
def _timed_run ( self , func , distribution , args = ( ) , kwargs = { } , default = None ) : class InterruptableThread ( threading . Thread ) : def __init__ ( self ) : threading . Thread . __init__ ( self ) self . result = default self . exc_info = ( None , None , None ) def run ( self ) : try : self . result = func ( args , ** kwargs ) except Exception as err : self . exc_info = sys . exc_info ( ) def suicide ( self ) : raise RuntimeError ( 'Stop has been called' ) it = InterruptableThread ( ) it . start ( ) started_at = datetime . now ( ) it . join ( self . timeout ) ended_at = datetime . now ( ) diff = ended_at - started_at if it . exc_info [ 0 ] is not None : a , b , c = it . exc_info raise Exception ( a , b , c ) if it . isAlive ( ) : it . suicide ( ) raise RuntimeError else : return it . result
This function will spawn a thread and run the given function using the args kwargs and return the given default value if the timeout is exceeded .
21,996
def compute_avg_adj_deg ( G ) : r return np . sum ( np . dot ( G . A , G . A ) , axis = 1 ) / ( np . sum ( G . A , axis = 1 ) + 1. )
r Compute the average adjacency degree for each node .
21,997
def compute_spectrogram ( G , atom = None , M = 100 , ** kwargs ) : r if not atom : def atom ( x ) : return np . exp ( - M * ( x / G . lmax ) ** 2 ) scale = np . linspace ( 0 , G . lmax , M ) spectr = np . empty ( ( G . N , M ) ) for shift_idx in range ( M ) : shift_filter = filters . Filter ( G , lambda x : atom ( x - scale [ shift_idx ] ) ) tig = compute_norm_tig ( shift_filter , ** kwargs ) . squeeze ( ) ** 2 spectr [ : , shift_idx ] = tig G . spectr = spectr return spectr
r Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis .
21,998
def evaluate ( self , x ) : r x = np . asanyarray ( x ) y = np . empty ( [ self . Nf ] + list ( x . shape ) ) for i , kernel in enumerate ( self . _kernels ) : y [ i ] = kernel ( x ) return y
r Evaluate the kernels at given frequencies .
21,999
def estimate_frame_bounds ( self , x = None ) : r if x is None : x = np . linspace ( 0 , self . G . lmax , 1000 ) else : x = np . asanyarray ( x ) sum_filters = np . sum ( self . evaluate ( x ) ** 2 , axis = 0 ) return sum_filters . min ( ) , sum_filters . max ( )
r Estimate lower and upper frame bounds .