idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
5,300 | def calc_signal_spatial ( self ) : # Calculate the surface intensity self . surface_intensity_sparse = self . calc_surface_intensity ( ) # Calculate the probability per object-by-object level self . surface_intensity_object = self . kernel . pdf ( self . catalog . lon , self . catalog . lat ) # Spatial component of signal probability u_spatial = self . surface_intensity_object return u_spatial | Calculate the spatial signal probability for each catalog object . | 99 | 12 |
5,301 | def fit_richness ( self , atol = 1.e-3 , maxiter = 50 ) : # Check whether the signal probability for all objects are zero # This can occur for finite kernels on the edge of the survey footprint if np . isnan ( self . u ) . any ( ) : logger . warning ( "NaN signal probability found" ) return 0. , 0. , None if not np . any ( self . u ) : logger . warning ( "Signal probability is zero for all objects" ) return 0. , 0. , None if self . f == 0 : logger . warning ( "Observable fraction is zero" ) return 0. , 0. , None # Richness corresponding to 0, 1, and 10 observable stars richness = np . array ( [ 0. , 1. / self . f , 10. / self . f ] ) loglike = np . array ( [ self . value ( richness = r ) for r in richness ] ) found_maximum = False iteration = 0 while not found_maximum : parabola = ugali . utils . parabola . Parabola ( richness , 2. * loglike ) if parabola . vertex_x < 0. : found_maximum = True else : richness = np . append ( richness , parabola . vertex_x ) loglike = np . append ( loglike , self . value ( richness = richness [ - 1 ] ) ) if np . fabs ( loglike [ - 1 ] - np . max ( loglike [ 0 : - 1 ] ) ) < atol : found_maximum = True iteration += 1 if iteration > maxiter : logger . warning ( "Maximum number of iterations reached" ) break index = np . argmax ( loglike ) return loglike [ index ] , richness [ index ] , parabola | Maximize the log - likelihood as a function of richness . | 387 | 12 |
5,302 | def resolve_reference ( self , ref ) : url , resolved = self . resolver . resolve ( ref ) return resolved | Resolve a JSON Pointer object reference to the object itself . | 25 | 13 |
5,303 | def get_path ( self , path ) : mapping = self . get_path_mapping ( path ) return self . path_class ( api = self , path = path , mapping = mapping ) | Construct a Path object from a path string . | 42 | 9 |
5,304 | def from_file ( cls , filename ) : with open ( filename ) as infp : if filename . endswith ( '.yaml' ) or filename . endswith ( '.yml' ) : import yaml data = yaml . safe_load ( infp ) else : import json data = json . load ( infp ) return cls . from_data ( data ) | Construct an APIDefinition by parsing the given filename . | 83 | 12 |
5,305 | def _server_error_message ( url , message ) : msg = _error_message . format ( url = url , message = message ) log . error ( msg ) return msg | Log and return a server error message . | 38 | 8 |
5,306 | def make_request ( url , method = 'GET' , query = None , body = None , auth = None , timeout = 10 , client = None , macaroons = None ) : headers = { } kwargs = { 'timeout' : timeout , 'headers' : headers } # Handle the request body. if body is not None : if isinstance ( body , collections . Mapping ) : body = json . dumps ( body ) kwargs [ 'data' ] = body # Handle request methods. if method in ( 'GET' , 'HEAD' ) : if query : url = '{}?{}' . format ( url , urlencode ( query , True ) ) elif method in ( 'DELETE' , 'PATCH' , 'POST' , 'PUT' ) : headers [ 'Content-Type' ] = 'application/json' else : raise ValueError ( 'invalid method {}' . format ( method ) ) if macaroons is not None : headers [ 'Macaroons' ] = macaroons kwargs [ 'auth' ] = auth if client is None else client . auth ( ) api_method = getattr ( requests , method . lower ( ) ) # Perform the request. try : response = api_method ( url , * * kwargs ) except requests . exceptions . Timeout : raise timeout_error ( url , timeout ) except Exception as err : msg = _server_error_message ( url , err ) raise ServerError ( msg ) # Handle error responses. try : response . raise_for_status ( ) except HTTPError as err : msg = _server_error_message ( url , err . response . text ) raise ServerError ( err . response . status_code , msg ) except requests . exceptions . RequestException as err : msg = _server_error_message ( url , err . message ) raise ServerError ( msg ) # Some requests just result in a status with no response body. if not response . content : return { } # Assume the response body is a JSON encoded string. try : return response . json ( ) except Exception as err : msg = 'Error decoding JSON response: {} message: {}' . format ( url , err ) log . error ( msg ) raise ServerError ( msg ) | Make a request with the provided data . | 484 | 8 |
5,307 | def get_plans ( self , reference ) : response = make_request ( '{}charm?charm-url={}' . format ( self . url , 'cs:' + reference . path ( ) ) , timeout = self . timeout , client = self . _client ) try : return tuple ( map ( lambda plan : Plan ( url = plan [ 'url' ] , plan = plan [ 'plan' ] , created_on = datetime . datetime . strptime ( plan [ 'created-on' ] , "%Y-%m-%dT%H:%M:%SZ" ) , description = plan . get ( 'description' ) , price = plan . get ( 'price' ) ) , response ) ) except Exception as err : log . error ( 'cannot process plans: invalid JSON response: {!r}' . format ( response ) ) raise ServerError ( 'unable to get list of plans for {}: {}' . format ( reference . path ( ) , err ) ) | Get the plans for a given charm . | 220 | 8 |
5,308 | def list_wallets ( self ) : response = make_request ( '{}wallet' . format ( self . url ) , timeout = self . timeout , client = self . _client ) try : total = response [ 'total' ] return { 'credit' : response [ 'credit' ] , 'total' : WalletTotal ( limit = total [ 'limit' ] , budgeted = total [ 'budgeted' ] , available = total [ 'available' ] , unallocated = total [ 'unallocated' ] , usage = total [ 'usage' ] , consumed = total [ 'consumed' ] ) , 'wallets' : tuple ( Wallet ( owner = wallet [ 'owner' ] , wallet = wallet [ 'wallet' ] , limit = wallet [ 'limit' ] , budgeted = wallet [ 'budgeted' ] , unallocated = wallet [ 'unallocated' ] , available = wallet [ 'available' ] , consumed = wallet [ 'consumed' ] , default = 'default' in wallet ) for wallet in response [ 'wallets' ] ) , } except Exception as err : log . error ( 'cannot process wallets: invalid JSON response: {!r}' . format ( response ) ) raise ServerError ( 'unable to get list of wallets: {!r}' . format ( err ) ) | Get the list of wallets . | 287 | 6 |
5,309 | def get_wallet ( self , wallet_name ) : response = make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , timeout = self . timeout , client = self . _client ) try : total = response [ 'total' ] return { 'credit' : response [ 'credit' ] , 'limit' : response [ 'limit' ] , 'total' : WalletTotal ( limit = total [ 'limit' ] , budgeted = total [ 'budgeted' ] , available = total [ 'available' ] , unallocated = total [ 'unallocated' ] , usage = total [ 'usage' ] , consumed = total [ 'consumed' ] ) } except Exception as exc : log . error ( 'cannot get wallet from server: {!r}' . format ( exc ) ) raise ServerError ( 'unable to get list of wallets: {!r}' . format ( exc ) ) | Get a single wallet . | 206 | 5 |
5,310 | def update_wallet ( self , wallet_name , limit ) : request = { 'update' : { 'limit' : str ( limit ) , } } return make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , method = 'PATCH' , body = request , timeout = self . timeout , client = self . _client ) | Update a wallet with a new limit . | 82 | 8 |
5,311 | def delete_wallet ( self , wallet_name ) : return make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , method = 'DELETE' , timeout = self . timeout , client = self . _client ) | Delete a wallet . | 58 | 4 |
5,312 | def create_budget ( self , wallet_name , model_uuid , limit ) : request = { 'model' : model_uuid , 'limit' : limit , } return make_request ( '{}wallet/{}/budget' . format ( self . url , wallet_name ) , method = 'POST' , body = request , timeout = self . timeout , client = self . _client ) | Create a new budget for a model and wallet . | 88 | 10 |
5,313 | def delete_budget ( self , model_uuid ) : return make_request ( '{}model/{}/budget' . format ( self . url , model_uuid ) , method = 'DELETE' , timeout = self . timeout , client = self . _client ) | Delete a budget . | 62 | 4 |
5,314 | def confusion ( df , labels = [ 'neg' , 'pos' ] ) : c = pd . DataFrame ( np . zeros ( ( 2 , 2 ) ) , dtype = int ) a , b = df . columns [ : 2 ] # labels[df.columns[:2]] c . columns = sorted ( set ( df [ a ] ) ) [ : 2 ] c . columns . name = a c . index = list ( c . columns ) c . index . name = b c1 , c2 = c . columns c [ c1 ] [ c1 ] = ( ( df [ a ] == c1 ) & ( df [ b ] == c1 ) ) . sum ( ) c [ c1 ] [ c2 ] = ( ( df [ a ] == c1 ) & ( df [ b ] == c2 ) ) . sum ( ) c [ c2 ] [ c2 ] = ( ( df [ a ] == c2 ) & ( df [ b ] == c2 ) ) . sum ( ) c [ c2 ] [ c1 ] = ( ( df [ a ] == c2 ) & ( df [ b ] == c1 ) ) . sum ( ) return c | Binary classification confusion | 258 | 4 |
5,315 | def thresh_from_spec ( spec , labels , scores , * * kwargs ) : cost_fun . verbose = kwargs . pop ( 'verbose' , cost_fun . verbose ) cost_fun . target = spec return minimize ( cost_fun , x0 = [ .5 ] , args = ( labels , scores ) , method = 'SLSQP' , constraints = ( { 'type' : 'ineq' , 'fun' : lambda x : np . array ( [ x [ 0 ] ] ) , 'jac' : lambda x : np . array ( [ 1. ] ) } , ) , * * kwargs ) | r Find the threshold level that accomplishes the desired specificity | 143 | 11 |
5,316 | def add_dicts ( d1 , d2 ) : if d1 is None : return d2 if d2 is None : return d1 keys = set ( d1 ) keys . update ( set ( d2 ) ) ret = { } for key in keys : v1 = d1 . get ( key ) v2 = d2 . get ( key ) if v1 is None : ret [ key ] = v2 elif v2 is None : ret [ key ] = v1 else : ret [ key ] = v1 + v2 return ret | Merge two dicts of addable values | 118 | 9 |
5,317 | def _update_capacity ( self , data ) : if 'ConsumedCapacity' in data : # This is all for backwards compatibility consumed = data [ 'ConsumedCapacity' ] if not isinstance ( consumed , list ) : consumed = [ consumed ] for cap in consumed : self . capacity += cap . get ( 'CapacityUnits' , 0 ) self . table_capacity += cap . get ( 'Table' , { } ) . get ( 'CapacityUnits' , 0 ) local_indexes = cap . get ( 'LocalSecondaryIndexes' , { } ) for k , v in six . iteritems ( local_indexes ) : self . indexes . setdefault ( k , 0 ) self . indexes [ k ] += v [ 'CapacityUnits' ] global_indexes = cap . get ( 'GlobalSecondaryIndexes' , { } ) for k , v in six . iteritems ( global_indexes ) : self . global_indexes . setdefault ( k , 0 ) self . global_indexes [ k ] += v [ 'CapacityUnits' ] | Update the consumed capacity metrics | 237 | 5 |
5,318 | def fetch ( self ) : self . limit . set_request_args ( self . kwargs ) data = self . connection . call ( * self . args , * * self . kwargs ) self . limit . post_fetch ( data ) self . last_evaluated_key = data . get ( 'LastEvaluatedKey' ) if self . last_evaluated_key is None : self . kwargs . pop ( 'ExclusiveStartKey' , None ) else : self . kwargs [ 'ExclusiveStartKey' ] = self . last_evaluated_key self . _update_capacity ( data ) if 'consumed_capacity' in data : self . consumed_capacity += data [ 'consumed_capacity' ] for raw_item in data [ 'Items' ] : item = self . connection . dynamizer . decode_keys ( raw_item ) if self . limit . accept ( item ) : yield item | Fetch more results from Dynamo | 203 | 6 |
5,319 | def build_kwargs ( self ) : keys , self . keys = self . keys [ : MAX_GET_BATCH ] , self . keys [ MAX_GET_BATCH : ] query = { 'ConsistentRead' : self . consistent } if self . attributes is not None : query [ 'ProjectionExpression' ] = self . attributes if self . alias : query [ 'ExpressionAttributeNames' ] = self . alias query [ 'Keys' ] = keys return { 'RequestItems' : { self . tablename : query , } , 'ReturnConsumedCapacity' : self . return_capacity , } | Construct the kwargs to pass to batch_get_item | 133 | 13 |
5,320 | def fetch ( self ) : kwargs = self . build_kwargs ( ) data = self . connection . call ( 'batch_get_item' , * * kwargs ) if 'UnprocessedKeys' in data : for items in six . itervalues ( data [ 'UnprocessedKeys' ] ) : self . keys . extend ( items [ 'Keys' ] ) # Getting UnprocessedKeys indicates that we are exceeding our # throughput. So sleep for a bit. self . _attempt += 1 self . connection . exponential_sleep ( self . _attempt ) else : # No UnprocessedKeys means our request rate is fine, so we can # reset the attempt number. self . _attempt = 0 self . _update_capacity ( data ) if 'consumed_capacity' in data : # Comes back as a list from BatchWriteItem self . consumed_capacity = sum ( data [ 'consumed_capacity' ] , self . consumed_capacity ) return iter ( data [ 'Responses' ] [ self . tablename ] ) | Fetch a set of items from their keys | 230 | 9 |
5,321 | def copy ( self ) : return Limit ( self . scan_limit , self . item_limit , self . min_scan_limit , self . strict , self . filter ) | Return a copy of the limit | 37 | 6 |
5,322 | def set_request_args ( self , args ) : if self . scan_limit is not None : args [ 'Limit' ] = self . scan_limit elif self . item_limit is not None : args [ 'Limit' ] = max ( self . item_limit , self . min_scan_limit ) else : args . pop ( 'Limit' , None ) | Set the Limit parameter into the request args | 80 | 8 |
5,323 | def complete ( self ) : if self . scan_limit is not None and self . scan_limit == 0 : return True if self . item_limit is not None and self . item_limit == 0 : return True return False | Return True if the limit has been reached | 48 | 8 |
5,324 | def accept ( self , item ) : accept = self . filter ( item ) if accept and self . item_limit is not None : if self . item_limit > 0 : self . item_limit -= 1 elif self . strict : return False return accept | Apply the filter and item_limit and return True to accept | 54 | 12 |
5,325 | def returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False | Generate a random walk and return True if the walker has returned to the origin after taking n steps . | 63 | 22 |
5,326 | def first_return ( ) : walk = randwalk ( ) >> drop ( 1 ) >> takewhile ( lambda v : v != Origin ) >> list return len ( walk ) | Generate a random walk and return its length upto the moment that the walker first returns to the origin . | 36 | 23 |
5,327 | def seq ( start = 0 , step = 1 ) : def seq ( a , d ) : while 1 : yield a a += d return seq ( start , step ) | An arithmetic sequence generator . Works with any type with + defined . | 35 | 13 |
5,328 | def pipe ( inpipe , outpipe ) : if hasattr ( outpipe , '__pipe__' ) : return outpipe . __pipe__ ( inpipe ) elif hasattr ( outpipe , '__call__' ) : return outpipe ( inpipe ) else : raise BrokenPipe ( 'No connection mechanism defined' ) | Connect inpipe and outpipe . If outpipe is not a Stream instance it should be an function callable on an iterable . | 71 | 27 |
5,329 | def submit ( self , * items ) : with self . lock : if self . closed : raise BrokenPipe ( 'Job submission has been closed.' ) id = self . jobcount self . _status += [ 'SUBMITTED' ] * len ( items ) self . jobcount += len ( items ) for item in items : self . waitqueue . put ( ( id , item ) ) id += 1 if len ( items ) == 1 : return id - 1 else : return range ( id - len ( items ) , id ) | Return job ids assigned to the submitted items . | 113 | 10 |
5,330 | def cancel ( self , * ids ) : ncancelled = 0 with self . lock : for id in ids : try : if self . _status [ id ] == 'SUBMITTED' : self . _status [ id ] = 'CANCELLED' ncancelled += 1 except IndexError : pass return ncancelled | Try to cancel jobs with associated ids . Return the actual number of jobs cancelled . | 76 | 17 |
5,331 | def shutdown ( self ) : with self . lock : self . pool . inqueue . put ( StopIteration ) # Stop the pool workers self . waitqueue . put ( StopIteration ) # Stop the input_feeder _iterqueue ( self . waitqueue ) >> item [ - 1 ] # Exhaust the waitqueue self . closed = True self . join ( ) | Shut down the Executor . Suspend all waiting jobs . Running workers will terminate after finishing their current job items . The call will block until all workers are terminated . | 78 | 33 |
5,332 | def main ( ) : arguments = docopt ( __doc__ , version = __version__ ) if arguments [ 'configure' ] and flag : configure ( ) if arguments [ 'cuisine' ] : if arguments [ 'list' ] : cuisine ( 'list' ) else : cuisine ( arguments [ '<cuisine-id>' ] ) elif arguments [ 'surprise' ] : surprise ( ) elif arguments [ 'reviews' ] : reviews ( arguments [ '<restaurant-id>' ] ) elif arguments [ 'search' ] : search ( arguments [ 'QUERY' ] ) elif arguments [ 'budget' ] : try : money = arguments [ '<budget>' ] money = float ( money ) budget ( money ) except : print 'Budget should be a number!' elif arguments [ 'restaurant' ] : restaurant ( arguments [ '<restaurant-id>' ] ) else : print ( __doc__ ) | monica helps you order food from the timeline | 206 | 9 |
5,333 | def _get_requirements ( fname ) : packages = _read ( fname ) . split ( '\n' ) packages = ( p . strip ( ) for p in packages ) packages = ( p for p in packages if p and not p . startswith ( '#' ) ) return list ( packages ) | Create a list of requirements from the output of the pip freeze command saved in a text file . | 68 | 19 |
5,334 | def TermsProcessor ( instance , placeholder , rendered_content , original_context ) : if 'terms' in original_context : return rendered_content return mark_safe ( replace_terms ( rendered_content ) ) | Adds links all placeholders plugins except django - terms plugins | 45 | 12 |
5,335 | def time_stops ( self ) : if not self . supports_time : return [ ] if self . service . calendar == 'standard' : units = self . service . time_interval_units interval = self . service . time_interval steps = [ self . time_start ] if units in ( 'years' , 'decades' , 'centuries' ) : if units == 'years' : years = interval elif units == 'decades' : years = 10 * interval else : years = 100 * interval next_value = lambda x : x . replace ( year = x . year + years ) elif units == 'months' : def _fn ( x ) : year = x . year + ( x . month + interval - 1 ) // 12 month = ( x . month + interval ) % 12 or 12 day = min ( x . day , calendar . monthrange ( year , month ) [ 1 ] ) return x . replace ( year = year , month = month , day = day ) next_value = _fn else : if units == 'milliseconds' : delta = timedelta ( milliseconds = interval ) elif units == 'seconds' : delta = timedelta ( seconds = interval ) elif units == 'minutes' : delta = timedelta ( minutes = interval ) elif units == 'hours' : delta = timedelta ( hours = interval ) elif units == 'days' : delta = timedelta ( days = interval ) elif units == 'weeks' : delta = timedelta ( weeks = interval ) else : raise ValidationError ( "Service has an invalid time_interval_units: {}" . format ( self . service . time_interval_units ) ) next_value = lambda x : x + delta while steps [ - 1 ] < self . time_end : value = next_value ( steps [ - 1 ] ) if value > self . time_end : break steps . append ( value ) return steps else : # TODO raise NotImplementedError | Valid time steps for this service as a list of datetime objects . | 427 | 14 |
5,336 | def _parse_coords ( self , opts ) : # The coordinates are mutually exclusive, so # shouldn't have to worry about over-writing them. if 'coords' in vars ( opts ) : return radius = vars ( opts ) . get ( 'radius' , 0 ) gal = None if vars ( opts ) . get ( 'gal' ) is not None : gal = opts . gal elif vars ( opts ) . get ( 'cel' ) is not None : gal = cel2gal ( * opts . cel ) elif vars ( opts ) . get ( 'hpx' ) is not None : gal = pix2ang ( * opts . hpx ) if gal is not None : opts . coords = [ ( gal [ 0 ] , gal [ 1 ] , radius ) ] opts . names = [ vars ( opts ) . get ( 'name' , '' ) ] else : opts . coords = None opts . names = None if vars ( opts ) . get ( 'targets' ) is not None : opts . names , opts . coords = self . parse_targets ( opts . targets ) if vars ( opts ) . get ( 'radius' ) is not None : opts . coords [ 'radius' ] = vars ( opts ) . get ( 'radius' ) | Parse target coordinates in various ways ... | 306 | 8 |
5,337 | def default_value ( self ) : if callable ( self . default ) and self . call_default : return self . default ( ) return self . default | Property to return the default value . | 33 | 7 |
5,338 | def raw_value ( self ) : if self . parent_setting is not None : return self . parent_setting . raw_value [ self . full_name ] else : return getattr ( settings , self . full_name ) | Property to return the variable defined in django . conf . settings . | 49 | 14 |
5,339 | def get_value ( self ) : try : value = self . raw_value except ( AttributeError , KeyError ) as err : self . _reraise_if_required ( err ) default_value = self . default_value if self . transform_default : return self . transform ( default_value ) return default_value else : return self . transform ( value ) | Return the transformed raw or default value . | 79 | 8 |
5,340 | def run_validators ( self , value ) : errors = [ ] for validator in self . validators : try : validator ( value ) except ValidationError as error : errors . extend ( error . messages ) if errors : raise ValidationError ( errors ) | Run the validators on the setting value . | 56 | 9 |
5,341 | def transform ( self , path ) : if path is None or not path : return None obj_parent_modules = path . split ( "." ) objects = [ obj_parent_modules . pop ( - 1 ) ] while True : try : parent_module_path = "." . join ( obj_parent_modules ) parent_module = importlib . import_module ( parent_module_path ) break except ImportError : if len ( obj_parent_modules ) == 1 : raise ImportError ( "No module named '%s'" % obj_parent_modules [ 0 ] ) objects . insert ( 0 , obj_parent_modules . pop ( - 1 ) ) current_object = parent_module for obj in objects : current_object = getattr ( current_object , obj ) return current_object | Transform a path into an actual Python object . | 171 | 9 |
5,342 | def get_value ( self ) : try : self . raw_value except ( AttributeError , KeyError ) as err : self . _reraise_if_required ( err ) default_value = self . default_value if self . transform_default : return self . transform ( default_value ) return default_value else : # If setting is defined, load values of all subsettings. value = { } for key , subsetting in self . settings . items ( ) : value [ key ] = subsetting . get_value ( ) return value | Return dictionary with values of subsettings . | 116 | 8 |
5,343 | def sum_mags ( mags , weights = None ) : flux = 10 ** ( - np . asarray ( mags ) / 2.5 ) if weights is None : return - 2.5 * np . log10 ( np . sum ( flux ) ) else : return - 2.5 * np . log10 ( np . sum ( weights * flux ) ) | Sum an array of magnitudes in flux space . | 78 | 10 |
5,344 | def absolute_magnitude ( distance_modulus , g , r , prob = None ) : V = g - 0.487 * ( g - r ) - 0.0249 flux = np . sum ( 10 ** ( - ( V - distance_modulus ) / 2.5 ) ) Mv = - 2.5 * np . log10 ( flux ) return Mv | Calculate the absolute magnitude from a set of bands | 81 | 11 |
5,345 | def observableFractionCDF ( self , mask , distance_modulus , mass_min = 0.1 ) : method = 'step' mass_init , mass_pdf , mass_act , mag_1 , mag_2 = self . sample ( mass_min = mass_min , full_data_range = False ) mag_1 = mag_1 + distance_modulus mag_2 = mag_2 + distance_modulus mask_1 , mask_2 = mask . mask_roi_unique . T mag_err_1 = mask . photo_err_1 ( mask_1 [ : , np . newaxis ] - mag_1 ) mag_err_2 = mask . photo_err_2 ( mask_2 [ : , np . newaxis ] - mag_2 ) # "upper" bound set by maglim delta_hi_1 = ( mask_1 [ : , np . newaxis ] - mag_1 ) / mag_err_1 delta_hi_2 = ( mask_2 [ : , np . newaxis ] - mag_2 ) / mag_err_2 # "lower" bound set by bins_mag (maglim shouldn't be 0) delta_lo_1 = ( mask . roi . bins_mag [ 0 ] - mag_1 ) / mag_err_1 delta_lo_2 = ( mask . roi . bins_mag [ 0 ] - mag_2 ) / mag_err_2 cdf_1 = norm_cdf ( delta_hi_1 ) - norm_cdf ( delta_lo_1 ) cdf_2 = norm_cdf ( delta_hi_2 ) - norm_cdf ( delta_lo_2 ) cdf = cdf_1 * cdf_2 if method is None or method == 'none' : comp_cdf = cdf elif self . band_1_detection == True : comp = mask . mask_1 . completeness ( mag_1 , method = method ) comp_cdf = comp * cdf elif self . band_1_detection == False : comp = mask . mask_2 . completeness ( mag_2 , method = method ) comp_cdf = comp * cdf else : comp_1 = mask . mask_1 . completeness ( mag_1 , method = method ) comp_2 = mask . mask_2 . completeness ( mag_2 , method = method ) comp_cdf = comp_1 * comp_2 * cdf observable_fraction = ( mass_pdf [ np . newaxis ] * comp_cdf ) . sum ( axis = - 1 ) return observable_fraction [ mask . mask_roi_digi [ mask . roi . pixel_interior_cut ] ] | Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask . Incorporates simplistic photometric errors . | 600 | 32 |
5,346 | def histogram2d ( self , distance_modulus = None , delta_mag = 0.03 , steps = 10000 ) : if distance_modulus is not None : self . distance_modulus = distance_modulus # Isochrone will be binned, so might as well sample lots of points mass_init , mass_pdf , mass_act , mag_1 , mag_2 = self . sample ( mass_steps = steps ) #logger.warning("Fudging intrinisic dispersion in isochrone.") #mag_1 += np.random.normal(scale=0.02,size=len(mag_1)) #mag_2 += np.random.normal(scale=0.02,size=len(mag_2)) # We cast to np.float32 to save memory bins_mag_1 = np . arange ( self . mod + mag_1 . min ( ) - ( 0.5 * delta_mag ) , self . mod + mag_1 . max ( ) + ( 0.5 * delta_mag ) , delta_mag ) . astype ( np . float32 ) bins_mag_2 = np . arange ( self . mod + mag_2 . min ( ) - ( 0.5 * delta_mag ) , self . mod + mag_2 . max ( ) + ( 0.5 * delta_mag ) , delta_mag ) . astype ( np . float32 ) # ADW: Completeness needs to go in mass_pdf here... isochrone_pdf = np . histogram2d ( self . mod + mag_1 , self . mod + mag_2 , bins = [ bins_mag_1 , bins_mag_2 ] , weights = mass_pdf ) [ 0 ] . astype ( np . float32 ) return isochrone_pdf , bins_mag_1 , bins_mag_2 | Return a 2D histogram the isochrone in mag - mag space . | 408 | 16 |
5,347 | def pdf_mmd ( self , lon , lat , mag_1 , mag_2 , distance_modulus , mask , delta_mag = 0.03 , steps = 1000 ) : logger . info ( 'Running MMD pdf' ) roi = mask . roi mmd = self . signalMMD ( mask , distance_modulus , delta_mag = delta_mag , mass_steps = steps ) # This is fragile, store this information somewhere else... nedges = np . rint ( ( roi . bins_mag [ - 1 ] - roi . bins_mag [ 0 ] ) / delta_mag ) + 1 edges_mag , delta_mag = np . linspace ( roi . bins_mag [ 0 ] , roi . bins_mag [ - 1 ] , nedges , retstep = True ) idx_mag_1 = np . searchsorted ( edges_mag , mag_1 ) idx_mag_2 = np . searchsorted ( edges_mag , mag_2 ) if np . any ( idx_mag_1 > nedges ) or np . any ( idx_mag_1 == 0 ) : msg = "Magnitude out of range..." raise Exception ( msg ) if np . any ( idx_mag_2 > nedges ) or np . any ( idx_mag_2 == 0 ) : msg = "Magnitude out of range..." raise Exception ( msg ) idx = mask . roi . indexROI ( lon , lat ) u_color = mmd [ ( mask . mask_roi_digi [ idx ] , idx_mag_1 , idx_mag_2 ) ] # Remove the bin size to convert the pdf to units of mag^-2 u_color /= delta_mag ** 2 return u_color | Ok now here comes the beauty of having the signal MMD . | 398 | 13 |
5,348 | def raw_separation ( self , mag_1 , mag_2 , steps = 10000 ) : # http://stackoverflow.com/q/12653120/ mag_1 = np . array ( mag_1 , copy = False , ndmin = 1 ) mag_2 = np . array ( mag_2 , copy = False , ndmin = 1 ) init , pdf , act , iso_mag_1 , iso_mag_2 = self . sample ( mass_steps = steps ) iso_mag_1 += self . distance_modulus iso_mag_2 += self . distance_modulus iso_cut = ( iso_mag_1 < np . max ( mag_1 ) ) & ( iso_mag_1 > np . min ( mag_1 ) ) | ( iso_mag_2 < np . max ( mag_2 ) ) & ( iso_mag_2 > np . min ( mag_2 ) ) iso_mag_1 = iso_mag_1 [ iso_cut ] iso_mag_2 = iso_mag_2 [ iso_cut ] dist_mag_1 = mag_1 [ : , np . newaxis ] - iso_mag_1 dist_mag_2 = mag_2 [ : , np . newaxis ] - iso_mag_2 return np . min ( np . sqrt ( dist_mag_1 ** 2 + dist_mag_2 ** 2 ) , axis = 1 ) | Calculate the separation in magnitude - magnitude space between points and isochrone . Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point . | 312 | 39 |
5,349 | def separation ( self , mag_1 , mag_2 ) : iso_mag_1 = self . mag_1 + self . distance_modulus iso_mag_2 = self . mag_2 + self . distance_modulus def interp_iso ( iso_mag_1 , iso_mag_2 , mag_1 , mag_2 ) : interp_1 = scipy . interpolate . interp1d ( iso_mag_1 , iso_mag_2 , bounds_error = False ) interp_2 = scipy . interpolate . interp1d ( iso_mag_2 , iso_mag_1 , bounds_error = False ) dy = interp_1 ( mag_1 ) - mag_2 dx = interp_2 ( mag_2 ) - mag_1 dmag_1 = np . fabs ( dx * dy ) / ( dx ** 2 + dy ** 2 ) * dy dmag_2 = np . fabs ( dx * dy ) / ( dx ** 2 + dy ** 2 ) * dx return dmag_1 , dmag_2 # Separate the various stellar evolution stages if np . issubdtype ( self . stage . dtype , np . number ) : sel = ( self . stage < self . hb_stage ) else : sel = ( self . stage != self . hb_stage ) # First do the MS/RGB rgb_mag_1 = iso_mag_1 [ sel ] rgb_mag_2 = iso_mag_2 [ sel ] dmag_1 , dmag_2 = interp_iso ( rgb_mag_1 , rgb_mag_2 , mag_1 , mag_2 ) # Then do the HB (if it exists) if not np . all ( sel ) : hb_mag_1 = iso_mag_1 [ ~ sel ] hb_mag_2 = iso_mag_2 [ ~ sel ] hb_dmag_1 , hb_dmag_2 = interp_iso ( hb_mag_1 , hb_mag_2 , mag_1 , mag_2 ) dmag_1 = np . nanmin ( [ dmag_1 , hb_dmag_1 ] , axis = 0 ) dmag_2 = np . nanmin ( [ dmag_2 , hb_dmag_2 ] , axis = 0 ) #return dmag_1,dmag_2 return np . sqrt ( dmag_1 ** 2 + dmag_2 ** 2 ) | Calculate the separation between a specific point and the isochrone in magnitude - magnitude space . Uses an interpolation | 557 | 24 |
5,350 | def get_handler ( self , operation_id ) : handler = ( self . handlers . get ( operation_id ) or self . handlers . get ( snake_case ( operation_id ) ) ) if handler : return handler raise MissingHandler ( 'Missing handler for operation %s (tried %s too)' % ( operation_id , snake_case ( operation_id ) ) ) | Get the handler function for a given operation . | 81 | 9 |
5,351 | def add_handlers ( self , namespace ) : if isinstance ( namespace , str ) : namespace = import_module ( namespace ) if isinstance ( namespace , dict ) : namespace = namespace . items ( ) else : namespace = vars ( namespace ) . items ( ) for name , value in namespace : if name . startswith ( '_' ) : continue if isfunction ( value ) or ismethod ( value ) : self . handlers [ name ] = value | Add handler functions from the given namespace for instance a module . | 98 | 12 |
5,352 | def get_context ( self , arr , expr , context ) : expression_names = [ x for x in self . get_expression_names ( expr ) if x not in set ( context . keys ( ) ) . union ( [ 'i' ] ) ] if len ( expression_names ) != 1 : raise ValueError ( 'The expression must have exactly one variable.' ) return { expression_names [ 0 ] : arr } | Returns a context dictionary for use in evaluating the expression . | 90 | 11 |
5,353 | def execute ( self , array_in , expression , * * kwargs ) : context = self . get_context ( array_in , expression , kwargs ) context . update ( kwargs ) return ma . masked_where ( self . evaluate_expression ( expression , context ) , array_in ) | Creates and returns a masked view of the input array . | 66 | 12 |
5,354 | def timeout_error ( url , timeout ) : msg = 'Request timed out: {} timeout: {}s' . format ( url , timeout ) log . warning ( msg ) return ServerError ( msg ) | Raise a server error indicating a request timeout to the given URL . | 42 | 14 |
5,355 | def histogram ( title , title_x , title_y , x , bins_x ) : plt . figure ( ) plt . hist ( x , bins_x ) plt . xlabel ( title_x ) plt . ylabel ( title_y ) plt . title ( title ) | Plot a basic histogram . | 65 | 6 |
5,356 | def twoDimensionalHistogram ( title , title_x , title_y , z , bins_x , bins_y , lim_x = None , lim_y = None , vmin = None , vmax = None ) : plt . figure ( ) mesh_x , mesh_y = np . meshgrid ( bins_x , bins_y ) if vmin != None and vmin == vmax : plt . pcolor ( mesh_x , mesh_y , z ) else : plt . pcolor ( mesh_x , mesh_y , z , vmin = vmin , vmax = vmax ) plt . xlabel ( title_x ) plt . ylabel ( title_y ) plt . title ( title ) plt . colorbar ( ) if lim_x : plt . xlim ( lim_x [ 0 ] , lim_x [ 1 ] ) if lim_y : plt . ylim ( lim_y [ 0 ] , lim_y [ 1 ] ) | Create a two - dimension histogram plot or binned map . | 219 | 13 |
5,357 | def twoDimensionalScatter ( title , title_x , title_y , x , y , lim_x = None , lim_y = None , color = 'b' , size = 20 , alpha = None ) : plt . figure ( ) plt . scatter ( x , y , c = color , s = size , alpha = alpha , edgecolors = 'none' ) plt . xlabel ( title_x ) plt . ylabel ( title_y ) plt . title ( title ) if type ( color ) is not str : plt . colorbar ( ) if lim_x : plt . xlim ( lim_x [ 0 ] , lim_x [ 1 ] ) if lim_y : plt . ylim ( lim_y [ 0 ] , lim_y [ 1 ] ) | Create a two - dimensional scatter plot . | 176 | 8 |
5,358 | def drawHealpixMap ( hpxmap , lon , lat , size = 1.0 , xsize = 501 , coord = 'GC' , * * kwargs ) : ax = plt . gca ( ) x = np . linspace ( - size , size , xsize ) y = np . linspace ( - size , size , xsize ) xx , yy = np . meshgrid ( x , y ) coord = coord . upper ( ) if coord == 'GC' : #Assumes map and (lon,lat) are Galactic, but plotting celestial llon , llat = image2sphere ( * gal2cel ( lon , lat ) , x = xx . flat , y = yy . flat ) pix = ang2pix ( get_nside ( hpxmap ) , * cel2gal ( llon , llat ) ) elif coord == 'CG' : #Assumes map and (lon,lat) are celestial, but plotting Galactic llon , llat = image2sphere ( * cel2gal ( lon , lat ) , x = xx . flat , y = yy . flat ) pix = ang2pix ( get_nside ( hpxmap ) , * gal2cel ( llon , llat ) ) else : #Assumes plotting the native coordinates llon , llat = image2sphere ( lon , lat , xx . flat , yy . flat ) pix = ang2pix ( get_nside ( hpxmap ) , llon , llat ) values = hpxmap [ pix ] . reshape ( xx . shape ) zz = np . ma . array ( values , mask = ( values == hp . UNSEEN ) , fill_value = np . nan ) return drawProjImage ( xx , yy , zz , coord = coord , * * kwargs ) | Draw local projection of healpix map . | 410 | 9 |
5,359 | def getDSSImage ( ra , dec , radius = 1.0 , xsize = 800 , * * kwargs ) : import subprocess import tempfile service = 'skyview' if service == 'stsci' : url = "https://archive.stsci.edu/cgi-bin/dss_search?" scale = 2.0 * radius * 60. params = dict ( ra = '%.3f' % ra , dec = '%.3f' % dec , width = scale , height = scale , format = 'gif' , version = 1 ) #v='poss2ukstu_red' elif service == 'skyview' : url = "https://skyview.gsfc.nasa.gov/cgi-bin/images?" params = dict ( survey = 'DSS' , position = '%.3f,%.3f' % ( ra , dec ) , scaling = 'Linear' , Return = 'GIF' , size = 2 * radius , projection = 'Car' , pixels = xsize ) else : raise Exception ( "Unrecognized service." ) query = '&' . join ( "%s=%s" % ( k , v ) for k , v in params . items ( ) ) tmp = tempfile . NamedTemporaryFile ( suffix = '.gif' ) cmd = 'wget --progress=dot:mega -O %s "%s"' % ( tmp . name , url + query ) subprocess . call ( cmd , shell = True ) im = plt . imread ( tmp . name ) tmp . close ( ) if service == 'stsci' and xsize : im = scipy . misc . imresize ( im , size = ( xsize , xsize ) ) return im | Download Digitized Sky Survey images | 376 | 6 |
5,360 | def draw_slices ( hist , func = np . sum , * * kwargs ) : from mpl_toolkits . axes_grid1 import make_axes_locatable kwargs . setdefault ( 'ls' , '-' ) ax = plt . gca ( ) data = hist # Slices vslice = func ( data , axis = 0 ) hslice = func ( data , axis = 1 ) npix = np . array ( data . shape ) #xlim,ylim = plt.array(zip([0,0],npix-1)) xlim = ax . get_xlim ( ) ylim = ax . get_ylim ( ) #extent = ax.get_extent() #xlim =extent[:2] #ylim = extent[2:] # Bin centers xbin = np . linspace ( xlim [ 0 ] , xlim [ 1 ] , len ( vslice ) ) #+0.5 ybin = np . linspace ( ylim [ 0 ] , ylim [ 1 ] , len ( hslice ) ) #+0.5 divider = make_axes_locatable ( ax ) #gh2 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[2, 1]) hax = divider . append_axes ( "right" , size = 1.2 , pad = 0.05 , sharey = ax , axes_class = axes_divider . LocatableAxes ) hax . axis [ "left" ] . toggle ( label = False , ticklabels = False ) #hax.plot(hslice, plt.arange(*ylim)+0.5,'-') # Bin center hax . plot ( hslice , ybin , * * kwargs ) # Bin center hax . xaxis . set_major_locator ( MaxNLocator ( 4 , prune = 'both' ) ) hax . set_ylim ( * ylim ) #gh1 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[0, 2]) vax = divider . append_axes ( "top" , size = 1.2 , pad = 0.05 , sharex = ax , axes_class = axes_divider . LocatableAxes ) vax . axis [ "bottom" ] . toggle ( label = False , ticklabels = False ) vax . plot ( xbin , vslice , * * kwargs ) vax . yaxis . set_major_locator ( MaxNLocator ( 4 , prune = 'lower' ) ) vax . set_xlim ( * xlim ) return vax , hax | Draw horizontal and vertical slices through histogram | 604 | 8 |
5,361 | def plotSkymapCatalog ( lon , lat , * * kwargs ) : fig = plt . figure ( ) ax = plt . subplot ( 111 , projection = projection ) drawSkymapCatalog ( ax , lon , lat , * * kwargs ) | Plot a catalog of coordinates on a full - sky map . | 58 | 12 |
5,362 | def makePath ( x_path , y_path , epsilon = 1.e-10 ) : x_path_closed = np . concatenate ( [ x_path , x_path [ : : - 1 ] ] ) y_path_closed = np . concatenate ( [ y_path , epsilon + y_path [ : : - 1 ] ] ) path = matplotlib . path . Path ( list ( zip ( x_path_closed , y_path_closed ) ) ) return path | Create closed path . | 113 | 4 |
5,363 | def drawMask ( self , ax = None , mask = None , mtype = 'maglim' ) : if not ax : ax = plt . gca ( ) if mask is None : mask = ugali . analysis . loglike . createMask ( self . config , roi = self . roi ) mask_map = hp . UNSEEN * np . ones ( hp . nside2npix ( self . nside ) ) if mtype . lower ( ) == 'maglim' : mask_map [ mask . roi . pixels ] = mask . mask_1 . mask_roi_sparse elif mtype . lower ( ) == 'fracdet' : mask_map [ mask . roi . pixels ] = mask . mask_1 . frac_roi_sparse else : raise Exception ( "Unrecognized type: %s" % mtype ) masked = ( mask_map == hp . UNSEEN ) | ( mask_map == 0 ) mask_map = np . ma . array ( mask_map , mask = masked , fill_value = np . nan ) im = drawHealpixMap ( mask_map , self . lon , self . lat , self . radius , coord = self . coord ) try : cbar = ax . cax . colorbar ( im ) except : cbar = plt . colorbar ( im ) cbar . ax . set_xticklabels ( cbar . ax . get_xticklabels ( ) , rotation = 90 ) ax . annotate ( mtype , * * self . label_kwargs ) return im | Draw the maglim from the mask . | 347 | 8 |
5,364 | def parse ( self , configManager , config ) : parser = ConfigParser . RawConfigParser ( ) configOptions = dict ( ) configFile = self . _getConfigFile ( config ) if configFile : parser . readfp ( configFile ) for section in parser . sections ( ) : if self . sections is None or section in self . sections : configOptions . update ( parser . items ( section ) ) return configOptions | Parse configuration options out of an . ini configuration file . | 88 | 13 |
5,365 | def write_chapter ( self ) : self . paragraphs = [ ] self . paragraphs . append ( '\n' ) for x in range ( randint ( 0 , 50 ) ) : p = Paragraph ( self . model ) self . paragraphs . append ( p . get_paragraph ( ) ) self . paragraphs . append ( '\n' ) return self . paragraphs | Create a chapter that contains a random number of paragraphs | 77 | 10 |
5,366 | def buildcss ( app , buildpath , imagefile ) : # set default values div = 'body' repeat = 'repeat-y' position = 'center' attachment = 'scroll' if app . config . sphinxmark_div != 'default' : div = app . config . sphinxmark_div if app . config . sphinxmark_repeat is False : repeat = 'no-repeat' if app . config . sphinxmark_fixed is True : attachment = 'fixed' border = app . config . sphinxmark_border if border == 'left' or border == 'right' : css = template ( 'border' , div = div , image = imagefile , side = border ) else : css = template ( 'watermark' , div = div , image = imagefile , repeat = repeat , position = position , attachment = attachment ) LOG . debug ( '[sphinxmark] Template: ' + css ) cssname = 'sphinxmark.css' cssfile = os . path . join ( buildpath , cssname ) with open ( cssfile , 'w' ) as f : f . write ( css ) return ( cssname ) | Create CSS file . | 260 | 4 |
5,367 | def createimage ( app , srcdir , buildpath ) : text = app . config . sphinxmark_text # draw transparent background width = app . config . sphinxmark_text_width height = app . config . sphinxmark_text_spacing img = Image . new ( 'RGBA' , ( width , height ) , ( 255 , 255 , 255 , 0 ) ) d = ImageDraw . Draw ( img ) # set font fontfile = os . path . join ( srcdir , 'arial.ttf' ) font = ImageFont . truetype ( fontfile , app . config . sphinxmark_text_size ) # set x y location for text xsize , ysize = d . textsize ( text , font ) LOG . debug ( '[sphinxmark] x = ' + str ( xsize ) + '\ny = ' + str ( ysize ) ) x = ( width / 2 ) - ( xsize / 2 ) y = ( height / 2 ) - ( ysize / 2 ) # add text to image color = app . config . sphinxmark_text_color d . text ( ( x , y ) , text , font = font , fill = color ) # set opacity img . putalpha ( app . config . sphinxmark_text_opacity ) # rotate image img = img . rotate ( app . config . sphinxmark_text_rotation ) # save image imagefile = 'textmark_' + text + '.png' imagepath = os . path . join ( buildpath , imagefile ) img . save ( imagepath , 'PNG' ) LOG . debug ( '[sphinxmark] Image saved to: ' + imagepath ) return ( imagefile ) | Create PNG image from string . | 375 | 6 |
5,368 | def getimage ( app ) : # append source directory to TEMPLATE_PATH so template is found srcdir = os . path . abspath ( os . path . dirname ( __file__ ) ) TEMPLATE_PATH . append ( srcdir ) staticbase = '_static' buildpath = os . path . join ( app . outdir , staticbase ) try : os . makedirs ( buildpath ) except OSError : if not os . path . isdir ( buildpath ) : raise if app . config . sphinxmark_image == 'default' : imagefile = 'watermark-draft.png' imagepath = os . path . join ( srcdir , imagefile ) copy ( imagepath , buildpath ) LOG . debug ( '[sphinxmark] Using default image: ' + imagefile ) elif app . config . sphinxmark_image == 'text' : imagefile = createimage ( app , srcdir , buildpath ) LOG . debug ( '[sphinxmark] Image: ' + imagefile ) else : imagefile = app . config . sphinxmark_image if app . config . html_static_path : staticpath = app . config . html_static_path [ 0 ] else : staticpath = '_static' LOG . debug ( '[sphinxmark] static path: ' + staticpath ) imagepath = os . path . join ( app . confdir , staticpath , imagefile ) LOG . debug ( '[sphinxmark] Imagepath: ' + imagepath ) try : copy ( imagepath , buildpath ) except Exception : message = ( "Cannot find '%s'. Put watermark images in the " "'_static' directory or specify the location using " "'html_static_path'." % imagefile ) LOG . warning ( message ) LOG . warning ( 'Failed to add watermark.' ) return return ( buildpath , imagefile ) | Get image file . | 415 | 4 |
5,369 | def watermark ( app , env ) : if app . config . sphinxmark_enable is True : LOG . info ( 'adding watermark...' , nonl = True ) buildpath , imagefile = getimage ( app ) cssname = buildcss ( app , buildpath , imagefile ) app . add_css_file ( cssname ) LOG . info ( ' done' ) | Add watermark . | 85 | 4 |
5,370 | def setup ( app ) : app . add_config_value ( 'sphinxmark_enable' , False , 'html' ) app . add_config_value ( 'sphinxmark_div' , 'default' , 'html' ) app . add_config_value ( 'sphinxmark_border' , None , 'html' ) app . add_config_value ( 'sphinxmark_repeat' , True , 'html' ) app . add_config_value ( 'sphinxmark_fixed' , False , 'html' ) app . add_config_value ( 'sphinxmark_image' , 'default' , 'html' ) app . add_config_value ( 'sphinxmark_text' , 'default' , 'html' ) app . add_config_value ( 'sphinxmark_text_color' , ( 255 , 0 , 0 ) , 'html' ) app . add_config_value ( 'sphinxmark_text_size' , 100 , 'html' ) app . add_config_value ( 'sphinxmark_text_width' , 1000 , 'html' ) app . add_config_value ( 'sphinxmark_text_opacity' , 20 , 'html' ) app . add_config_value ( 'sphinxmark_text_spacing' , 400 , 'html' ) app . add_config_value ( 'sphinxmark_text_rotation' , 0 , 'html' ) app . connect ( 'env-updated' , watermark ) return { 'version' : '0.1.18' , 'parallel_read_safe' : True , 'parallel_write_safe' : True , } | Configure setup for Sphinx extension . | 382 | 8 |
5,371 | def gammalnStirling ( z ) : return ( 0.5 * ( np . log ( 2. * np . pi ) - np . log ( z ) ) ) + ( z * ( np . log ( z + ( 1. / ( ( 12. * z ) - ( 1. / ( 10. * z ) ) ) ) ) - 1. ) ) | Uses Stirling s approximation for the log - gamma function suitable for large arguments . | 80 | 17 |
5,372 | def satellite ( isochrone , kernel , stellar_mass , distance_modulus , * * kwargs ) : mag_1 , mag_2 = isochrone . simulate ( stellar_mass , distance_modulus ) lon , lat = kernel . simulate ( len ( mag_1 ) ) return mag_1 , mag_2 , lon , lat | Wrapping the isochrone and kernel simulate functions . | 77 | 11 |
5,373 | def detectability ( self , * * kwargs ) : distance_modulus = kwargs . get ( 'distance_modulus' ) distance = mod2dist ( distance_modulus ) stellar_mass = kwargs . get ( 'stellar_mass' ) extension = kwargs . get ( 'extension' ) # Normalized to 10^3 Msolar at mod=18 norm = 10 ** 3 / mod2dist ( 18 ) ** 2 detect = stellar_mass / distance ** 2 detect /= norm | An a priori detectability proxy . | 111 | 8 |
5,374 | def _create_catalog ( self , catalog = None ) : if catalog is None : catalog = ugali . analysis . loglike . createCatalog ( self . config , self . roi ) cut = self . mask . restrictCatalogToObservableSpace ( catalog ) self . catalog = catalog . applyCut ( cut ) | Bundle it . | 69 | 4 |
5,375 | def _setup_subpix ( self , nside = 2 ** 16 ) : # Only setup once... if hasattr ( self , 'subpix' ) : return # Simulate over full ROI self . roi_radius = self . config [ 'coords' ] [ 'roi_radius' ] # Setup background spatial stuff logger . info ( "Setup subpixels..." ) self . nside_pixel = self . config [ 'coords' ] [ 'nside_pixel' ] self . nside_subpixel = self . nside_pixel * 2 ** 4 # Could be config parameter epsilon = np . degrees ( hp . max_pixrad ( self . nside_pixel ) ) # Pad roi radius to cover edge healpix subpix = ugali . utils . healpix . query_disc ( self . nside_subpixel , self . roi . vec , self . roi_radius + epsilon ) superpix = ugali . utils . healpix . superpixel ( subpix , self . nside_subpixel , self . nside_pixel ) self . subpix = subpix [ np . in1d ( superpix , self . roi . pixels ) ] | Subpixels for random position generation . | 271 | 8 |
5,376 | def _setup_cmd ( self , mode = 'cloud-in-cells' ) : # Only setup once... if hasattr ( self , 'bkg_lambda' ) : return logger . info ( "Setup color..." ) # In the limit theta->0: 2*pi*(1-cos(theta)) -> pi*theta**2 # (Remember to convert from sr to deg^2) #solid_angle_roi = sr2deg(2*np.pi*(1-np.cos(np.radians(self.roi_radius)))) solid_angle_roi = self . roi . area_pixel * len ( self . roi . pixels ) # Large CMD bins cause problems when simulating config = Config ( self . config ) config [ 'color' ] [ 'n_bins' ] *= 5 #10 config [ 'mag' ] [ 'n_bins' ] *= 1 #2 #config['mask']['minimum_solid_angle'] = 0 roi = ugali . analysis . loglike . createROI ( config , self . roi . lon , self . roi . lat ) mask = ugali . analysis . loglike . createMask ( config , roi ) self . bkg_centers_color = roi . centers_color self . bkg_centers_mag = roi . centers_mag # Background CMD has units: [objs / deg^2 / mag^2] cmd_background = mask . backgroundCMD ( self . catalog , mode ) self . bkg_lambda = cmd_background * solid_angle_roi * roi . delta_color * roi . delta_mag np . sum ( self . bkg_lambda ) # Clean up del config , roi , mask | The purpose here is to create a more finely binned background CMD to sample from . | 392 | 18 |
5,377 | def toy_background ( self , mc_source_id = 2 , seed = None ) : logger . info ( "Running toy background simulation..." ) size = 20000 nstar = np . random . poisson ( size ) #np.random.seed(0) logger . info ( "Simulating %i background stars..." % nstar ) ### # Random points from roi pixels ### idx = np.random.randint(len(self.roi.pixels)-1,size=nstar) ### pix = self.roi.pixels[idx] # Random points drawn from subpixels logger . info ( "Generating uniform positions..." ) idx = np . random . randint ( 0 , len ( self . subpix ) - 1 , size = nstar ) lon , lat = pix2ang ( self . nside_subpixel , self . subpix [ idx ] ) pix = ang2pix ( self . nside_pixel , lon , lat ) lon , lat = pix2ang ( self . nside_pixel , pix ) # Single color #mag_1 = 19.05*np.ones(len(pix)) #mag_2 = 19.10*np.ones(len(pix)) # Uniform in color logger . info ( "Generating uniform CMD..." ) mag_1 = np . random . uniform ( self . config [ 'mag' ] [ 'min' ] , self . config [ 'mag' ] [ 'max' ] , size = nstar ) color = np . random . uniform ( self . config [ 'color' ] [ 'min' ] , self . config [ 'color' ] [ 'max' ] , size = nstar ) mag_2 = mag_1 - color # There is probably a better way to do this step without creating the full HEALPix map mask = - 1. * np . ones ( hp . nside2npix ( self . nside_pixel ) ) mask [ self . roi . pixels ] = self . mask . mask_1 . mask_roi_sparse mag_lim_1 = mask [ pix ] mask = - 1. * np . ones ( hp . nside2npix ( self . nside_pixel ) ) mask [ self . roi . pixels ] = self . mask . mask_2 . mask_roi_sparse mag_lim_2 = mask [ pix ] #mag_err_1 = 1.0*np.ones(len(pix)) #mag_err_2 = 1.0*np.ones(len(pix)) mag_err_1 = self . photo_err_1 ( mag_lim_1 - mag_1 ) mag_err_2 = self . photo_err_2 ( mag_lim_2 - mag_2 ) mc_source_id = mc_source_id * np . ones ( len ( mag_1 ) ) select = ( mag_lim_1 > mag_1 ) & ( mag_lim_2 > mag_2 ) hdu = ugali . observation . catalog . makeHDU ( self . config , mag_1 [ select ] , mag_err_1 [ select ] , mag_2 [ select ] , mag_err_2 [ select ] , lon [ select ] , lat [ select ] , mc_source_id [ select ] ) catalog = ugali . observation . catalog . Catalog ( self . config , data = hdu . data ) return catalog | Quick uniform background generation . | 759 | 5 |
5,378 | def satellite ( self , stellar_mass , distance_modulus , mc_source_id = 1 , seed = None , * * kwargs ) : if seed is not None : np . random . seed ( seed ) isochrone = kwargs . pop ( 'isochrone' , self . isochrone ) kernel = kwargs . pop ( 'kernel' , self . kernel ) for k , v in kwargs . items ( ) : if k in kernel . params . keys ( ) : setattr ( kernel , k , v ) mag_1 , mag_2 = isochrone . simulate ( stellar_mass , distance_modulus ) lon , lat = kernel . simulate ( len ( mag_1 ) ) logger . info ( "Simulating %i satellite stars..." % len ( mag_1 ) ) pix = ang2pix ( self . config [ 'coords' ] [ 'nside_pixel' ] , lon , lat ) # There is probably a better way to do this step without creating the full HEALPix map mask = - 1. * np . ones ( hp . nside2npix ( self . config [ 'coords' ] [ 'nside_pixel' ] ) ) mask [ self . roi . pixels ] = self . mask . mask_1 . mask_roi_sparse mag_lim_1 = mask [ pix ] mask = - 1. * np . ones ( hp . nside2npix ( self . config [ 'coords' ] [ 'nside_pixel' ] ) ) mask [ self . roi . pixels ] = self . mask . mask_2 . mask_roi_sparse mag_lim_2 = mask [ pix ] mag_err_1 = self . photo_err_1 ( mag_lim_1 - mag_1 ) mag_err_2 = self . photo_err_2 ( mag_lim_2 - mag_2 ) # Randomize magnitudes by their errors mag_obs_1 = mag_1 + np . random . normal ( size = len ( mag_1 ) ) * mag_err_1 mag_obs_2 = mag_2 + np . random . normal ( size = len ( mag_2 ) ) * mag_err_2 #mag_obs_1 = mag_1 #mag_obs_2 = mag_2 #select = np.logical_and(mag_obs_1 < mag_lim_1, mag_obs_2 < mag_lim_2) select = ( mag_lim_1 > mag_obs_1 ) & ( mag_lim_2 > mag_obs_2 ) # Make sure objects lie within the original cmd (should also be done later...) #select &= (ugali.utils.binning.take2D(self.mask.solid_angle_cmd, mag_obs_1 - mag_obs_2, mag_obs_1,self.roi.bins_color, self.roi.bins_mag) > 0) #return mag_1_obs[cut], mag_2_obs[cut], lon[cut], lat[cut] logger . info ( "Clipping %i simulated satellite stars..." % ( ~ select ) . sum ( ) ) mc_source_id = mc_source_id * np . ones ( len ( mag_1 ) ) hdu = ugali . observation . catalog . makeHDU ( self . config , mag_obs_1 [ select ] , mag_err_1 [ select ] , mag_obs_2 [ select ] , mag_err_2 [ select ] , lon [ select ] , lat [ select ] , mc_source_id [ select ] ) catalog = ugali . observation . catalog . Catalog ( self . config , data = hdu . data ) return catalog | Create a simulated satellite . Returns a catalog object . | 832 | 10 |
5,379 | def makeHDU ( self , mag_1 , mag_err_1 , mag_2 , mag_err_2 , lon , lat , mc_source_id ) : if self . config [ 'catalog' ] [ 'coordsys' ] . lower ( ) == 'cel' and self . config [ 'coords' ] [ 'coordsys' ] . lower ( ) == 'gal' : lon , lat = ugali . utils . projector . gal2cel ( lon , lat ) elif self . config [ 'catalog' ] [ 'coordsys' ] . lower ( ) == 'gal' and self . config [ 'coords' ] [ 'coordsys' ] . lower ( ) == 'cel' : lon , lat = ugali . utils . projector . cel2gal ( lon , lat ) columns = [ pyfits . Column ( name = self . config [ 'catalog' ] [ 'objid_field' ] , format = 'D' , array = np . arange ( len ( lon ) ) ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'lon_field' ] , format = 'D' , array = lon ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'lat_field' ] , format = 'D' , array = lat ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'mag_1_field' ] , format = 'E' , array = mag_1 ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'mag_err_1_field' ] , format = 'E' , array = mag_err_1 ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'mag_2_field' ] , format = 'E' , array = mag_2 ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'mag_err_2_field' ] , format = 'E' , array = mag_err_2 ) , pyfits . Column ( name = self . config [ 'catalog' ] [ 'mc_source_id_field' ] , format = 'I' , array = mc_source_id ) , ] hdu = pyfits . new_table ( columns ) return hdu | Create a catalog fits file object based on input data . | 531 | 11 |
5,380 | def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) ) | Return a dict with swapped keys and values | 38 | 8 |
5,381 | def inverted_dict_of_lists ( d ) : new_dict = { } for ( old_key , old_value_list ) in viewitems ( dict ( d ) ) : for new_key in listify ( old_value_list ) : new_dict [ new_key ] = old_key return new_dict | Return a dict where the keys are all the values listed in the values of the original dict | 71 | 18 |
5,382 | def sort_strings ( strings , sort_order = None , reverse = False , case_sensitive = False , sort_order_first = True ) : if not case_sensitive : sort_order = tuple ( s . lower ( ) for s in sort_order ) strings = tuple ( s . lower ( ) for s in strings ) prefix_len = max ( len ( s ) for s in sort_order ) def compare ( a , b , prefix_len = prefix_len ) : if prefix_len : if a [ : prefix_len ] in sort_order : if b [ : prefix_len ] in sort_order : comparison = sort_order . index ( a [ : prefix_len ] ) - sort_order . index ( b [ : prefix_len ] ) comparison = int ( comparison / abs ( comparison or 1 ) ) if comparison : return comparison * ( - 2 * reverse + 1 ) elif sort_order_first : return - 1 * ( - 2 * reverse + 1 ) # b may be in sort_order list, so it should be first elif sort_order_first and b [ : prefix_len ] in sort_order : return - 2 * reverse + 1 return ( - 1 * ( a < b ) + 1 * ( a > b ) ) * ( - 2 * reverse + 1 ) return sorted ( strings , key = functools . cmp_to_key ( compare ) ) | Sort a list of strings according to the provided sorted list of string prefixes | 303 | 15 |
5,383 | def clean_field_dict ( field_dict , cleaner = str . strip , time_zone = None ) : d = { } if time_zone is None : tz = DEFAULT_TZ for k , v in viewitems ( field_dict ) : if k == '_state' : continue if isinstance ( v , basestring ) : d [ k ] = cleaner ( str ( v ) ) elif isinstance ( v , ( datetime . datetime , datetime . date ) ) : d [ k ] = tz . localize ( v ) else : d [ k ] = v return d | r Normalize field values by stripping whitespace from strings localizing datetimes to a timezone etc | 132 | 20 |
5,384 | def generate_tuple_batches ( qs , batch_len = 1 ) : num_items , batch = 0 , [ ] for item in qs : if num_items >= batch_len : yield tuple ( batch ) num_items = 0 batch = [ ] num_items += 1 batch += [ item ] if num_items : yield tuple ( batch ) | Iterate through a queryset in batches of length batch_len | 78 | 14 |
5,385 | def find_count_label ( d ) : for name in COUNT_NAMES : if name in d : return name for name in COUNT_NAMES : if str ( name ) . lower ( ) in d : return name | Find the member of a set that means count or frequency or probability or number of occurrences . | 49 | 18 |
5,386 | def fuzzy_get_value ( obj , approximate_key , default = None , * * kwargs ) : dict_obj = OrderedDict ( obj ) try : return dict_obj [ list ( dict_obj . keys ( ) ) [ int ( approximate_key ) ] ] except ( ValueError , IndexError ) : pass return fuzzy_get ( dict_obj , approximate_key , key_and_value = False , * * kwargs ) | Like fuzzy_get but assume the obj is dict - like and return the value without the key | 98 | 19 |
5,387 | def joined_seq ( seq , sep = None ) : joined_seq = tuple ( seq ) if isinstance ( sep , basestring ) : joined_seq = sep . join ( str ( item ) for item in joined_seq ) return joined_seq | r Join a sequence into a tuple or a concatenated string | 54 | 13 |
5,388 | def dos_from_table ( table , header = None ) : start_row = 0 if not table : return table if not header : header = table [ 0 ] start_row = 1 header_list = header if header and isinstance ( header , basestring ) : header_list = header . split ( '\t' ) if len ( header_list ) != len ( table [ 0 ] ) : header_list = header . split ( ',' ) if len ( header_list ) != len ( table [ 0 ] ) : header_list = header . split ( ' ' ) ans = { } for i , k in enumerate ( header ) : ans [ k ] = [ row [ i ] for row in table [ start_row : ] ] return ans | Produce dictionary of sequences from sequence of sequences optionally with a header row . | 163 | 15 |
5,389 | def transposed_lists ( list_of_lists , default = None ) : if default is None or default is [ ] or default is tuple ( ) : default = [ ] elif default is 'None' : default = [ None ] else : default = [ default ] N = len ( list_of_lists ) Ms = [ len ( row ) for row in list_of_lists ] M = max ( Ms ) ans = [ ] for j in range ( M ) : ans += [ [ ] ] for i in range ( N ) : if j < Ms [ i ] : ans [ - 1 ] += [ list_of_lists [ i ] [ j ] ] else : ans [ - 1 ] += list ( default ) return ans | Like numpy . transposed but allows uneven row lengths | 156 | 11 |
5,390 | def hist_from_counts ( counts , normalize = False , cumulative = False , to_str = False , sep = ',' , min_bin = None , max_bin = None ) : counters = [ dict ( ( i , c ) for i , c in enumerate ( counts ) ) ] intkeys_list = [ [ c for c in counts_dict if ( isinstance ( c , int ) or ( isinstance ( c , float ) and int ( c ) == c ) ) ] for counts_dict in counters ] min_bin , max_bin = min_bin or 0 , max_bin or len ( counts ) - 1 histograms = [ ] for intkeys , counts in zip ( intkeys_list , counters ) : histograms += [ OrderedDict ( ) ] if not intkeys : continue if normalize : N = sum ( counts [ c ] for c in intkeys ) for c in intkeys : counts [ c ] = float ( counts [ c ] ) / N if cumulative : for i in range ( min_bin , max_bin + 1 ) : histograms [ - 1 ] [ i ] = counts . get ( i , 0 ) + histograms [ - 1 ] . get ( i - 1 , 0 ) else : for i in range ( min_bin , max_bin + 1 ) : histograms [ - 1 ] [ i ] = counts . get ( i , 0 ) if not histograms : histograms = [ OrderedDict ( ) ] # fill in the zero counts between the integer bins of the histogram aligned_histograms = [ ] for i in range ( min_bin , max_bin + 1 ) : aligned_histograms += [ tuple ( [ i ] + [ hist . get ( i , 0 ) for hist in histograms ] ) ] if to_str : # FIXME: add header row return str_from_table ( aligned_histograms , sep = sep , max_rows = 365 * 2 + 1 ) return aligned_histograms | Compute an emprical histogram PMF or CDF in a list of lists | 428 | 18 |
5,391 | def get_similar ( obj , labels , default = None , min_similarity = 0.5 ) : raise NotImplementedError ( "Unfinished implementation, needs to be in fuzzy_get where list of scores & keywords is sorted." ) labels = listify ( labels ) def not_found ( * args , * * kwargs ) : return 0 min_score = int ( min_similarity * 100 ) for similarity_score in [ 100 , 95 , 90 , 80 , 70 , 50 , 30 , 10 , 5 , 0 ] : if similarity_score <= min_score : similarity_score = min_score for label in labels : try : result = obj . get ( label , not_found ) except AttributeError : try : result = obj . __getitem__ ( label ) except ( IndexError , TypeError ) : result = not_found if result is not not_found : return result if similarity_score == min_score : if result is not not_found : return result | Similar to fuzzy_get but allows non - string keys and a list of possible keys | 212 | 17 |
5,392 | def update_file_ext ( filename , ext = 'txt' , sep = '.' ) : path , filename = os . path . split ( filename ) if ext and ext [ 0 ] == sep : ext = ext [ 1 : ] return os . path . join ( path , sep . join ( filename . split ( sep ) [ : - 1 if filename . count ( sep ) > 1 else 1 ] + [ ext ] ) ) | r Force the file or path str to end with the indicated extension | 91 | 13 |
5,393 | def transcode ( infile , outfile = None , incoding = "shift-jis" , outcoding = "utf-8" ) : if not outfile : outfile = os . path . basename ( infile ) + '.utf8' with codecs . open ( infile , "rb" , incoding ) as fpin : with codecs . open ( outfile , "wb" , outcoding ) as fpout : fpout . write ( fpin . read ( ) ) | Change encoding of text file | 111 | 5 |
5,394 | def dict2obj ( d ) : if isinstance ( d , ( Mapping , list , tuple ) ) : try : d = dict ( d ) except ( ValueError , TypeError ) : return d else : return d obj = Object ( ) for k , v in viewitems ( d ) : obj . __dict__ [ k ] = dict2obj ( v ) return obj | Convert a dict to an object or namespace | 80 | 9 |
5,395 | def int_pair ( s , default = ( 0 , None ) ) : s = re . split ( r'[^0-9]+' , str ( s ) . strip ( ) ) if len ( s ) and len ( s [ 0 ] ) : if len ( s ) > 1 and len ( s [ 1 ] ) : return ( int ( s [ 0 ] ) , int ( s [ 1 ] ) ) return ( int ( s [ 0 ] ) , default [ 1 ] ) return default | Return the digits to either side of a single non - digit character as a 2 - tuple of integers | 106 | 20 |
5,396 | def make_float ( s , default = '' , ignore_commas = True ) : if ignore_commas and isinstance ( s , basestring ) : s = s . replace ( ',' , '' ) try : return float ( s ) except ( IndexError , ValueError , AttributeError , TypeError ) : try : return float ( str ( s ) ) except ValueError : try : return float ( normalize_scientific_notation ( str ( s ) , ignore_commas ) ) except ValueError : try : return float ( first_digits ( s ) ) except ValueError : return default | r Coerce a string into a float | 129 | 9 |
5,397 | def normalize_names ( names ) : if isinstance ( names , basestring ) : names = names . split ( ',' ) names = listify ( names ) return [ str ( name ) . strip ( ) for name in names ] | Coerce a string or nested list of strings into a flat list of strings . | 51 | 17 |
5,398 | def normalize_serial_number ( sn , max_length = None , left_fill = '0' , right_fill = str ( ) , blank = str ( ) , valid_chars = ' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' , invalid_chars = None , strip_whitespace = True , join = False , na = rex . nones ) : # All 9 kwargs have persistent default values stored as attributes of the funcion instance if max_length is None : max_length = normalize_serial_number . max_length else : normalize_serial_number . max_length = max_length if left_fill is None : left_fill = normalize_serial_number . left_fill else : normalize_serial_number . left_fill = left_fill if right_fill is None : right_fill = normalize_serial_number . right_fill else : normalize_serial_number . right_fill = right_fill if blank is None : blank = normalize_serial_number . blank else : normalize_serial_number . blank = blank if valid_chars is None : valid_chars = normalize_serial_number . valid_chars else : normalize_serial_number . valid_chars = valid_chars if invalid_chars is None : invalid_chars = normalize_serial_number . invalid_chars else : normalize_serial_number . invalid_chars = invalid_chars if strip_whitespace is None : strip_whitespace = normalize_serial_number . strip_whitespace else : normalize_serial_number . strip_whitespace = strip_whitespace if join is None : join = normalize_serial_number . join else : normalize_serial_number . join = join if na is None : na = normalize_serial_number . na else : normalize_serial_number . na = na if invalid_chars is None : invalid_chars = ( c for c in charlist . ascii_all if c not in valid_chars ) invalid_chars = '' . join ( invalid_chars ) sn = str ( sn ) . strip ( invalid_chars ) if strip_whitespace : sn = sn . strip ( ) if invalid_chars : if join : sn = sn . translate ( dict ( zip ( invalid_chars , [ '' ] * len ( invalid_chars ) ) ) ) else : sn = multisplit ( sn , invalid_chars ) [ - 1 ] sn = sn [ - max_length : ] if strip_whitespace : sn = sn . strip ( ) if na : if isinstance ( na , ( tuple , set , dict , list ) ) and sn in na : sn = '' elif na . match ( sn ) : sn = '' if not sn and not ( blank is False ) : return blank if left_fill : sn = left_fill * int ( max_length - len ( sn ) / len ( left_fill ) ) + sn if right_fill : sn = sn + right_fill * ( max_length - len ( sn ) / len ( right_fill ) ) return sn | r Make a string compatible with typical serial number requirements | 724 | 10 |
5,399 | def strip_HTML ( s ) : result = '' total = 0 for c in s : if c == '<' : total = 1 elif c == '>' : total = 0 result += ' ' elif total == 0 : result += c return result | Simple clumsy slow HTML tag stripper | 55 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.