idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
21,100 | def create_env ( self , interpreter , is_current , options ) : if is_current : pyvenv_options = options [ 'pyvenv_options' ] if "--system-site-packages" in pyvenv_options : self . system_site_packages = True logger . debug ( "Creating virtualenv with pyvenv. options=%s" , pyvenv_options ) self . create ( self . env_pat... | Create the virtualenv and return its info . |
21,101 | def store_usage_stat ( self , venv_data , cache ) : with open ( self . stat_file_path , 'at' ) as f : self . _write_venv_usage ( f , venv_data ) | Log an usage record for venv_data . |
21,102 | def clean_unused_venvs ( self , max_days_to_keep ) : with filelock ( self . stat_file_lock ) : now = datetime . utcnow ( ) venvs_dict = self . _get_compacted_dict_usage_from_file ( ) for venv_uuid , usage_date in venvs_dict . copy ( ) . items ( ) : usage_date = self . _str_to_datetime ( usage_date ) if ( now - usage_da... | Compact usage stats and remove venvs . |
21,103 | def logged_exec ( cmd ) : logger = logging . getLogger ( 'fades.exec' ) logger . debug ( "Executing external command: %r" , cmd ) p = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True ) stdout = [ ] for line in p . stdout : line = line [ : - 1 ] stdout . ap... | Execute a command redirecting the output to the log . |
21,104 | def _get_specific_dir ( dir_type ) : if SNAP_BASEDIR_NAME in os . environ : logger . debug ( "Getting base dir information from SNAP_BASEDIR_NAME env var." ) direct = os . path . join ( os . environ [ SNAP_BASEDIR_NAME ] , dir_type ) else : try : basedirectory = _get_basedirectory ( ) except ImportError : logger . debu... | Get a specific directory using some XDG base with sensible default . |
21,105 | def _get_interpreter_info ( interpreter = None ) : if interpreter is None : major , minor = sys . version_info [ : 2 ] executable = sys . executable else : args = [ interpreter , '-c' , SHOW_VERSION_CMD ] try : requested_interpreter_info = logged_exec ( args ) except Exception as error : logger . error ( "Error getting... | Return the interpreter s full path using pythonX . Y format . |
21,106 | def get_interpreter_version ( requested_interpreter ) : logger . debug ( 'Getting interpreter version for: %s' , requested_interpreter ) current_interpreter = _get_interpreter_info ( ) logger . debug ( 'Current interpreter is %s' , current_interpreter ) if requested_interpreter is None : return ( current_interpreter , ... | Return a sanitized interpreter and indicates if it is the current one . |
21,107 | def check_pypi_updates ( dependencies ) : dependencies_up_to_date = [ ] for dependency in dependencies . get ( 'pypi' , [ ] ) : try : latest_version = get_latest_version_number ( dependency . project_name ) except Exception as error : logger . warning ( "--check-updates command will be aborted. Error: %s" , error ) ret... | Return a list of dependencies to upgrade . |
21,108 | def _pypi_head_package ( dependency ) : if dependency . specs : _ , version = dependency . specs [ 0 ] url = BASE_PYPI_URL_WITH_VERSION . format ( name = dependency . project_name , version = version ) else : url = BASE_PYPI_URL . format ( name = dependency . project_name ) logger . debug ( "Doing HEAD requests against... | Hit pypi with a http HEAD to check if pkg_name exists . |
21,109 | def check_pypi_exists ( dependencies ) : for dependency in dependencies . get ( 'pypi' , [ ] ) : logger . debug ( "Checking if %r exists in PyPI" , dependency ) try : exists = _pypi_head_package ( dependency ) except Exception as error : logger . error ( "Error checking %s in PyPI: %r" , dependency , error ) raise Fade... | Check if the indicated dependencies actually exists in pypi . |
21,110 | def download_remote_script ( url ) : temp_fh = tempfile . NamedTemporaryFile ( 'wt' , encoding = 'utf8' , suffix = ".py" , delete = False ) downloader = _ScriptDownloader ( url ) logger . info ( "Downloading remote script from %r using (%r downloader) to %r" , url , downloader . name , temp_fh . name ) content = downlo... | Download the content of a remote script to a local temp file . |
21,111 | def dump_to_log ( self , logger ) : logger . error ( "Execution ended in %s for cmd %s" , self . _retcode , self . _cmd ) for line in self . _collected_stdout : logger . error ( STDOUT_LOG_PREFIX + line ) | Send the cmd info and collected stdout to logger . |
21,112 | def _decide ( self ) : netloc = parse . urlparse ( self . url ) . netloc name = self . NETLOCS . get ( netloc , 'raw' ) return name | Find out which method should be applied to download that URL . |
21,113 | def get ( self ) : method_name = "_download_" + self . name method = getattr ( self , method_name ) return method ( ) | Get the script content from the URL using the decided downloader . |
21,114 | def _download_raw ( self , url = None ) : if url is None : url = self . url req = request . Request ( url , headers = self . HEADERS_PLAIN ) return request . urlopen ( req ) . read ( ) . decode ( "utf8" ) | Download content from URL directly . |
21,115 | def _download_linkode ( self ) : linkode_id = self . url . split ( "/" ) [ - 1 ] if linkode_id . startswith ( "#" ) : linkode_id = linkode_id [ 1 : ] url = "https://linkode.org/api/1/linkodes/" + linkode_id req = request . Request ( url , headers = self . HEADERS_JSON ) resp = request . urlopen ( req ) raw = resp . rea... | Download content from Linkode pastebin . |
21,116 | def _download_pastebin ( self ) : paste_id = self . url . split ( "/" ) [ - 1 ] url = "https://pastebin.com/raw/" + paste_id return self . _download_raw ( url ) | Download content from Pastebin itself . |
21,117 | def _download_gist ( self ) : parts = parse . urlparse ( self . url ) url = "https://gist.github.com" + parts . path + "/raw" return self . _download_raw ( url ) | Download content from github s pastebin . |
21,118 | def get_version ( ) : with open ( 'fades/_version.py' ) as fh : m = re . search ( "\(([^']*)\)" , fh . read ( ) ) if m is None : raise ValueError ( "Unrecognized version in 'fades/_version.py'" ) return m . groups ( ) [ 0 ] . replace ( ', ' , '.' ) | Retrieves package version from the file . |
21,119 | def initialize_options ( self ) : install . initialize_options ( self ) script = SCRIPT_WIN if sys . platform == "win32" else SCRIPT_REST self . distribution . scripts = [ script ] | Run parent initialization and then fix the scripts var . |
21,120 | def run ( self ) : install . run ( self ) if self . _custom_man_dir is not None : if not os . path . exists ( self . _custom_man_dir ) : os . makedirs ( self . _custom_man_dir ) shutil . copy ( "man/fades.1" , self . _custom_man_dir ) | Run parent install and then save the man file . |
21,121 | def finalize_options ( self ) : install . finalize_options ( self ) if self . prefix is None : man_dir = None else : man_dir = os . path . join ( self . prefix , "share" , "man" , "man1" ) if self . root is not None : man_dir = os . path . join ( self . root , man_dir [ 1 : ] ) self . _custom_man_dir = man_dir | Alter the installation path . |
21,122 | def options_from_file ( args ) : logger . debug ( "updating options from config files" ) updated_from_file = [ ] for config_file in CONFIG_FILES : logger . debug ( "updating from: %s" , config_file ) parser = ConfigParser ( ) parser . read ( config_file ) try : items = parser . items ( 'fades' ) except NoSectionError :... | Get a argparse . Namespace and return it updated with options from config files . |
21,123 | def _venv_match ( self , installed , requirements ) : if not requirements : return None if installed else [ ] satisfying_deps = [ ] for repo , req_deps in requirements . items ( ) : useful_inst = set ( ) if repo not in installed : return None if repo == REPO_VCS : inst_deps = { VCSDependency ( url ) for url in installe... | Return True if what is installed satisfies the requirements . |
21,124 | def _match_by_uuid ( self , current_venvs , uuid ) : for venv_str in current_venvs : venv = json . loads ( venv_str ) env_path = venv . get ( 'metadata' , { } ) . get ( 'env_path' ) _ , env_uuid = os . path . split ( env_path ) if env_uuid == uuid : return venv | Select a venv matching exactly by uuid . |
21,125 | def _select_better_fit ( self , matching_venvs ) : venvs = [ ] to_compare = [ ] for matching , venv in matching_venvs : to_compare . append ( sorted ( matching , key = lambda req : getattr ( req , 'key' , '' ) ) ) venvs . append ( venv ) scores = [ 0 ] * len ( venvs ) for dependencies in zip ( * to_compare ) : if not i... | Receive a list of matching venvs and decide which one is the best fit . |
21,126 | def _match_by_requirements ( self , current_venvs , requirements , interpreter , options ) : matching_venvs = [ ] for venv_str in current_venvs : venv = json . loads ( venv_str ) if venv . get ( 'options' ) != options or venv . get ( 'interpreter' ) != interpreter : continue matching = self . _venv_match ( venv [ 'inst... | Select a venv matching interpreter and options complying with requirements . |
21,127 | def _select ( self , current_venvs , requirements = None , interpreter = '' , uuid = '' , options = None ) : if uuid : logger . debug ( "Searching a venv by uuid: %s" , uuid ) venv = self . _match_by_uuid ( current_venvs , uuid ) else : logger . debug ( "Searching a venv for: reqs=%s interpreter=%s options=%s" , requir... | Select which venv satisfy the received requirements . |
21,128 | def get_venv ( self , requirements = None , interpreter = '' , uuid = '' , options = None ) : lines = self . _read_cache ( ) return self . _select ( lines , requirements , interpreter , uuid = uuid , options = options ) | Find a venv that serves these requirements if any . |
21,129 | def store ( self , installed_stuff , metadata , interpreter , options ) : new_content = { 'timestamp' : int ( time . mktime ( time . localtime ( ) ) ) , 'installed' : installed_stuff , 'metadata' : metadata , 'interpreter' : interpreter , 'options' : options } logger . debug ( "Storing installed=%s metadata=%s interpre... | Store the virtualenv metadata for the indicated installed_stuff . |
21,130 | def remove ( self , env_path ) : with filelock ( self . lockpath ) : cache = self . _read_cache ( ) logger . debug ( "Removing virtualenv from cache: %s" % env_path ) lines = [ line for line in cache if json . loads ( line ) . get ( 'metadata' , { } ) . get ( 'env_path' ) != env_path ] self . _write_cache ( lines ) | Remove metadata for a given virtualenv from cache . |
21,131 | def _read_cache ( self ) : if os . path . exists ( self . filepath ) : with open ( self . filepath , 'rt' , encoding = 'utf8' ) as fh : lines = [ x . strip ( ) for x in fh ] else : logger . debug ( "Index not found, starting empty" ) lines = [ ] return lines | Read virtualenv metadata from cache . |
21,132 | def _write_cache ( self , lines , append = False ) : mode = 'at' if append else 'wt' with open ( self . filepath , mode , encoding = 'utf8' ) as fh : fh . writelines ( line + '\n' for line in lines ) | Write virtualenv metadata to cache . |
21,133 | def install ( self , dependency ) : if not self . pip_installed : logger . info ( "Need to install a dependency with pip, but no builtin, " "doing it manually (just wait a little, all should go well)" ) self . _brute_force_install_pip ( ) str_dep = str ( dependency ) args = [ self . pip_exe , "install" ] + str_dep . sp... | Install a new dependency . |
21,134 | def get_version ( self , dependency ) : logger . debug ( "getting installed version for %s" , dependency ) stdout = helpers . logged_exec ( [ self . pip_exe , "show" , str ( dependency ) ] ) version = [ line for line in stdout if line . startswith ( 'Version:' ) ] if len ( version ) == 1 : version = version [ 0 ] . str... | Return the installed version parsing the output of pip show . |
21,135 | def _brute_force_install_pip ( self ) : if os . path . exists ( self . pip_installer_fname ) : logger . debug ( "Using pip installer from %r" , self . pip_installer_fname ) else : logger . debug ( "Installer for pip not found in %r, downloading it" , self . pip_installer_fname ) self . _download_pip_installer ( ) logge... | A brute force install of pip itself . |
21,136 | def _generate_configs_from_default ( self , overrides = None ) : config = DEFAULT_CONFIG . copy ( ) if not overrides : overrides = { } for k , v in overrides . items ( ) : config [ k ] = v return config | Generate configs by inheriting from defaults |
21,137 | def read_ical ( self , ical_file_location ) : with open ( ical_file_location , 'r' ) as ical_file : data = ical_file . read ( ) self . cal = Calendar . from_ical ( data ) return self . cal | Read the ical file |
21,138 | def read_csv ( self , csv_location , csv_configs = None ) : csv_configs = self . _generate_configs_from_default ( csv_configs ) with open ( csv_location , 'r' ) as csv_file : csv_reader = csv . reader ( csv_file ) self . csv_data = list ( csv_reader ) self . csv_data = self . csv_data [ csv_configs [ 'HEADER_COLUMNS_TO... | Read the csv file |
21,139 | def make_ical ( self , csv_configs = None ) : csv_configs = self . _generate_configs_from_default ( csv_configs ) self . cal = Calendar ( ) for row in self . csv_data : event = Event ( ) event . add ( 'summary' , row [ csv_configs [ 'CSV_NAME' ] ] ) event . add ( 'dtstart' , row [ csv_configs [ 'CSV_START_DATE' ] ] ) e... | Make iCal entries |
21,140 | def save_ical ( self , ical_location ) : data = self . cal . to_ical ( ) with open ( ical_location , 'w' ) as ical_file : ical_file . write ( data . decode ( 'utf-8' ) ) | Save the calendar instance to a file |
21,141 | def save_csv ( self , csv_location ) : with open ( csv_location , 'w' ) as csv_handle : writer = csv . writer ( csv_handle ) for row in self . csv_data : writer . writerow ( row ) | Save the csv to a file |
21,142 | def open ( cls , filename ) : if filename . endswith ( '.gz' ) : fp = gzip . open ( filename , 'rb' ) try : return cls ( fp , filename , compression = 'gz' ) finally : fp . close ( ) elif filename . endswith ( '.bz2' ) : fp = bz2 . BZ2File ( filename , 'rb' ) try : return cls ( fp , filename , compression = 'bz2' ) fin... | Read an image file from disk |
21,143 | def image ( self ) : if self . bands == 1 : return self . data . squeeze ( ) elif self . bands == 3 : return numpy . dstack ( self . data ) | An Image like array of self . data convenient for image processing tasks |
21,144 | def apply_numpy_specials ( self , copy = True ) : if copy : data = self . data . astype ( numpy . float64 ) elif self . data . dtype != numpy . float64 : data = self . data = self . data . astype ( numpy . float64 ) else : data = self . data data [ data == self . specials [ 'Null' ] ] = numpy . nan data [ data < self .... | Convert isis special pixel values to numpy special pixel values . |
21,145 | def parse ( cls , value , record_bytes ) : if isinstance ( value , six . string_types ) : return cls ( value , 0 ) if isinstance ( value , list ) : if len ( value ) == 1 : return cls ( value [ 0 ] , 0 ) if len ( value ) == 2 : return cls ( value [ 0 ] , cls . _parse_bytes ( value [ 1 ] , record_bytes ) ) raise ValueErr... | Parses the pointer label . |
21,146 | def _save ( self , file_to_write , overwrite ) : if overwrite : file_to_write = self . filename elif os . path . isfile ( file_to_write ) : msg = 'File ' + file_to_write + ' already exists !\n' + 'Call save() with "overwrite = True" to overwrite the file.' raise IOError ( msg ) encoder = pvl . encoder . PDSLabelEncoder... | Save PDS3Image object as PDS3 file . |
21,147 | def _create_label ( self , array ) : if len ( array . shape ) == 3 : bands = array . shape [ 0 ] lines = array . shape [ 1 ] line_samples = array . shape [ 2 ] else : bands = 1 lines = array . shape [ 0 ] line_samples = array . shape [ 1 ] record_bytes = line_samples * array . itemsize label_module = pvl . PVLModule ( ... | Create sample PDS3 label for NumPy Array . It is called by image . py to create PDS3Image object from Numpy Array . |
21,148 | def _update_label ( self , label , array ) : maximum = float ( numpy . max ( array ) ) mean = float ( numpy . mean ( array ) ) median = float ( numpy . median ( array ) ) minimum = float ( numpy . min ( array ) ) stdev = float ( numpy . std ( array , ddof = 1 ) ) encoder = pvl . encoder . PDSLabelEncoder serial_label =... | Update PDS3 label for NumPy Array . It is called by _create_label to update label values such as - ^IMAGE RECORD_BYTES - STANDARD_DEVIATION - MAXIMUM MINIMUM - MEDIAN MEAN |
21,149 | def iv ( base , counter ) : if ( counter >> 64 ) != 0 : raise ECEException ( u"Counter too big" ) ( mask , ) = struct . unpack ( "!Q" , base [ 4 : ] ) return base [ : 4 ] + struct . pack ( "!Q" , counter ^ mask ) | Generate an initialization vector . |
21,150 | def encrypt ( content , salt = None , key = None , private_key = None , dh = None , auth_secret = None , keyid = None , keylabel = "P-256" , rs = 4096 , version = "aes128gcm" ) : def encrypt_record ( key , nonce , counter , buf , last ) : encryptor = Cipher ( algorithms . AES ( key ) , modes . GCM ( iv ( nonce , counte... | Encrypt a data block |
21,151 | def parameters ( self , namespaced = False ) : if namespaced : return json . loads ( json . dumps ( self . args [ 0 ] [ 'parameters' ] ) , object_hook = lambda d : SimpleNamespace ( ** d ) ) else : return self . args [ 0 ] . get ( 'parameters' ) | returns the exception varlink error parameters |
21,152 | def handle ( self , message , _server = None , _request = None ) : if not message : return if message [ - 1 ] == 0 : message = message [ : - 1 ] string = message . decode ( 'utf-8' ) handle = self . _handle ( json . loads ( string ) , message , _server , _request ) for out in handle : if out == None : return try : yiel... | This generator function handles any incoming message . |
21,153 | def server_close ( self ) : if self . remove_file : try : os . remove ( self . remove_file ) except : pass self . socket . close ( ) | Called to clean - up the server . |
21,154 | def open ( self , interface_name , namespaced = False , connection = None ) : if not connection : connection = self . open_connection ( ) if interface_name not in self . _interfaces : self . get_interface ( interface_name , socket_connection = connection ) if interface_name not in self . _interfaces : raise InterfaceNo... | Open a new connection and get a client interface handle with the varlink methods installed . |
21,155 | def get_interfaces ( self , socket_connection = None ) : if not socket_connection : socket_connection = self . open_connection ( ) close_socket = True else : close_socket = False _service = self . handler ( self . _interfaces [ "org.varlink.service" ] , socket_connection ) self . info = _service . GetInfo ( ) if close_... | Returns the a list of Interface objects the service implements . |
21,156 | def add_interface ( self , interface ) : if not isinstance ( interface , Interface ) : raise TypeError self . _interfaces [ interface . name ] = interface | Manually add or overwrite an interface definition from an Interface object . |
21,157 | def create ( atoms_list , N , L , cutoff = 0 , all_atomtypes = [ ] ) : myAlphas , myBetas = genBasis . getBasisFunc ( cutoff , N ) n_datapoints = len ( atoms_list ) atoms = atoms_list [ 0 ] x = get_lastatom_soap ( atoms , cutoff , myAlphas , myBetas , N , L , all_atomtypes = all_atomtypes ) n_features = x . shape [ 1 ]... | Takes a trajectory xyz file and writes soap features |
21,158 | def getPoly ( rCut , nMax ) : rCutVeryHard = rCut + 5.0 rx = 0.5 * rCutVeryHard * ( x + 1 ) basisFunctions = [ ] for i in range ( 1 , nMax + 1 ) : basisFunctions . append ( lambda rr , i = i , rCut = rCut : ( rCut - np . clip ( rr , 0 , rCut ) ) ** ( i + 2 ) ) S = np . zeros ( ( nMax , nMax ) ) for i in range ( 1 , nMa... | Used to calculate discrete vectors for the polynomial basis functions . |
21,159 | def _format_ase2clusgeo ( obj , all_atomtypes = None ) : totalAN = len ( obj ) if all_atomtypes is not None : atomtype_set = set ( all_atomtypes ) else : atomtype_set = set ( obj . get_atomic_numbers ( ) ) atomtype_lst = np . sort ( list ( atomtype_set ) ) n_atoms_per_type_lst = [ ] pos_lst = [ ] for atomtype in atomty... | Takes an ase Atoms object and returns numpy arrays and integers which are read by the internal clusgeo . Apos is currently a flattened out numpy array |
21,160 | def get_soap_structure ( obj , alp , bet , rCut = 5.0 , nMax = 5 , Lmax = 5 , crossOver = True , all_atomtypes = None , eta = 1.0 ) : Hpos = obj . get_positions ( ) arrsoap = get_soap_locals ( obj , Hpos , alp , bet , rCut , nMax , Lmax , crossOver , all_atomtypes = all_atomtypes , eta = eta ) return arrsoap | Get the RBF basis SOAP output for atoms in a finite structure . |
21,161 | def get_periodic_soap_locals ( obj , Hpos , alp , bet , rCut = 5.0 , nMax = 5 , Lmax = 5 , crossOver = True , all_atomtypes = None , eta = 1.0 ) : suce = _get_supercell ( obj , rCut ) arrsoap = get_soap_locals ( suce , Hpos , alp , bet , rCut , nMax = nMax , Lmax = Lmax , crossOver = crossOver , all_atomtypes = all_ato... | Get the RBF basis SOAP output for the given position in a periodic system . |
21,162 | def orbit_gen ( self ) : if self . norbits == 1 : yield self else : for i in range ( self . norbits ) : yield self [ : , i ] | Generator for iterating over each orbit . |
21,163 | def zmax ( self , return_times = False , func = np . mean , interp_kwargs = None , minimize_kwargs = None , approximate = False ) : if return_times and func is not None : raise ValueError ( "Cannot return times if reducing " "using an input function. Pass `func=None` if " "you want to return all individual values " "an... | Estimate the maximum z height of the orbit by identifying local maxima in the absolute value of the z position and interpolating between timesteps near the maxima . |
21,164 | def eccentricity ( self , ** kw ) : r ra = self . apocenter ( ** kw ) rp = self . pericenter ( ** kw ) return ( ra - rp ) / ( ra + rp ) | r Returns the eccentricity computed from the mean apocenter and mean pericenter . |
21,165 | def estimate_period ( self , radial = True ) : if self . t is None : raise ValueError ( "To compute the period, a time array is needed." " Specify a time array when creating this object." ) if radial : r = self . physicsspherical . r . value if self . norbits == 1 : T = peak_to_peak_period ( self . t . value , r ) T = ... | Estimate the period of the orbit . By default computes the radial period . If radial == False this returns period estimates for each dimension of the orbit . |
21,166 | def circulation ( self ) : L = self . angular_momentum ( ) if L . ndim == 2 : single_orbit = True L = L [ ... , None ] else : single_orbit = False ndim , ntimes , norbits = L . shape L0 = L [ : , 0 ] circ = np . ones ( ( ndim , norbits ) ) for ii in range ( ndim ) : cnd = ( np . sign ( L0 [ ii ] ) != np . sign ( L [ ii... | Determine which axes the Orbit circulates around by checking whether there is a change of sign of the angular momentum about an axis . Returns a 2D array with ndim integers per orbit point . If a box orbit all integers will be 0 . A 1 indicates circulation about the corresponding axis . |
21,167 | def align_circulation_with_z ( self , circulation = None ) : if circulation is None : circulation = self . circulation ( ) circulation = atleast_2d ( circulation , insert_axis = 1 ) cart = self . cartesian pos = cart . xyz vel = np . vstack ( ( cart . v_x . value [ None ] , cart . v_y . value [ None ] , cart . v_z . va... | If the input orbit is a tube orbit this function aligns the circulation axis with the z axis and returns a copy . |
21,168 | def greatcircle_to_greatcircle ( from_greatcircle_coord , to_greatcircle_frame ) : intermediate_from = from_greatcircle_coord . transform_to ( from_greatcircle_coord . pole ) intermediate_to = intermediate_from . transform_to ( to_greatcircle_frame . pole ) return intermediate_to . transform_to ( to_greatcircle_frame ) | Transform between two greatcircle frames . |
21,169 | def reference_to_greatcircle ( reference_frame , greatcircle_frame ) : pole = greatcircle_frame . pole . transform_to ( coord . ICRS ) ra0 = greatcircle_frame . ra0 center = greatcircle_frame . center R_rot = rotation_matrix ( greatcircle_frame . rotation , 'z' ) if not np . isnan ( ra0 ) : xaxis = np . array ( [ np . ... | Convert a reference coordinate to a great circle frame . |
21,170 | def pole_from_endpoints ( coord1 , coord2 ) : c1 = coord1 . cartesian / coord1 . cartesian . norm ( ) coord2 = coord2 . transform_to ( coord1 . frame ) c2 = coord2 . cartesian / coord2 . cartesian . norm ( ) pole = c1 . cross ( c2 ) pole = pole / pole . norm ( ) return coord1 . frame . realize_frame ( pole ) | Compute the pole from a great circle that connects the two specified coordinates . |
21,171 | def sph_midpoint ( coord1 , coord2 ) : c1 = coord1 . cartesian / coord1 . cartesian . norm ( ) coord2 = coord2 . transform_to ( coord1 . frame ) c2 = coord2 . cartesian / coord2 . cartesian . norm ( ) midpt = 0.5 * ( c1 + c2 ) usph = midpt . represent_as ( coord . UnitSphericalRepresentation ) return coord1 . frame . r... | Compute the midpoint between two points on the sphere . |
21,172 | def get_uv_tan ( c ) : l = c . spherical . lon b = c . spherical . lat p = np . array ( [ - np . sin ( l ) , np . cos ( l ) , np . zeros_like ( l . value ) ] ) . T q = np . array ( [ - np . cos ( l ) * np . sin ( b ) , - np . sin ( l ) * np . sin ( b ) , np . cos ( b ) ] ) . T return np . stack ( ( p , q ) , axis = - 1... | Get tangent plane basis vectors on the unit sphere at the given spherical coordinates . |
21,173 | def transform_pm_cov ( c , cov , to_frame ) : if c . isscalar and cov . shape != ( 2 , 2 ) : raise ValueError ( 'If input coordinate object is a scalar coordinate, ' 'the proper motion covariance matrix must have shape ' '(2, 2), not {}' . format ( cov . shape ) ) elif not c . isscalar and len ( c ) != cov . shape [ 0 ... | Transform a proper motion covariance matrix to a new frame . |
21,174 | def rodrigues_axis_angle_rotate ( x , vec , theta ) : x = np . array ( x ) . T vec = np . array ( vec ) . T theta = np . array ( theta ) . T [ ... , None ] out = np . cos ( theta ) * x + np . sin ( theta ) * np . cross ( vec , x ) + ( 1 - np . cos ( theta ) ) * ( vec * x ) . sum ( axis = - 1 ) [ ... , None ] * vec retu... | Rotated the input vector or set of vectors x around the axis vec by the angle theta . |
21,175 | def z_angle_rotate ( xy , theta ) : xy = np . array ( xy ) . T theta = np . array ( theta ) . T out = np . zeros_like ( xy ) out [ ... , 0 ] = np . cos ( theta ) * xy [ ... , 0 ] - np . sin ( theta ) * xy [ ... , 1 ] out [ ... , 1 ] = np . sin ( theta ) * xy [ ... , 0 ] + np . cos ( theta ) * xy [ ... , 1 ] return out ... | Rotated the input vector or set of vectors xy by the angle theta . |
21,176 | def static_to_constantrotating ( frame_i , frame_r , w , t = None ) : return _constantrotating_static_helper ( frame_r = frame_r , frame_i = frame_i , w = w , t = t , sign = 1. ) | Transform from an inertial static frame to a rotating frame . |
21,177 | def constantrotating_to_static ( frame_r , frame_i , w , t = None ) : return _constantrotating_static_helper ( frame_r = frame_r , frame_i = frame_i , w = w , t = t , sign = - 1. ) | Transform from a constantly rotating frame to a static inertial frame . |
21,178 | def to_dict ( potential ) : from . . import potential as gp if isinstance ( potential , gp . CompositePotential ) : d = dict ( ) d [ 'class' ] = potential . __class__ . __name__ d [ 'components' ] = [ ] for k , p in potential . items ( ) : comp_dict = _to_dict_help ( p ) comp_dict [ 'name' ] = k d [ 'components' ] . ap... | Turn a potential object into a dictionary that fully specifies the state of the object . |
21,179 | def _prepare_ws ( self , w0 , mmap , n_steps ) : from . . dynamics import PhaseSpacePosition if not isinstance ( w0 , PhaseSpacePosition ) : w0 = PhaseSpacePosition . from_w ( w0 ) arr_w0 = w0 . w ( self . _func_units ) self . ndim , self . norbits = arr_w0 . shape self . ndim = self . ndim // 2 return_shape = ( 2 * se... | Decide how to make the return array . If mmap is False this returns a full array of zeros but with the correct shape as the output . If mmap is True return a pointer to a memory - mapped array . The latter is particularly useful for integrating a large number of orbits or integrating a large number of time steps . |
21,180 | def fast_lyapunov_max ( w0 , hamiltonian , dt , n_steps , d0 = 1e-5 , n_steps_per_pullback = 10 , noffset_orbits = 2 , t1 = 0. , atol = 1E-10 , rtol = 1E-10 , nmax = 0 , return_orbit = True ) : from . lyapunov import dop853_lyapunov_max , dop853_lyapunov_max_dont_save if isinstance ( hamiltonian , PotentialBase ) : fro... | Compute the maximum Lyapunov exponent using a C - implemented estimator that uses the DOPRI853 integrator . |
21,181 | def surface_of_section ( orbit , plane_ix , interpolate = False ) : w = orbit . w ( ) if w . ndim == 2 : w = w [ ... , None ] ndim , ntimes , norbits = w . shape H_dim = ndim // 2 p_ix = plane_ix + H_dim if interpolate : raise NotImplementedError ( "Not yet implemented, sorry!" ) all_sos = np . zeros ( ( ndim , norbits... | Generate and return a surface of section from the given orbit . |
21,182 | def _remove_units ( self , x ) : if hasattr ( x , 'unit' ) : x = x . decompose ( self . units ) . value else : x = np . array ( x ) return x | Always returns an array . If a Quantity is passed in it converts to the units associated with this object and returns the value . |
21,183 | def mass_enclosed ( self , q , t = 0. ) : q = self . _remove_units_prepare_shape ( q ) orig_shape , q = self . _get_c_valid_arr ( q ) t = self . _validate_prepare_time ( t , q ) h = 1E-3 r = np . sqrt ( np . sum ( q ** 2 , axis = 1 ) ) epsilon = h * q / r [ : , np . newaxis ] dPhi_dr_plus = self . _energy ( q + epsilon... | Estimate the mass enclosed within the given position by assuming the potential is spherical . |
21,184 | def circular_velocity ( self , q , t = 0. ) : q = self . _remove_units_prepare_shape ( q ) r = np . sqrt ( np . sum ( q ** 2 , axis = 0 ) ) * self . units [ 'length' ] dPhi_dxyz = self . gradient ( q , t = t ) dPhi_dr = np . sum ( dPhi_dxyz * q / r . value , axis = 0 ) return self . units . decompose ( np . sqrt ( r * ... | Estimate the circular velocity at the given position assuming the potential is spherical . |
21,185 | def format_doc ( * args , ** kwargs ) : def set_docstring ( obj ) : doc = obj . __doc__ obj . __doc__ = None kwargs [ '__doc__' ] = obj . __doc__ or '' obj . __doc__ = doc . format ( * args , ** kwargs ) return obj return set_docstring | Replaces the docstring of the decorated object and then formats it . |
21,186 | def quantity_to_hdf5 ( f , key , q ) : if hasattr ( q , 'unit' ) : f [ key ] = q . value f [ key ] . attrs [ 'unit' ] = str ( q . unit ) else : f [ key ] = q f [ key ] . attrs [ 'unit' ] = "" | Turn an Astropy Quantity object into something we can write out to an HDF5 file . |
21,187 | def get_constant ( self , name ) : try : c = getattr ( const , name ) except AttributeError : raise ValueError ( "Constant name '{}' doesn't exist in astropy.constants" . format ( name ) ) return c . decompose ( self . _core_units ) . value | Retrieve a constant with specified name in this unit system . |
21,188 | def atleast_2d ( * arys , ** kwargs ) : insert_axis = kwargs . pop ( 'insert_axis' , 0 ) slc = [ slice ( None ) ] * 2 slc [ insert_axis ] = None slc = tuple ( slc ) res = [ ] for ary in arys : ary = np . asanyarray ( ary ) if len ( ary . shape ) == 0 : result = ary . reshape ( 1 , 1 ) elif len ( ary . shape ) == 1 : re... | View inputs as arrays with at least two dimensions . |
21,189 | def from_v_theta ( cls , v , theta ) : theta = np . asarray ( theta ) v = np . asarray ( v ) s = np . sin ( 0.5 * theta ) c = np . cos ( 0.5 * theta ) vnrm = np . sqrt ( np . sum ( v * v ) ) q = np . concatenate ( [ [ c ] , s * v / vnrm ] ) return cls ( q ) | Create a quaternion from unit vector v and rotation angle theta . |
21,190 | def random ( cls ) : s = np . random . uniform ( ) s1 = np . sqrt ( 1 - s ) s2 = np . sqrt ( s ) t1 = np . random . uniform ( 0 , 2 * np . pi ) t2 = np . random . uniform ( 0 , 2 * np . pi ) w = np . cos ( t2 ) * s2 x = np . sin ( t1 ) * s1 y = np . cos ( t1 ) * s1 z = np . sin ( t2 ) * s2 return cls ( [ w , x , y , z ... | Randomly sample a Quaternion from a distribution uniform in 3D rotation angles . |
21,191 | def step ( self , t , x_im1 , v_im1_2 , dt ) : x_i = x_im1 + v_im1_2 * dt F_i = self . F ( t , np . vstack ( ( x_i , v_im1_2 ) ) , * self . _func_args ) a_i = F_i [ self . ndim : ] v_i = v_im1_2 + a_i * dt / 2 v_ip1_2 = v_i + a_i * dt / 2 return x_i , v_i , v_ip1_2 | Step forward the positions and velocities by the given timestep . |
21,192 | def fit_isochrone ( orbit , m0 = 2E11 , b0 = 1. , minimize_kwargs = None ) : r pot = orbit . hamiltonian . potential if pot is None : raise ValueError ( "The orbit object must have an associated potential" ) w = np . squeeze ( orbit . w ( pot . units ) ) if w . ndim > 2 : raise ValueError ( "Input orbit object must be ... | r Fit the toy Isochrone potential to the sum of the energy residuals relative to the mean energy by minimizing the function |
21,193 | def fit_harmonic_oscillator ( orbit , omega0 = [ 1. , 1 , 1 ] , minimize_kwargs = None ) : r omega0 = np . atleast_1d ( omega0 ) pot = orbit . hamiltonian . potential if pot is None : raise ValueError ( "The orbit object must have an associated potential" ) w = np . squeeze ( orbit . w ( pot . units ) ) if w . ndim > 2... | r Fit the toy harmonic oscillator potential to the sum of the energy residuals relative to the mean energy by minimizing the function |
21,194 | def check_angle_sampling ( nvecs , angles ) : failed_nvecs = [ ] failures = [ ] for i , vec in enumerate ( nvecs ) : X = ( angles * vec [ : , None ] ) . sum ( axis = 0 ) diff = float ( np . abs ( X . max ( ) - X . min ( ) ) ) if diff < ( 2. * np . pi ) : warnings . warn ( "Need a longer integration window for mode {0}"... | Returns a list of the index of elements of n which do not have adequate toy angle coverage . The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n . |
21,195 | def find_actions ( orbit , N_max , force_harmonic_oscillator = False , toy_potential = None ) : r if orbit . norbits == 1 : return _single_orbit_find_actions ( orbit , N_max , force_harmonic_oscillator = force_harmonic_oscillator , toy_potential = toy_potential ) else : norbits = orbit . norbits actions = np . zeros ( ... | r Find approximate actions and angles for samples of a phase - space orbit . Uses toy potentials with known analytic action - angle transformations to approximate the true coordinates as a Fourier sum . |
21,196 | def angact_ho ( x , omega ) : action = ( x [ 3 : ] ** 2 + ( omega * x [ : 3 ] ) ** 2 ) / ( 2. * omega ) angle = np . array ( [ np . arctan ( - x [ 3 + i ] / omega [ i ] / x [ i ] ) if x [ i ] != 0. else - np . sign ( x [ 3 + i ] ) * np . pi / 2. for i in range ( 3 ) ] ) for i in range ( 3 ) : if ( x [ i ] < 0 ) : angle... | Calculate angle and action variable in sho potential with parameter omega |
21,197 | def peak_to_peak_period ( t , f , amplitude_threshold = 1E-2 ) : if hasattr ( t , 'unit' ) : t_unit = t . unit t = t . value else : t_unit = u . dimensionless_unscaled max_ix = argrelmax ( f , mode = 'wrap' ) [ 0 ] max_ix = max_ix [ ( max_ix != 0 ) & ( max_ix != ( len ( f ) - 1 ) ) ] min_ix = argrelmin ( f , mode = 'wr... | Estimate the period of the input time series by measuring the average peak - to - peak time . |
21,198 | def estimate_dt_n_steps ( w0 , hamiltonian , n_periods , n_steps_per_period , dE_threshold = 1E-9 , func = np . nanmax , ** integrate_kwargs ) : if not isinstance ( w0 , PhaseSpacePosition ) : w0 = np . asarray ( w0 ) w0 = PhaseSpacePosition . from_w ( w0 , units = hamiltonian . units ) dt = _autodetermine_initial_dt (... | Estimate the timestep and number of steps to integrate an orbit for given its initial conditions and a potential object . |
21,199 | def reflex_correct ( coords , galactocentric_frame = None ) : c = coord . SkyCoord ( coords ) if galactocentric_frame is None : galactocentric_frame = coord . Galactocentric ( ) v_sun = galactocentric_frame . galcen_v_sun observed = c . transform_to ( galactocentric_frame ) rep = observed . cartesian . without_differen... | Correct the input Astropy coordinate object for solar reflex motion . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.