idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
18,600 | def find_char_color ( ansi_string , pos ) : result = list ( ) position = 0 # Set to None when character is found. for item in ( i for i in RE_SPLIT . split ( ansi_string ) if i ) : if RE_SPLIT . match ( item ) : result . append ( item ) if position is not None : position += len ( item ) elif position is not None : for char in item : if position == pos : result . append ( char ) position = None break position += 1 return '' . join ( result ) | Determine what color a character is in the string . | 124 | 12 |
18,601 | def angular_distance_fast ( ra1 , dec1 , ra2 , dec2 ) : lon1 = np . deg2rad ( ra1 ) lat1 = np . deg2rad ( dec1 ) lon2 = np . deg2rad ( ra2 ) lat2 = np . deg2rad ( dec2 ) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np . sin ( dlat / 2.0 ) ** 2 + np . cos ( lat1 ) * np . cos ( lat2 ) * np . sin ( dlon / 2.0 ) ** 2 c = 2 * np . arcsin ( np . sqrt ( a ) ) return np . rad2deg ( c ) | Compute angular distance using the Haversine formula . Use this one when you know you will never ask for points at their antipodes . If this is not the case use the angular_distance function which is slower but works also for antipodes . | 159 | 50 |
18,602 | def angular_distance ( ra1 , dec1 , ra2 , dec2 ) : # Vincenty formula, slower than the Haversine formula in some cases, but stable also at antipodes lon1 = np . deg2rad ( ra1 ) lat1 = np . deg2rad ( dec1 ) lon2 = np . deg2rad ( ra2 ) lat2 = np . deg2rad ( dec2 ) sdlon = np . sin ( lon2 - lon1 ) cdlon = np . cos ( lon2 - lon1 ) slat1 = np . sin ( lat1 ) slat2 = np . sin ( lat2 ) clat1 = np . cos ( lat1 ) clat2 = np . cos ( lat2 ) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np . rad2deg ( np . arctan2 ( np . sqrt ( num1 ** 2 + num2 ** 2 ) , denominator ) ) | Returns the angular distance between two points two sets of points or a set of points and one point . | 249 | 20 |
18,603 | def memoize ( method ) : cache = method . cache = collections . OrderedDict ( ) # Put these two methods in the local space (faster) _get = cache . get _popitem = cache . popitem @ functools . wraps ( method ) def memoizer ( instance , x , * args , * * kwargs ) : if not _WITH_MEMOIZATION or isinstance ( x , u . Quantity ) : # Memoization is not active or using units, do not use memoization return method ( instance , x , * args , * * kwargs ) # Create a tuple because a tuple is hashable unique_id = tuple ( float ( yy . value ) for yy in instance . parameters . values ( ) ) + ( x . size , x . min ( ) , x . max ( ) ) # Create a unique identifier for this combination of inputs key = hash ( unique_id ) # Let's do it this way so we only look into the dictionary once result = _get ( key ) if result is not None : return result else : result = method ( instance , x , * args , * * kwargs ) cache [ key ] = result if len ( cache ) > _CACHE_SIZE : # Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) ) [ _popitem ( False ) for i in range ( max ( _CACHE_SIZE // 2 , 1 ) ) ] return result # Add the function as a "attribute" so we can access it memoizer . input_object = method return memoizer | A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls | 354 | 22 |
18,604 | def free_parameters ( self ) : # Refresh the list self . _update_parameters ( ) # Filter selecting only free parameters free_parameters_dictionary = collections . OrderedDict ( ) for parameter_name , parameter in self . _parameters . iteritems ( ) : if parameter . free : free_parameters_dictionary [ parameter_name ] = parameter return free_parameters_dictionary | Get a dictionary with all the free parameters in this model | 89 | 11 |
18,605 | def set_free_parameters ( self , values ) : assert len ( values ) == len ( self . free_parameters ) for parameter , this_value in zip ( self . free_parameters . values ( ) , values ) : parameter . value = this_value | Set the free parameters in the model to the provided values . | 58 | 12 |
18,606 | def add_independent_variable ( self , variable ) : assert isinstance ( variable , IndependentVariable ) , "Variable must be an instance of IndependentVariable" if self . _has_child ( variable . name ) : self . _remove_child ( variable . name ) self . _add_child ( variable ) # Add also to the list of independent variables self . _independent_variables [ variable . name ] = variable | Add a global independent variable to this model such as time . | 88 | 12 |
18,607 | def remove_independent_variable ( self , variable_name ) : self . _remove_child ( variable_name ) # Remove also from the list of independent variables self . _independent_variables . pop ( variable_name ) | Remove an independent variable which was added with add_independent_variable | 48 | 13 |
18,608 | def add_external_parameter ( self , parameter ) : assert isinstance ( parameter , Parameter ) , "Variable must be an instance of IndependentVariable" if self . _has_child ( parameter . name ) : # Remove it from the children only if it is a Parameter instance, otherwise don't, which will # make the _add_child call fail (which is the expected behaviour! You shouldn't call two children # with the same name) if isinstance ( self . _get_child ( parameter . name ) , Parameter ) : warnings . warn ( "External parameter %s already exist in the model. Overwriting it..." % parameter . name , RuntimeWarning ) self . _remove_child ( parameter . name ) # This will fail if another node with the same name is already in the model self . _add_child ( parameter ) | Add a parameter that comes from something other than a function to the model . | 178 | 15 |
18,609 | def unlink ( self , parameter ) : if not isinstance ( parameter , list ) : # Make a list of one element parameter_list = [ parameter ] else : # Make a copy to avoid tampering with the input parameter_list = list ( parameter ) for param in parameter_list : if param . has_auxiliary_variable ( ) : param . remove_auxiliary_variable ( ) else : with warnings . catch_warnings ( ) : warnings . simplefilter ( "always" , RuntimeWarning ) warnings . warn ( "Parameter %s has no link to be removed." % param . path , RuntimeWarning ) | Sets free one or more parameters which have been linked previously | 129 | 12 |
18,610 | def display ( self , complete = False ) : # Switch on the complete display flag self . _complete_display = bool ( complete ) # This will automatically choose the best representation among repr and repr_html super ( Model , self ) . display ( ) # Go back to default self . _complete_display = False | Display information about the point source . | 65 | 7 |
18,611 | def save ( self , output_file , overwrite = False ) : if os . path . exists ( output_file ) and overwrite is False : raise ModelFileExists ( "The file %s exists already. If you want to overwrite it, use the 'overwrite=True' " "options as 'model.save(\"%s\", overwrite=True)'. " % ( output_file , output_file ) ) else : data = self . to_dict_with_types ( ) # Write it to disk try : # Get the YAML representation of the data representation = my_yaml . dump ( data , default_flow_style = False ) with open ( output_file , "w+" ) as f : # Add a new line at the end of each voice (just for clarity) f . write ( representation . replace ( "\n" , "\n\n" ) ) except IOError : raise CannotWriteModel ( os . path . dirname ( os . path . abspath ( output_file ) ) , "Could not write model file %s. Check your permissions to write or the " "report on the free space which follows: " % output_file ) | Save the model to disk | 251 | 5 |
18,612 | def get_point_source_fluxes ( self , id , energies , tag = None ) : return self . _point_sources . values ( ) [ id ] ( energies , tag = tag ) | Get the fluxes from the id - th point source | 44 | 11 |
18,613 | def get_extended_source_fluxes ( self , id , j2000_ra , j2000_dec , energies ) : return self . _extended_sources . values ( ) [ id ] ( j2000_ra , j2000_dec , energies ) | Get the flux of the id - th extended sources at the given position at the given energies | 58 | 18 |
18,614 | def long_path_formatter ( line , max_width = pd . get_option ( 'max_colwidth' ) ) : if len ( line ) > max_width : tokens = line . split ( "." ) trial1 = "%s...%s" % ( tokens [ 0 ] , tokens [ - 1 ] ) if len ( trial1 ) > max_width : return "...%s" % ( tokens [ - 1 ] [ - 1 : - ( max_width - 3 ) ] ) else : return trial1 else : return line | If a path is longer than max_width it substitute it with the first and last element joined by ... . For example this . is . a . long . path . which . we . want . to . shorten becomes this ... shorten | 117 | 47 |
18,615 | def has_free_parameters ( self ) : for component in self . _components . values ( ) : for par in component . shape . parameters . values ( ) : if par . free : return True for par in self . position . parameters . values ( ) : if par . free : return True return False | Returns True or False whether there is any parameter in this source | 66 | 12 |
18,616 | def _repr__base ( self , rich_output = False ) : # Make a dictionary which will then be transformed in a list repr_dict = collections . OrderedDict ( ) key = '%s (point source)' % self . name repr_dict [ key ] = collections . OrderedDict ( ) repr_dict [ key ] [ 'position' ] = self . _sky_position . to_dict ( minimal = True ) repr_dict [ key ] [ 'spectrum' ] = collections . OrderedDict ( ) for component_name , component in self . components . iteritems ( ) : repr_dict [ key ] [ 'spectrum' ] [ component_name ] = component . to_dict ( minimal = True ) return dict_to_list ( repr_dict , rich_output ) | Representation of the object | 175 | 5 |
18,617 | def get_function ( function_name , composite_function_expression = None ) : # Check whether this is a composite function or a simple function if composite_function_expression is not None : # Composite function return _parse_function_expression ( composite_function_expression ) else : if function_name in _known_functions : return _known_functions [ function_name ] ( ) else : # Maybe this is a template # NOTE: import here to avoid circular import from astromodels . functions . template_model import TemplateModel , MissingDataFile try : instance = TemplateModel ( function_name ) except MissingDataFile : raise UnknownFunction ( "Function %s is not known. Known functions are: %s" % ( function_name , "," . join ( _known_functions . keys ( ) ) ) ) else : return instance | Returns the function name which must be among the known functions or a composite function . | 180 | 16 |
18,618 | def get_function_class ( function_name ) : if function_name in _known_functions : return _known_functions [ function_name ] else : raise UnknownFunction ( "Function %s is not known. Known functions are: %s" % ( function_name , "," . join ( _known_functions . keys ( ) ) ) ) | Return the type for the requested function | 78 | 7 |
18,619 | def check_calling_sequence ( name , function_name , function , possible_variables ) : # Get calling sequence # If the function has been memoized, it will have a "input_object" member try : calling_sequence = inspect . getargspec ( function . input_object ) . args except AttributeError : # This might happen if the function is with memoization calling_sequence = inspect . getargspec ( function ) . args assert calling_sequence [ 0 ] == 'self' , "Wrong syntax for 'evaluate' in %s. The first argument " "should be called 'self'." % name # Figure out how many variables are used variables = filter ( lambda var : var in possible_variables , calling_sequence ) # Check that they actually make sense. They must be used in the same order # as specified in possible_variables assert len ( variables ) > 0 , "The name of the variables for 'evaluate' in %s must be one or more " "among %s, instead of %s" % ( name , ',' . join ( possible_variables ) , "," . join ( variables ) ) if variables != possible_variables [ : len ( variables ) ] : raise AssertionError ( "The variables %s are out of order in '%s' of %s. Should be %s." % ( "," . join ( variables ) , function_name , name , possible_variables [ : len ( variables ) ] ) ) other_parameters = filter ( lambda var : var not in variables and var != 'self' , calling_sequence ) return variables , other_parameters | Check the calling sequence for the function looking for the variables specified . One or more of the variables can be in the calling sequence . Note that the order of the variables will be enforced . It will also enforce that the first parameter in the calling sequence is called self . | 346 | 53 |
18,620 | def free_parameters ( self ) : free_parameters = collections . OrderedDict ( [ ( k , v ) for k , v in self . parameters . iteritems ( ) if v . free ] ) return free_parameters | Returns a dictionary of free parameters for this function | 51 | 9 |
18,621 | def _get_data_file_path ( data_file ) : try : file_path = pkg_resources . resource_filename ( "astromodels" , 'data/%s' % data_file ) except KeyError : raise IOError ( "Could not read or find data file %s. Try reinstalling astromodels. If this does not fix your " "problem, open an issue on github." % ( data_file ) ) else : return os . path . abspath ( file_path ) | Returns the absolute path to the required data files . | 113 | 10 |
18,622 | def _setup ( self ) : tablepath = _get_data_file_path ( "dark_matter/gammamc_dif.dat" ) self . _data = np . loadtxt ( tablepath ) channel_index_mapping = { 1 : 8 , # ee 2 : 6 , # mumu 3 : 3 , # tautau 4 : 1 , # bb 5 : 2 , # tt 6 : 7 , # gg 7 : 4 , # ww 8 : 5 , # zz 9 : 0 , # cc 10 : 10 , # uu 11 : 11 , # dd 12 : 9 , # ss } # Number of decades in x = log10(E/M) ndec = 10.0 xedge = np . linspace ( 0 , 1.0 , 251 ) self . _x = 0.5 * ( xedge [ 1 : ] + xedge [ : - 1 ] ) * ndec - ndec ichan = channel_index_mapping [ int ( self . channel . value ) ] # These are the mass points self . _mass = np . array ( [ 2.0 , 4.0 , 6.0 , 8.0 , 10.0 , 25.0 , 50.0 , 80.3 , 91.2 , 100.0 , 150.0 , 176.0 , 200.0 , 250.0 , 350.0 , 500.0 , 750.0 , 1000.0 , 1500.0 , 2000.0 , 3000.0 , 5000.0 , 7000.0 , 1E4 ] ) self . _dn = self . _data . reshape ( ( 12 , 24 , 250 ) ) self . _dn_interp = RegularGridInterpolator ( [ self . _mass , self . _x ] , self . _dn [ ichan , : , : ] , bounds_error = False , fill_value = None ) if self . mass . value > 10000 : print "Warning: DMFitFunction only appropriate for masses <= 10 TeV" print "To model DM from 2 GeV < mass < 1 PeV use DMSpectra" | Mapping between the channel codes and the rows in the gammamc file | 459 | 16 |
18,623 | def is_valid_variable_name ( string_to_check ) : try : parse ( '{} = None' . format ( string_to_check ) ) return True except ( SyntaxError , ValueError , TypeError ) : return False | Returns whether the provided name is a valid variable name in Python | 53 | 12 |
18,624 | def _check_unit ( new_unit , old_unit ) : try : new_unit . physical_type except AttributeError : raise UnitMismatch ( "The provided unit (%s) has no physical type. Was expecting a unit for %s" % ( new_unit , old_unit . physical_type ) ) if new_unit . physical_type != old_unit . physical_type : raise UnitMismatch ( "Physical type mismatch: you provided a unit for %s instead of a unit for %s" % ( new_unit . physical_type , old_unit . physical_type ) ) | Check that the new unit is compatible with the old unit for the quantity described by variable_name | 132 | 19 |
18,625 | def peak_energy ( self ) : # Eq. 6 in Massaro et al. 2004 # (http://adsabs.harvard.edu/abs/2004A%26A...413..489M) return self . piv . value * pow ( 10 , ( ( 2 + self . alpha . value ) * np . log ( 10 ) ) / ( 2 * self . beta . value ) ) | Returns the peak energy in the nuFnu spectrum | 85 | 10 |
18,626 | def in_unit_of ( self , unit , as_quantity = False ) : new_unit = u . Unit ( unit ) new_quantity = self . as_quantity . to ( new_unit ) if as_quantity : return new_quantity else : return new_quantity . value | Return the current value transformed to the new units | 67 | 9 |
18,627 | def _get_value ( self ) : # This is going to be true (possibly) only for derived classes. It is here to make the code cleaner # and also to avoid infinite recursion if self . _aux_variable : return self . _aux_variable [ 'law' ] ( self . _aux_variable [ 'variable' ] . value ) if self . _transformation is None : return self . _internal_value else : # A transformation is set. Transform back from internal value to true value # # print("Interval value is %s" % self._internal_value) # print("Returning %s" % self._transformation.backward(self._internal_value)) return self . _transformation . backward ( self . _internal_value ) | Return current parameter value | 164 | 4 |
18,628 | def _set_value ( self , new_value ) : if self . min_value is not None and new_value < self . min_value : raise SettingOutOfBounds ( "Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}" . format ( self . name , new_value , self . min_value ) ) if self . max_value is not None and new_value > self . max_value : raise SettingOutOfBounds ( "Trying to set parameter {0} = {1}, which is more than the maximum allowed {2}" . format ( self . name , new_value , self . max_value ) ) # Issue a warning if there is an auxiliary variable, as the setting does not have any effect if self . has_auxiliary_variable ( ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "always" , RuntimeWarning ) warnings . warn ( "You are trying to assign to a parameter which is either linked or " "has auxiliary variables. The assignment has no effect." , RuntimeWarning ) # Save the value as a pure floating point to avoid the overhead of the astropy.units machinery when # not needed if self . _transformation is None : new_internal_value = new_value else : new_internal_value = self . _transformation . forward ( new_value ) # If the parameter has changed, update its value and call the callbacks if needed if new_internal_value != self . _internal_value : # Update self . _internal_value = new_internal_value # Call the callbacks (if any) for callback in self . _callbacks : try : callback ( self ) except : raise NotCallableOrErrorInCall ( "Could not call callback for parameter %s" % self . name ) | Sets the current value of the parameter ensuring that it is within the allowed range . | 393 | 17 |
18,629 | def _set_internal_value ( self , new_internal_value ) : if new_internal_value != self . _internal_value : self . _internal_value = new_internal_value # Call callbacks if any for callback in self . _callbacks : callback ( self ) | This is supposed to be only used by fitting engines | 62 | 10 |
18,630 | def _set_min_value ( self , min_value ) : # Check that the min value can be transformed if a transformation is present if self . _transformation is not None : if min_value is not None : try : _ = self . _transformation . forward ( min_value ) except FloatingPointError : raise ValueError ( "The provided minimum %s cannot be transformed with the transformation %s which " "is defined for the parameter %s" % ( min_value , type ( self . _transformation ) , self . path ) ) # Store the minimum as a pure float self . _external_min_value = min_value # Check that the current value of the parameter is still within the boundaries. If not, issue a warning if self . _external_min_value is not None and self . value < self . _external_min_value : warnings . warn ( "The current value of the parameter %s (%s) " "was below the new minimum %s." % ( self . name , self . value , self . _external_min_value ) , exceptions . RuntimeWarning ) self . value = self . _external_min_value | Sets current minimum allowed value | 247 | 6 |
18,631 | def _set_max_value ( self , max_value ) : self . _external_max_value = max_value # Check that the current value of the parameter is still within the boundaries. If not, issue a warning if self . _external_max_value is not None and self . value > self . _external_max_value : warnings . warn ( "The current value of the parameter %s (%s) " "was above the new maximum %s." % ( self . name , self . value , self . _external_max_value ) , exceptions . RuntimeWarning ) self . value = self . _external_max_value | Sets current maximum allowed value | 137 | 6 |
18,632 | def _set_bounds ( self , bounds ) : # Use the properties so that the checks and the handling of units are made automatically min_value , max_value = bounds # Remove old boundaries to avoid problems with the new one, if the current value was within the old boundaries # but is not within the new ones (it will then be adjusted automatically later) self . min_value = None self . max_value = None self . min_value = min_value self . max_value = max_value | Sets the boundaries for this parameter to min_value and max_value | 107 | 15 |
18,633 | def _set_prior ( self , prior ) : if prior is None : # Removing prior self . _prior = None else : # Try and call the prior with the current value of the parameter try : _ = prior ( self . value ) except : raise NotCallableOrErrorInCall ( "Could not call the provided prior. " + "Is it a function accepting the current value of the parameter?" ) try : prior . set_units ( self . unit , u . dimensionless_unscaled ) except AttributeError : raise NotCallableOrErrorInCall ( "It looks like the provided prior is not a astromodels function." ) self . _prior = prior | Set prior for this parameter . The prior must be a function accepting the current value of the parameter as input and giving the probability density as output . | 147 | 29 |
18,634 | def set_uninformative_prior ( self , prior_class ) : prior_instance = prior_class ( ) if self . min_value is None : raise ParameterMustHaveBounds ( "Parameter %s does not have a defined minimum. Set one first, then re-run " "set_uninformative_prior" % self . path ) else : try : prior_instance . lower_bound = self . min_value except SettingOutOfBounds : raise SettingOutOfBounds ( "Cannot use minimum of %s for prior %s" % ( self . min_value , prior_instance . name ) ) if self . max_value is None : raise ParameterMustHaveBounds ( "Parameter %s does not have a defined maximum. Set one first, then re-run " "set_uninformative_prior" % self . path ) else : # pragma: no cover try : prior_instance . upper_bound = self . max_value except SettingOutOfBounds : raise SettingOutOfBounds ( "Cannot use maximum of %s for prior %s" % ( self . max_value , prior_instance . name ) ) assert np . isfinite ( prior_instance . upper_bound . value ) , "The parameter %s must have a finite maximum" % self . name assert np . isfinite ( prior_instance . lower_bound . value ) , "The parameter %s must have a finite minimum" % self . name self . _set_prior ( prior_instance ) | Sets the prior for the parameter to a uniform prior between the current minimum and maximum or a log - uniform prior between the current minimum and maximum . | 332 | 30 |
18,635 | def remove_auxiliary_variable ( self ) : if not self . has_auxiliary_variable ( ) : # do nothing, but print a warning warnings . warn ( "Cannot remove a non-existing auxiliary variable" , RuntimeWarning ) else : # Remove the law from the children self . _remove_child ( self . _aux_variable [ 'law' ] . name ) # Clean up the dictionary self . _aux_variable = { } # Set the parameter to the status it has before the auxiliary variable was created self . free = self . _old_free | Remove an existing auxiliary variable | 120 | 5 |
18,636 | def _get_child_from_path ( self , path ) : keys = path . split ( "." ) this_child = self for key in keys : try : this_child = this_child . _get_child ( key ) except KeyError : raise KeyError ( "Child %s not found" % path ) return this_child | Return a children below this level starting from a path of the kind this_level . something . something . name | 73 | 22 |
18,637 | def _find_instances ( self , cls ) : instances = collections . OrderedDict ( ) for child_name , child in self . _children . iteritems ( ) : if isinstance ( child , cls ) : key_name = "." . join ( child . _get_path ( ) ) instances [ key_name ] = child # Now check if the instance has children, # and if it does go deeper in the tree # NOTE: an empty dictionary evaluate as False if child . _children : instances . update ( child . _find_instances ( cls ) ) else : instances . update ( child . _find_instances ( cls ) ) return instances | Find all the instances of cls below this node . | 146 | 11 |
18,638 | def find_library ( library_root , additional_places = None ) : # find_library searches for all system paths in a system independent way (but NOT those defined in # LD_LIBRARY_PATH or DYLD_LIBRARY_PATH) first_guess = ctypes . util . find_library ( library_root ) if first_guess is not None : # Found in one of the system paths if sys . platform . lower ( ) . find ( "linux" ) >= 0 : # On linux the linker already knows about these paths, so we # can return None as path return sanitize_lib_name ( first_guess ) , None elif sys . platform . lower ( ) . find ( "darwin" ) >= 0 : # On Mac we still need to return the path, because the linker sometimes # does not look into it return sanitize_lib_name ( first_guess ) , os . path . dirname ( first_guess ) else : # Windows is not supported raise NotImplementedError ( "Platform %s is not supported" % sys . platform ) else : # could not find it. Let's examine LD_LIBRARY_PATH or DYLD_LIBRARY_PATH # (if they sanitize_lib_name(first_guess), are not defined, possible_locations will become [""] which will # be handled by the next loop) if sys . platform . lower ( ) . find ( "linux" ) >= 0 : # Unix / linux possible_locations = os . environ . get ( "LD_LIBRARY_PATH" , "" ) . split ( ":" ) elif sys . platform . lower ( ) . find ( "darwin" ) >= 0 : # Mac possible_locations = os . environ . get ( "DYLD_LIBRARY_PATH" , "" ) . split ( ":" ) else : raise NotImplementedError ( "Platform %s is not supported" % sys . platform ) if additional_places is not None : possible_locations . extend ( additional_places ) # Now look into the search paths library_name = None library_dir = None for search_path in possible_locations : if search_path == "" : # This can happen if there are more than one :, or if nor LD_LIBRARY_PATH # nor DYLD_LIBRARY_PATH are defined (because of the default use above for os.environ.get) continue results = glob . glob ( os . path . join ( search_path , "lib%s*" % library_root ) ) if len ( results ) >= 1 : # Results contain things like libXS.so, libXSPlot.so, libXSpippo.so # If we are looking for libXS.so, we need to make sure that we get the right one! for result in results : if re . match ( "lib%s[\-_\.]" % library_root , os . path . basename ( result ) ) is None : continue else : # FOUND IT # This is the full path of the library, like /usr/lib/libcfitsio_1.2.3.4 library_name = result library_dir = search_path break else : continue if library_name is not None : break if library_name is None : return None , None else : # Sanitize the library name to get from the fully-qualified path to just the library name # (/usr/lib/libgfortran.so.3.0 becomes gfortran) return sanitize_lib_name ( library_name ) , library_dir | Returns the name of the library without extension | 793 | 8 |
18,639 | def dict_to_table ( dictionary , list_of_keys = None ) : # assert len(dictionary.values()) > 0, "Dictionary cannot be empty" # Create an empty table table = Table ( ) # If the dictionary is not empty, fill the table if len ( dictionary ) > 0 : # Add the names as first column table [ 'name' ] = dictionary . keys ( ) # Now add all other properties # Use the first parameter as prototype prototype = dictionary . values ( ) [ 0 ] column_names = prototype . keys ( ) # If we have a white list for the columns, use it if list_of_keys is not None : column_names = filter ( lambda key : key in list_of_keys , column_names ) # Fill the table for column_name in column_names : table [ column_name ] = map ( lambda x : x [ column_name ] , dictionary . values ( ) ) return table | Return a table representing the dictionary . | 201 | 7 |
18,640 | def _base_repr_ ( self , html = False , show_name = True , * * kwargs ) : table_id = 'table{id}' . format ( id = id ( self ) ) data_lines , outs = self . formatter . _pformat_table ( self , tableid = table_id , html = html , max_width = ( - 1 if html else None ) , show_name = show_name , show_unit = None , show_dtype = False ) out = '\n' . join ( data_lines ) # if astropy.table.six.PY2 and isinstance(out, astropy.table.six.text_type): # out = out.encode('utf-8') return out | Override the method in the astropy . Table class to avoid displaying the description and the format of the columns | 167 | 21 |
18,641 | def fetch_cache_key ( request ) : m = hashlib . md5 ( ) m . update ( request . body ) return m . hexdigest ( ) | Returns a hashed cache key . | 35 | 7 |
18,642 | def dispatch ( self , request , * args , * * kwargs ) : if not graphql_api_settings . CACHE_ACTIVE : return self . super_call ( request , * args , * * kwargs ) cache = caches [ "default" ] operation_ast = self . get_operation_ast ( request ) if operation_ast and operation_ast . operation == "mutation" : cache . clear ( ) return self . super_call ( request , * args , * * kwargs ) cache_key = "_graplql_{}" . format ( self . fetch_cache_key ( request ) ) response = cache . get ( cache_key ) if not response : response = self . super_call ( request , * args , * * kwargs ) # cache key and value cache . set ( cache_key , response , timeout = graphql_api_settings . CACHE_TIMEOUT ) return response | Fetches queried data from graphql and returns cached & hashed key . | 202 | 17 |
18,643 | def _parse ( partial_dt ) : dt = None try : if isinstance ( partial_dt , datetime ) : dt = partial_dt if isinstance ( partial_dt , date ) : dt = _combine_date_time ( partial_dt , time ( 0 , 0 , 0 ) ) if isinstance ( partial_dt , time ) : dt = _combine_date_time ( date . today ( ) , partial_dt ) if isinstance ( partial_dt , ( int , float ) ) : dt = datetime . fromtimestamp ( partial_dt ) if isinstance ( partial_dt , ( str , bytes ) ) : dt = parser . parse ( partial_dt , default = timezone . now ( ) ) if dt is not None and timezone . is_naive ( dt ) : dt = timezone . make_aware ( dt ) return dt except ValueError : return None | parse a partial datetime object to a complete datetime object | 205 | 12 |
18,644 | def clean_dict ( d ) : if not isinstance ( d , ( dict , list ) ) : return d if isinstance ( d , list ) : return [ v for v in ( clean_dict ( v ) for v in d ) if v ] return OrderedDict ( [ ( k , v ) for k , v in ( ( k , clean_dict ( v ) ) for k , v in list ( d . items ( ) ) ) if v ] ) | Remove all empty fields in a nested dict | 100 | 8 |
18,645 | def _get_queryset ( klass ) : if isinstance ( klass , QuerySet ) : return klass elif isinstance ( klass , Manager ) : manager = klass elif isinstance ( klass , ModelBase ) : manager = klass . _default_manager else : if isinstance ( klass , type ) : klass__name = klass . __name__ else : klass__name = klass . __class__ . __name__ raise ValueError ( "Object is of type '{}', but must be a Django Model, " "Manager, or QuerySet" . format ( klass__name ) ) return manager . all ( ) | Returns a QuerySet from a Model Manager or QuerySet . Created to make get_object_or_404 and get_list_or_404 more DRY . | 145 | 34 |
18,646 | def find_schema_paths ( schema_files_path = DEFAULT_SCHEMA_FILES_PATH ) : paths = [ ] for path in schema_files_path : if os . path . isdir ( path ) : paths . append ( path ) if paths : return paths raise SchemaFilesNotFound ( "Searched " + os . pathsep . join ( schema_files_path ) ) | Searches the locations in the SCHEMA_FILES_PATH to try to find where the schema SQL files are located . | 91 | 26 |
18,647 | def run ( ) : # create a arg parser and configure it. parser = argparse . ArgumentParser ( description = 'SharQ Server.' ) parser . add_argument ( '-c' , '--config' , action = 'store' , required = True , help = 'Absolute path of the SharQ configuration file.' , dest = 'sharq_config' ) parser . add_argument ( '-gc' , '--gunicorn-config' , action = 'store' , required = False , help = 'Gunicorn configuration file.' , dest = 'gunicorn_config' ) parser . add_argument ( '--version' , action = 'version' , version = 'SharQ Server %s' % __version__ ) args = parser . parse_args ( ) # read the configuration file and set gunicorn options. config_parser = ConfigParser . SafeConfigParser ( ) # get the full path of the config file. sharq_config = os . path . abspath ( args . sharq_config ) config_parser . read ( sharq_config ) host = config_parser . get ( 'sharq-server' , 'host' ) port = config_parser . get ( 'sharq-server' , 'port' ) bind = '%s:%s' % ( host , port ) try : workers = config_parser . get ( 'sharq-server' , 'workers' ) except ConfigParser . NoOptionError : workers = number_of_workers ( ) try : accesslog = config_parser . get ( 'sharq-server' , 'accesslog' ) except ConfigParser . NoOptionError : accesslog = None options = { 'bind' : bind , 'workers' : workers , 'worker_class' : 'gevent' # required for sharq to function. } if accesslog : options . update ( { 'accesslog' : accesslog } ) if args . gunicorn_config : gunicorn_config = os . path . abspath ( args . gunicorn_config ) options . update ( { 'config' : gunicorn_config } ) print """ ___ _ ___ ___ / __| |_ __ _ _ _ / _ \ / __| ___ _ ___ _____ _ _ \__ \ ' \/ _` | '_| (_) | \__ \/ -_) '_\ V / -_) '_| |___/_||_\__,_|_| \__\_\ |___/\___|_| \_/\___|_| Version: %s Listening on: %s """ % ( __version__ , bind ) server = setup_server ( sharq_config ) SharQServerApplicationRunner ( server . app , options ) . run ( ) | Exposes a CLI to configure the SharQ Server and runs the server . | 602 | 15 |
18,648 | def setup_server ( config_path ) : # configure the SharQ server server = SharQServer ( config_path ) # start the requeue loop gevent . spawn ( server . requeue ) return server | Configure SharQ server start the requeue loop and return the server . | 46 | 16 |
18,649 | def requeue ( self ) : job_requeue_interval = float ( self . config . get ( 'sharq' , 'job_requeue_interval' ) ) while True : self . sq . requeue ( ) gevent . sleep ( job_requeue_interval / 1000.00 ) | Loop endlessly and requeue expired jobs . | 70 | 9 |
18,650 | def _view_enqueue ( self , queue_type , queue_id ) : response = { 'status' : 'failure' } try : request_data = json . loads ( request . data ) except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 request_data . update ( { 'queue_type' : queue_type , 'queue_id' : queue_id } ) try : response = self . sq . enqueue ( * * request_data ) except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 return jsonify ( * * response ) , 201 | Enqueues a job into SharQ . | 149 | 9 |
18,651 | def _view_dequeue ( self , queue_type ) : response = { 'status' : 'failure' } request_data = { 'queue_type' : queue_type } try : response = self . sq . dequeue ( * * request_data ) if response [ 'status' ] == 'failure' : return jsonify ( * * response ) , 404 except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 return jsonify ( * * response ) | Dequeues a job from SharQ . | 114 | 9 |
18,652 | def _view_finish ( self , queue_type , queue_id , job_id ) : response = { 'status' : 'failure' } request_data = { 'queue_type' : queue_type , 'queue_id' : queue_id , 'job_id' : job_id } try : response = self . sq . finish ( * * request_data ) if response [ 'status' ] == 'failure' : return jsonify ( * * response ) , 404 except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 return jsonify ( * * response ) | Marks a job as finished in SharQ . | 141 | 10 |
18,653 | def _view_interval ( self , queue_type , queue_id ) : response = { 'status' : 'failure' } try : request_data = json . loads ( request . data ) interval = request_data [ 'interval' ] except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 request_data = { 'queue_type' : queue_type , 'queue_id' : queue_id , 'interval' : interval } try : response = self . sq . interval ( * * request_data ) if response [ 'status' ] == 'failure' : return jsonify ( * * response ) , 404 except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 return jsonify ( * * response ) | Updates the queue interval in SharQ . | 184 | 9 |
18,654 | def _view_metrics ( self , queue_type , queue_id ) : response = { 'status' : 'failure' } request_data = { } if queue_type : request_data [ 'queue_type' ] = queue_type if queue_id : request_data [ 'queue_id' ] = queue_id try : response = self . sq . metrics ( * * request_data ) except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 return jsonify ( * * response ) | Gets SharQ metrics based on the params . | 123 | 10 |
18,655 | def _view_clear_queue ( self , queue_type , queue_id ) : response = { 'status' : 'failure' } try : request_data = json . loads ( request . data ) except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 request_data . update ( { 'queue_type' : queue_type , 'queue_id' : queue_id } ) try : response = self . sq . clear_queue ( * * request_data ) except Exception , e : response [ 'message' ] = e . message return jsonify ( * * response ) , 400 return jsonify ( * * response ) | remove queueu from SharQ based on the queue_type and queue_id . | 149 | 17 |
18,656 | def start_patching ( name = None ) : # type: (Optional[str]) -> None global _factory_map , _patchers , _mocks if _patchers and name is None : warnings . warn ( 'start_patching() called again, already patched' ) _pre_import ( ) if name is not None : factory = _factory_map [ name ] items = [ ( name , factory ) ] else : items = _factory_map . items ( ) for name , factory in items : patcher = mock . patch ( name , new = factory ( ) ) mocked = patcher . start ( ) _patchers [ name ] = patcher _mocks [ name ] = mocked | Initiate mocking of the functions listed in _factory_map . | 152 | 15 |
18,657 | def stop_patching ( name = None ) : # type: (Optional[str]) -> None global _patchers , _mocks if not _patchers : warnings . warn ( 'stop_patching() called again, already stopped' ) if name is not None : items = [ ( name , _patchers [ name ] ) ] else : items = list ( _patchers . items ( ) ) for name , patcher in items : patcher . stop ( ) del _patchers [ name ] del _mocks [ name ] | Finish the mocking initiated by start_patching | 114 | 9 |
18,658 | def standardize_back ( xs , offset , scale ) : try : offset = float ( offset ) except : raise ValueError ( 'The argument offset is not None or float.' ) try : scale = float ( scale ) except : raise ValueError ( 'The argument scale is not None or float.' ) try : xs = np . array ( xs , dtype = "float64" ) except : raise ValueError ( 'The argument xs is not numpy array or similar.' ) return xs * scale + offset | This is function for de - standarization of input series . | 111 | 13 |
18,659 | def standardize ( x , offset = None , scale = None ) : if offset == None : offset = np . array ( x ) . mean ( ) else : try : offset = float ( offset ) except : raise ValueError ( 'The argument offset is not None or float' ) if scale == None : scale = np . array ( x ) . std ( ) else : try : scale = float ( scale ) except : raise ValueError ( 'The argument scale is not None or float' ) try : x = np . array ( x , dtype = "float64" ) except : raise ValueError ( 'The argument x is not numpy array or similar.' ) return ( x - offset ) / scale | This is function for standarization of input series . | 148 | 11 |
18,660 | def input_from_history ( a , n , bias = False ) : if not type ( n ) == int : raise ValueError ( 'The argument n must be int.' ) if not n > 0 : raise ValueError ( 'The argument n must be greater than 0' ) try : a = np . array ( a , dtype = "float64" ) except : raise ValueError ( 'The argument a is not numpy array or similar.' ) x = np . array ( [ a [ i : i + n ] for i in range ( len ( a ) - n + 1 ) ] ) if bias : x = np . vstack ( ( x . T , np . ones ( len ( x ) ) ) ) . T return x | This is function for creation of input matrix . | 157 | 9 |
18,661 | def init_weights ( self , w , n = - 1 ) : if n == - 1 : n = self . n if type ( w ) == str : if w == "random" : w = np . random . normal ( 0 , 0.5 , n ) elif w == "zeros" : w = np . zeros ( n ) else : raise ValueError ( 'Impossible to understand the w' ) elif len ( w ) == n : try : w = np . array ( w , dtype = "float64" ) except : raise ValueError ( 'Impossible to understand the w' ) else : raise ValueError ( 'Impossible to understand the w' ) self . w = w | This function initialises the adaptive weights of the filter . | 152 | 11 |
18,662 | def predict ( self , x ) : y = np . dot ( self . w , x ) return y | This function calculates the new output value y from input array x . | 22 | 13 |
18,663 | def explore_learning ( self , d , x , mu_start = 0 , mu_end = 1. , steps = 100 , ntrain = 0.5 , epochs = 1 , criteria = "MSE" , target_w = False ) : mu_range = np . linspace ( mu_start , mu_end , steps ) errors = np . zeros ( len ( mu_range ) ) for i , mu in enumerate ( mu_range ) : # init self . init_weights ( "zeros" ) self . mu = mu # run y , e , w = self . pretrained_run ( d , x , ntrain = ntrain , epochs = epochs ) if type ( target_w ) != bool : errors [ i ] = get_mean_error ( w [ - 1 ] - target_w , function = criteria ) else : errors [ i ] = get_mean_error ( e , function = criteria ) return errors , mu_range | Test what learning rate is the best . | 210 | 8 |
18,664 | def check_float_param ( self , param , low , high , name ) : try : param = float ( param ) except : raise ValueError ( 'Parameter {} is not float or similar' . format ( name ) ) if low != None or high != None : if not low <= param <= high : raise ValueError ( 'Parameter {} is not in range <{}, {}>' . format ( name , low , high ) ) return param | Check if the value of the given parameter is in the given range and a float . Designed for testing parameters like mu and eps . To pass this function the variable param must be able to be converted into a float with a value between low and high . | 93 | 51 |
18,665 | def check_int_param ( self , param , low , high , name ) : try : param = int ( param ) except : raise ValueError ( 'Parameter {} is not int or similar' . format ( name ) ) if low != None or high != None : if not low <= param <= high : raise ValueError ( 'Parameter {} is not in range <{}, {}>' . format ( name , low , high ) ) return param | Check if the value of the given parameter is in the given range and an int . Designed for testing parameters like mu and eps . To pass this function the variable param must be able to be converted into a float with a value between low and high . | 93 | 51 |
18,666 | def MAE ( x1 , x2 = - 1 ) : e = get_valid_error ( x1 , x2 ) return np . sum ( np . abs ( e ) ) / float ( len ( e ) ) | Mean absolute error - this function accepts two series of data or directly one series with error . | 48 | 19 |
18,667 | def MSE ( x1 , x2 = - 1 ) : e = get_valid_error ( x1 , x2 ) return np . dot ( e , e ) / float ( len ( e ) ) | Mean squared error - this function accepts two series of data or directly one series with error . | 45 | 19 |
18,668 | def RMSE ( x1 , x2 = - 1 ) : e = get_valid_error ( x1 , x2 ) return np . sqrt ( np . dot ( e , e ) / float ( len ( e ) ) ) | Root - mean - square error - this function accepts two series of data or directly one series with error . | 51 | 21 |
18,669 | def ELBND ( w , e , function = "max" ) : # check if the function is known if not function in [ "max" , "sum" ] : raise ValueError ( 'Unknown output function' ) # get length of data and number of parameters N = w . shape [ 0 ] n = w . shape [ 1 ] # get abs dw from w dw = np . zeros ( w . shape ) dw [ : - 1 ] = np . abs ( np . diff ( w , axis = 0 ) ) # absolute values of product of increments and error a = np . random . random ( ( 5 , 2 ) ) b = a . T * np . array ( [ 1 , 2 , 3 , 4 , 5 ] ) elbnd = np . abs ( ( dw . T * e ) . T ) # apply output function if function == "max" : elbnd = np . max ( elbnd , axis = 1 ) elif function == "sum" : elbnd = np . sum ( elbnd , axis = 1 ) # return output return elbnd | This function estimates Error and Learning Based Novelty Detection measure from given data . | 232 | 15 |
18,670 | def LDA_base ( x , labels ) : classes = np . array ( tuple ( set ( labels ) ) ) cols = x . shape [ 1 ] # mean values for every class means = np . zeros ( ( len ( classes ) , cols ) ) for i , cl in enumerate ( classes ) : means [ i ] = np . mean ( x [ labels == cl ] , axis = 0 ) # scatter matrices scatter_within = np . zeros ( ( cols , cols ) ) for cl , mean in zip ( classes , means ) : scatter_class = np . zeros ( ( cols , cols ) ) for row in x [ labels == cl ] : dif = row - mean scatter_class += np . dot ( dif . reshape ( cols , 1 ) , dif . reshape ( 1 , cols ) ) scatter_within += scatter_class total_mean = np . mean ( x , axis = 0 ) scatter_between = np . zeros ( ( cols , cols ) ) for cl , mean in zip ( classes , means ) : dif = mean - total_mean dif_product = np . dot ( dif . reshape ( cols , 1 ) , dif . reshape ( 1 , cols ) ) scatter_between += x [ labels == cl , : ] . shape [ 0 ] * dif_product # eigenvalues and eigenvectors from scatter matrices scatter_product = np . dot ( np . linalg . inv ( scatter_within ) , scatter_between ) eigen_values , eigen_vectors = np . linalg . eig ( scatter_product ) return eigen_values , eigen_vectors | Base function used for Linear Discriminant Analysis . | 372 | 10 |
18,671 | def LDA ( x , labels , n = False ) : # select n if not provided if not n : n = x . shape [ 1 ] - 1 # validate inputs try : x = np . array ( x ) except : raise ValueError ( 'Impossible to convert x to a numpy array.' ) assert type ( n ) == int , "Provided n is not an integer." assert x . shape [ 1 ] > n , "The requested n is bigger than \ number of features in x." # make the LDA eigen_values , eigen_vectors = LDA_base ( x , labels ) # sort the eigen vectors according to eigen values eigen_order = eigen_vectors . T [ ( - eigen_values ) . argsort ( ) ] return eigen_order [ : n ] . dot ( x . T ) . T | Linear Discriminant Analysis function . | 186 | 8 |
18,672 | def LDA_discriminants ( x , labels ) : # validate inputs try : x = np . array ( x ) except : raise ValueError ( 'Impossible to convert x to a numpy array.' ) # make the LDA eigen_values , eigen_vectors = LDA_base ( x , labels ) return eigen_values [ ( - eigen_values ) . argsort ( ) ] | Linear Discriminant Analysis helper for determination how many columns of data should be reduced . | 90 | 18 |
18,673 | def read_memory ( self ) : if self . mem_empty == True : if self . mem_idx == 0 : m_x = np . zeros ( self . n ) m_d = 0 else : m_x = np . mean ( self . mem_x [ : self . mem_idx + 1 ] , axis = 0 ) m_d = np . mean ( self . mem_d [ : self . mem_idx ] ) else : m_x = np . mean ( self . mem_x , axis = 0 ) m_d = np . mean ( np . delete ( self . mem_d , self . mem_idx ) ) self . mem_idx += 1 if self . mem_idx > len ( self . mem_x ) - 1 : self . mem_idx = 0 self . mem_empty = False return m_d , m_x | This function read mean value of target d and input vector x from history | 195 | 14 |
18,674 | def learning_entropy ( w , m = 10 , order = 1 , alpha = False ) : w = np . array ( w ) # get length of data and number of parameters N = w . shape [ 0 ] n = w . shape [ 1 ] # get abs dw from w dw = np . copy ( w ) dw [ order : ] = np . abs ( np . diff ( dw , n = order , axis = 0 ) ) # average floting window - window is k-m ... k-1 awd = np . zeros ( w . shape ) if not alpha : # estimate the ALPHA with multiscale approach swd = np . zeros ( w . shape ) for k in range ( m , N ) : awd [ k ] = np . mean ( dw [ k - m : k ] , axis = 0 ) swd [ k ] = np . std ( dw [ k - m : k ] , axis = 0 ) # estimate the points of entropy eps = 1e-10 # regularization term le = ( dw - awd ) / ( swd + eps ) else : # estimate the ALPHA with direct approach for k in range ( m , N ) : awd [ k ] = np . mean ( dw [ k - m : k ] , axis = 0 ) # estimate the points of entropy alphas = np . array ( alpha ) fh = np . zeros ( N ) for alpha in alphas : fh += np . sum ( awd * alpha < dw , axis = 1 ) le = fh / float ( n * len ( alphas ) ) # clear unknown zone on begining le [ : m ] = 0 # return output return le | This function estimates Learning Entropy . | 361 | 7 |
18,675 | def activation ( self , x , f = "sigmoid" , der = False ) : if f == "sigmoid" : if der : return x * ( 1 - x ) return 1. / ( 1 + np . exp ( - x ) ) elif f == "tanh" : if der : return 1 - x ** 2 return ( 2. / ( 1 + np . exp ( - 2 * x ) ) ) - 1 | This function process values of layer outputs with activation function . | 94 | 11 |
18,676 | def train ( self , x , d , epochs = 10 , shuffle = False ) : # measure the data and check if the dimmension agree N = len ( x ) if not len ( d ) == N : raise ValueError ( 'The length of vector d and matrix x must agree.' ) if not len ( x [ 0 ] ) == self . n_input : raise ValueError ( 'The number of network inputs is not correct.' ) if self . outputs == 1 : if not len ( d . shape ) == 1 : raise ValueError ( 'For one output MLP the d must have one dimension' ) else : if not d . shape [ 1 ] == self . outputs : raise ValueError ( 'The number of outputs must agree with number of columns in d' ) try : x = np . array ( x ) d = np . array ( d ) except : raise ValueError ( 'Impossible to convert x or d to a numpy array' ) # create empty arrays if self . outputs == 1 : e = np . zeros ( epochs * N ) else : e = np . zeros ( ( epochs * N , self . outputs ) ) MSE = np . zeros ( epochs ) # shuffle data if demanded if shuffle : randomize = np . arange ( len ( x ) ) np . random . shuffle ( randomize ) x = x [ randomize ] d = d [ randomize ] # adaptation loop for epoch in range ( epochs ) : for k in range ( N ) : self . predict ( x [ k ] ) e [ ( epoch * N ) + k ] = self . update ( d [ k ] ) MSE [ epoch ] = np . sum ( e [ epoch * N : ( epoch + 1 ) * N - 1 ] ** 2 ) / N return e , MSE | Function for batch training of MLP . | 386 | 8 |
18,677 | def run ( self , x ) : # measure the data and check if the dimmension agree try : x = np . array ( x ) except : raise ValueError ( 'Impossible to convert x to a numpy array' ) N = len ( x ) # create empty arrays if self . outputs == 1 : y = np . zeros ( N ) else : y = np . zeros ( ( N , self . outputs ) ) # predict data in loop for k in range ( N ) : y [ k ] = self . predict ( x [ k ] ) return y | Function for batch usage of already trained and tested MLP . | 121 | 12 |
18,678 | def PCA_components ( x ) : # validate inputs try : x = np . array ( x ) except : raise ValueError ( 'Impossible to convert x to a numpy array.' ) # eigen values and eigen vectors of data covariance matrix eigen_values , eigen_vectors = np . linalg . eig ( np . cov ( x . T ) ) # sort eigen vectors according biggest eigen value eigen_order = eigen_vectors . T [ ( - eigen_values ) . argsort ( ) ] # form output - order the eigenvalues return eigen_values [ ( - eigen_values ) . argsort ( ) ] | Principal Component Analysis helper to check out eigenvalues of components . | 148 | 14 |
18,679 | def PCA ( x , n = False ) : # select n if not provided if not n : n = x . shape [ 1 ] - 1 # validate inputs try : x = np . array ( x ) except : raise ValueError ( 'Impossible to convert x to a numpy array.' ) assert type ( n ) == int , "Provided n is not an integer." assert x . shape [ 1 ] > n , "The requested n is bigger than \ number of features in x." # eigen values and eigen vectors of data covariance matrix eigen_values , eigen_vectors = np . linalg . eig ( np . cov ( x . T ) ) # sort eigen vectors according biggest eigen value eigen_order = eigen_vectors . T [ ( - eigen_values ) . argsort ( ) ] # form output - reduced x matrix return eigen_order [ : n ] . dot ( x . T ) . T | Principal component analysis function . | 207 | 6 |
18,680 | def clean_axis ( axis ) : axis . get_xaxis ( ) . set_ticks ( [ ] ) axis . get_yaxis ( ) . set_ticks ( [ ] ) for spine in list ( axis . spines . values ( ) ) : spine . set_visible ( False ) | Remove ticks tick labels and frame from axis | 65 | 8 |
18,681 | def get_seaborn_colorbar ( dfr , classes ) : levels = sorted ( list ( set ( classes . values ( ) ) ) ) paldict = { lvl : pal for ( lvl , pal ) in zip ( levels , sns . cubehelix_palette ( len ( levels ) , light = 0.9 , dark = 0.1 , reverse = True , start = 1 , rot = - 2 ) , ) } lvl_pal = { cls : paldict [ lvl ] for ( cls , lvl ) in list ( classes . items ( ) ) } col_cb = pd . Series ( dfr . index ) . map ( lvl_pal ) # The col_cb Series index now has to match the dfr.index, but # we don't create the Series with this (and if we try, it # fails) - so change it with this line col_cb . index = dfr . index return col_cb | Return a colorbar representing classes for a Seaborn plot . | 204 | 13 |
18,682 | def get_safe_seaborn_labels ( dfr , labels ) : if labels is not None : return [ labels . get ( i , i ) for i in dfr . index ] return [ i for i in dfr . index ] | Returns labels guaranteed to correspond to the dataframe . | 53 | 10 |
18,683 | def get_seaborn_clustermap ( dfr , params , title = None , annot = True ) : fig = sns . clustermap ( dfr , cmap = params . cmap , vmin = params . vmin , vmax = params . vmax , col_colors = params . colorbar , row_colors = params . colorbar , figsize = ( params . figsize , params . figsize ) , linewidths = params . linewidths , xticklabels = params . labels , yticklabels = params . labels , annot = annot , ) fig . cax . yaxis . set_label_position ( "left" ) if title : fig . cax . set_ylabel ( title ) # Rotate ticklabels fig . ax_heatmap . set_xticklabels ( fig . ax_heatmap . get_xticklabels ( ) , rotation = 90 ) fig . ax_heatmap . set_yticklabels ( fig . ax_heatmap . get_yticklabels ( ) , rotation = 0 ) # Return clustermap return fig | Returns a Seaborn clustermap . | 244 | 8 |
18,684 | def heatmap_seaborn ( dfr , outfilename = None , title = None , params = None ) : # Decide on figure layout size: a minimum size is required for # aesthetics, and a maximum to avoid core dumps on rendering. # If we hit the maximum size, we should modify font size. maxfigsize = 120 calcfigsize = dfr . shape [ 0 ] * 1.1 figsize = min ( max ( 8 , calcfigsize ) , maxfigsize ) if figsize == maxfigsize : scale = maxfigsize / calcfigsize sns . set_context ( "notebook" , font_scale = scale ) # Add a colorbar? if params . classes is None : col_cb = None else : col_cb = get_seaborn_colorbar ( dfr , params . classes ) # Labels are defined before we build the clustering # If a label mapping is missing, use the key text as fall back params . labels = get_safe_seaborn_labels ( dfr , params . labels ) # Add attributes to parameter object, and draw heatmap params . colorbar = col_cb params . figsize = figsize params . linewidths = 0.25 fig = get_seaborn_clustermap ( dfr , params , title = title ) # Save to file if outfilename : fig . savefig ( outfilename ) # Return clustermap return fig | Returns seaborn heatmap with cluster dendrograms . | 306 | 13 |
18,685 | def add_mpl_dendrogram ( dfr , fig , heatmap_gs , orientation = "col" ) : # Row or column axes? if orientation == "row" : dists = distance . squareform ( distance . pdist ( dfr ) ) spec = heatmap_gs [ 1 , 0 ] orient = "left" nrows , ncols = 1 , 2 height_ratios = [ 1 ] else : # Column dendrogram dists = distance . squareform ( distance . pdist ( dfr . T ) ) spec = heatmap_gs [ 0 , 1 ] orient = "top" nrows , ncols = 2 , 1 height_ratios = [ 1 , 0.15 ] # Create row dendrogram axis gspec = gridspec . GridSpecFromSubplotSpec ( nrows , ncols , subplot_spec = spec , wspace = 0.0 , hspace = 0.1 , height_ratios = height_ratios , ) dend_axes = fig . add_subplot ( gspec [ 0 , 0 ] ) dend = sch . dendrogram ( sch . linkage ( distance . squareform ( dists ) , method = "complete" ) , color_threshold = np . inf , orientation = orient , ) clean_axis ( dend_axes ) return { "dendrogram" : dend , "gridspec" : gspec } | Return a dendrogram and corresponding gridspec attached to the fig | 308 | 13 |
18,686 | def get_mpl_heatmap_axes ( dfr , fig , heatmap_gs ) : # Create heatmap axis heatmap_axes = fig . add_subplot ( heatmap_gs [ 1 , 1 ] ) heatmap_axes . set_xticks ( np . linspace ( 0 , dfr . shape [ 0 ] - 1 , dfr . shape [ 0 ] ) ) heatmap_axes . set_yticks ( np . linspace ( 0 , dfr . shape [ 0 ] - 1 , dfr . shape [ 0 ] ) ) heatmap_axes . grid ( False ) heatmap_axes . xaxis . tick_bottom ( ) heatmap_axes . yaxis . tick_right ( ) return heatmap_axes | Return axis for Matplotlib heatmap . | 171 | 9 |
18,687 | def add_mpl_colorbar ( dfr , fig , dend , params , orientation = "row" ) : for name in dfr . index [ dend [ "dendrogram" ] [ "leaves" ] ] : if name not in params . classes : params . classes [ name ] = name # Assign a numerical value to each class, for mpl classdict = { cls : idx for ( idx , cls ) in enumerate ( params . classes . values ( ) ) } # colourbar cblist = [ ] for name in dfr . index [ dend [ "dendrogram" ] [ "leaves" ] ] : try : cblist . append ( classdict [ params . classes [ name ] ] ) except KeyError : cblist . append ( classdict [ name ] ) colbar = pd . Series ( cblist ) # Create colourbar axis - could capture if needed if orientation == "row" : cbaxes = fig . add_subplot ( dend [ "gridspec" ] [ 0 , 1 ] ) cbaxes . imshow ( [ [ cbar ] for cbar in colbar . values ] , cmap = plt . get_cmap ( pyani_config . MPL_CBAR ) , interpolation = "nearest" , aspect = "auto" , origin = "lower" , ) else : cbaxes = fig . add_subplot ( dend [ "gridspec" ] [ 1 , 0 ] ) cbaxes . imshow ( [ colbar ] , cmap = plt . get_cmap ( pyani_config . MPL_CBAR ) , interpolation = "nearest" , aspect = "auto" , origin = "lower" , ) clean_axis ( cbaxes ) return colbar | Add class colorbars to Matplotlib heatmap . | 400 | 11 |
18,688 | def add_mpl_labels ( heatmap_axes , rowlabels , collabels , params ) : if params . labels : # If a label mapping is missing, use the key text as fall back rowlabels = [ params . labels . get ( lab , lab ) for lab in rowlabels ] collabels = [ params . labels . get ( lab , lab ) for lab in collabels ] xlabs = heatmap_axes . set_xticklabels ( collabels ) ylabs = heatmap_axes . set_yticklabels ( rowlabels ) for label in xlabs : # Rotate column labels label . set_rotation ( 90 ) for labset in ( xlabs , ylabs ) : # Smaller font for label in labset : label . set_fontsize ( 8 ) | Add labels to Matplotlib heatmap axes in - place . | 186 | 13 |
18,689 | def add_mpl_colorscale ( fig , heatmap_gs , ax_map , params , title = None ) : # Set tick intervals cbticks = [ params . vmin + e * params . vdiff for e in ( 0 , 0.25 , 0.5 , 0.75 , 1 ) ] if params . vmax > 10 : exponent = int ( floor ( log10 ( params . vmax ) ) ) - 1 cbticks = [ int ( round ( e , - exponent ) ) for e in cbticks ] scale_subplot = gridspec . GridSpecFromSubplotSpec ( 1 , 3 , subplot_spec = heatmap_gs [ 0 , 0 ] , wspace = 0.0 , hspace = 0.0 ) scale_ax = fig . add_subplot ( scale_subplot [ 0 , 1 ] ) cbar = fig . colorbar ( ax_map , scale_ax , ticks = cbticks ) if title : cbar . set_label ( title , fontsize = 6 ) cbar . ax . yaxis . set_ticks_position ( "left" ) cbar . ax . yaxis . set_label_position ( "left" ) cbar . ax . tick_params ( labelsize = 6 ) cbar . outline . set_linewidth ( 0 ) return cbar | Add colour scale to heatmap . | 292 | 7 |
18,690 | def heatmap_mpl ( dfr , outfilename = None , title = None , params = None ) : # Layout figure grid and add title # Set figure size by the number of rows in the dataframe figsize = max ( 8 , dfr . shape [ 0 ] * 0.175 ) fig = plt . figure ( figsize = ( figsize , figsize ) ) # if title: # fig.suptitle(title) heatmap_gs = gridspec . GridSpec ( 2 , 2 , wspace = 0.0 , hspace = 0.0 , width_ratios = [ 0.3 , 1 ] , height_ratios = [ 0.3 , 1 ] ) # Add column and row dendrograms/axes to figure coldend = add_mpl_dendrogram ( dfr , fig , heatmap_gs , orientation = "col" ) rowdend = add_mpl_dendrogram ( dfr , fig , heatmap_gs , orientation = "row" ) # Add heatmap axes to figure, with rows/columns as in the dendrograms heatmap_axes = get_mpl_heatmap_axes ( dfr , fig , heatmap_gs ) ax_map = heatmap_axes . imshow ( dfr . iloc [ rowdend [ "dendrogram" ] [ "leaves" ] , coldend [ "dendrogram" ] [ "leaves" ] ] , interpolation = "nearest" , cmap = params . cmap , origin = "lower" , vmin = params . vmin , vmax = params . vmax , aspect = "auto" , ) # Are there class colourbars to add? if params . classes is not None : add_mpl_colorbar ( dfr , fig , coldend , params , orientation = "col" ) add_mpl_colorbar ( dfr , fig , rowdend , params , orientation = "row" ) # Add heatmap labels add_mpl_labels ( heatmap_axes , dfr . index [ rowdend [ "dendrogram" ] [ "leaves" ] ] , dfr . index [ coldend [ "dendrogram" ] [ "leaves" ] ] , params , ) # Add colour scale add_mpl_colorscale ( fig , heatmap_gs , ax_map , params , title ) # Return figure output, and write, if required plt . subplots_adjust ( top = 0.85 ) # Leave room for title # fig.set_tight_layout(True) # We know that there is a UserWarning here about tight_layout and # using the Agg renderer on OSX, so catch and ignore it, for cleanliness. with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) heatmap_gs . tight_layout ( fig , h_pad = 0.1 , w_pad = 0.5 ) if outfilename : fig . savefig ( outfilename ) return fig | Returns matplotlib heatmap with cluster dendrograms . | 662 | 13 |
18,691 | def run_dependency_graph ( jobgraph , workers = None , logger = None ) : cmdsets = [ ] for job in jobgraph : cmdsets = populate_cmdsets ( job , cmdsets , depth = 1 ) # Put command sets in reverse order, and submit to multiprocessing_run cmdsets . reverse ( ) cumretval = 0 for cmdset in cmdsets : if logger : # Try to be informative, if the logger module is being used logger . info ( "Command pool now running:" ) for cmd in cmdset : logger . info ( cmd ) cumretval += multiprocessing_run ( cmdset , workers ) if logger : # Try to be informative, if the logger module is being used logger . info ( "Command pool done." ) return cumretval | Creates and runs pools of jobs based on the passed jobgraph . | 168 | 14 |
18,692 | def populate_cmdsets ( job , cmdsets , depth ) : if len ( cmdsets ) < depth : cmdsets . append ( set ( ) ) cmdsets [ depth - 1 ] . add ( job . command ) if len ( job . dependencies ) == 0 : return cmdsets for j in job . dependencies : cmdsets = populate_cmdsets ( j , cmdsets , depth + 1 ) return cmdsets | Creates a list of sets containing jobs at different depths of the dependency tree . | 86 | 16 |
18,693 | def multiprocessing_run ( cmdlines , workers = None ) : # Run jobs # If workers is None or greater than the number of cores available, # it will be set to the maximum number of cores pool = multiprocessing . Pool ( processes = workers ) results = [ pool . apply_async ( subprocess . run , ( str ( cline ) , ) , { 'shell' : sys . platform != "win32" , 'stdout' : subprocess . PIPE , 'stderr' : subprocess . PIPE } ) for cline in cmdlines ] pool . close ( ) pool . join ( ) return sum ( [ r . get ( ) . returncode for r in results ] ) | Distributes passed command - line jobs using multiprocessing . | 156 | 13 |
18,694 | def get_input_files ( dirname , * ext ) : filelist = [ f for f in os . listdir ( dirname ) if os . path . splitext ( f ) [ - 1 ] in ext ] return [ os . path . join ( dirname , f ) for f in filelist ] | Returns files in passed directory filtered by extension . | 67 | 9 |
18,695 | def get_sequence_lengths ( fastafilenames ) : tot_lengths = { } for fn in fastafilenames : tot_lengths [ os . path . splitext ( os . path . split ( fn ) [ - 1 ] ) [ 0 ] ] = sum ( [ len ( s ) for s in SeqIO . parse ( fn , 'fasta' ) ] ) return tot_lengths | Returns dictionary of sequence lengths keyed by organism . | 92 | 10 |
18,696 | def last_exception ( ) : exc_type , exc_value , exc_traceback = sys . exc_info ( ) return "" . join ( traceback . format_exception ( exc_type , exc_value , exc_traceback ) ) | Returns last exception as a string or use in logging . | 55 | 11 |
18,697 | def make_outdir ( ) : if os . path . exists ( args . outdirname ) : if not args . force : logger . error ( "Output directory %s would overwrite existing " + "files (exiting)" , args . outdirname , ) sys . exit ( 1 ) elif args . noclobber : logger . warning ( "NOCLOBBER: not actually deleting directory %s" , args . outdirname ) else : logger . info ( "Removing directory %s and everything below it" , args . outdirname ) shutil . rmtree ( args . outdirname ) logger . info ( "Creating directory %s" , args . outdirname ) try : os . makedirs ( args . outdirname ) # We make the directory recursively # Depending on the choice of method, a subdirectory will be made for # alignment output files if args . method != "TETRA" : os . makedirs ( os . path . join ( args . outdirname , ALIGNDIR [ args . method ] ) ) except OSError : # This gets thrown if the directory exists. If we've forced overwrite/ # delete and we're not clobbering, we let things slide if args . noclobber and args . force : logger . info ( "NOCLOBBER+FORCE: not creating directory" ) else : logger . error ( last_exception ) sys . exit ( 1 ) | Make the output directory if required . | 315 | 7 |
18,698 | def compress_delete_outdir ( outdir ) : # Compress output in .tar.gz file and remove raw output tarfn = outdir + ".tar.gz" logger . info ( "\tCompressing output from %s to %s" , outdir , tarfn ) with tarfile . open ( tarfn , "w:gz" ) as fh : fh . add ( outdir ) logger . info ( "\tRemoving output directory %s" , outdir ) shutil . rmtree ( outdir ) | Compress the contents of the passed directory to . tar . gz and delete . | 114 | 17 |
18,699 | def calculate_anim ( infiles , org_lengths ) : logger . info ( "Running ANIm" ) logger . info ( "Generating NUCmer command-lines" ) deltadir = os . path . join ( args . outdirname , ALIGNDIR [ "ANIm" ] ) logger . info ( "Writing nucmer output to %s" , deltadir ) # Schedule NUCmer runs if not args . skip_nucmer : joblist = anim . generate_nucmer_jobs ( infiles , args . outdirname , nucmer_exe = args . nucmer_exe , filter_exe = args . filter_exe , maxmatch = args . maxmatch , jobprefix = args . jobprefix , ) if args . scheduler == "multiprocessing" : logger . info ( "Running jobs with multiprocessing" ) if args . workers is None : logger . info ( "(using maximum number of available " + "worker threads)" ) else : logger . info ( "(using %d worker threads, if available)" , args . workers ) cumval = run_mp . run_dependency_graph ( joblist , workers = args . workers , logger = logger ) logger . info ( "Cumulative return value: %d" , cumval ) if 0 < cumval : logger . warning ( "At least one NUCmer comparison failed. " + "ANIm may fail." ) else : logger . info ( "All multiprocessing jobs complete." ) else : logger . info ( "Running jobs with SGE" ) logger . info ( "Jobarray group size set to %d" , args . sgegroupsize ) run_sge . run_dependency_graph ( joblist , logger = logger , jgprefix = args . jobprefix , sgegroupsize = args . sgegroupsize , sgeargs = args . sgeargs , ) else : logger . warning ( "Skipping NUCmer run (as instructed)!" ) # Process resulting .delta files logger . info ( "Processing NUCmer .delta files." ) results = anim . process_deltadir ( deltadir , org_lengths , logger = logger ) if results . zero_error : # zero percentage identity error if not args . skip_nucmer and args . scheduler == "multiprocessing" : if 0 < cumval : logger . error ( "This has possibly been a NUCmer run failure, " + "please investigate" ) logger . error ( last_exception ( ) ) sys . exit ( 1 ) else : logger . error ( "This is possibly due to a NUCmer comparison " + "being too distant for use. Please consider " + "using the --maxmatch option." ) logger . error ( "This is alternatively due to NUCmer run " + "failure, analysis will continue, but please " + "investigate." ) if not args . nocompress : logger . info ( "Compressing/deleting %s" , deltadir ) compress_delete_outdir ( deltadir ) # Return processed data from .delta files return results | Returns ANIm result dataframes for files in input directory . | 689 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.