Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _select_better_fit(self, matching_venvs): # keep the venvs in a separate array, to pick up the winner, and the (sorted, to compare # each dependency with its equivalent) in other structure to later compare venvs = [] to_compare = ...
[ "Receive a list of matching venvs, and decide which one is the best fit." ]
Please provide a description of the function:def _match_by_requirements(self, current_venvs, requirements, interpreter, options): matching_venvs = [] for venv_str in current_venvs: venv = json.loads(venv_str) # simple filter, need to have exactly same options and interp...
[ "Select a venv matching interpreter and options, complying with requirements.\n\n Several venvs can be found in this case, will return the better fit.\n " ]
Please provide a description of the function: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.d...
[ "Select which venv satisfy the received requirements." ]
Please provide a description of the function: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." ]
Please provide a description of the function:def store(self, installed_stuff, metadata, interpreter, options): new_content = { 'timestamp': int(time.mktime(time.localtime())), 'installed': installed_stuff, 'metadata': metadata, 'interpreter': interpreter,...
[ "Store the virtualenv metadata for the indicated installed_stuff." ]
Please provide a description of the function: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.lo...
[ "Remove metadata for a given virtualenv from cache." ]
Please provide a description of the function: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") ...
[ "Read virtualenv metadata from cache." ]
Please provide a description of the function: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." ]
Please provide a description of the function: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_in...
[ "Install a new dependency." ]
Please provide a description of the function: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:')] i...
[ "Return the installed version parsing the output of 'pip show'." ]
Please provide a description of the function: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, dow...
[ "A brute force install of pip itself." ]
Please provide a description of the function:def _generate_configs_from_default(self, overrides=None): # type: (Dict[str, int]) -> Dict[str, int] config = DEFAULT_CONFIG.copy() if not overrides: overrides = {} for k, v in overrides.items(): config[k] = v ...
[ " Generate configs by inheriting from defaults " ]
Please provide a description of the function:def read_ical(self, ical_file_location): # type: (str) -> Calendar 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 " ]
Please provide a description of the function:def read_csv(self, csv_location, csv_configs=None): # type: (str, Dict[str, int]) -> List[List[str]] csv_configs = self._generate_configs_from_default(csv_configs) with open(csv_location, 'r') as csv_file: csv_reader = csv.reader(...
[ " Read the csv file " ]
Please provide a description of the function:def make_ical(self, csv_configs=None): # type: (Dict[str, int]) -> Calendar csv_configs = self._generate_configs_from_default(csv_configs) self.cal = Calendar() for row in self.csv_data: event = Event() event.a...
[ " Make iCal entries " ]
Please provide a description of the function:def make_csv(self): # type: () -> None for event in self.cal.subcomponents: if event.name != 'VEVENT': continue row = [ event.get('SUMMARY'), event.get('DTSTART').dt, ev...
[ " Make CSV " ]
Please provide a description of the function:def save_ical(self, ical_location): # type: (str) -> None 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 " ]
Please provide a description of the function:def save_csv(self, csv_location): # type: (str) -> None 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 " ]
Please provide a description of the function: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'...
[ " Read an image file from disk\n\n Parameters\n ----------\n filename : string\n Name of file to read as an image file. This file may be gzip\n (``.gz``) or bzip2 (``.bz2``) compressed.\n " ]
Please provide a description of the function: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\n\n * 2D array for single band, grayscale image data\n * 3D array for three band, RGB image data\n\n Enables working with ``self.data`` as if it were a PIL image.\n\n See https://planetaryimage.readthedocs.io/en/...
Please provide a description of the function: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 ...
[ "Convert isis special pixel values to numpy special pixel values.\n\n ======= =======\n Isis Numpy\n ======= =======\n Null nan\n Lrs -inf\n Lis -inf\n His inf\n Hrs inf\n ======= =====...
Please provide a description of the function: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: ...
[ "Parses the pointer label.\n\n Parameters\n ----------\n pointer_data\n Supported values for `pointer_data` are::\n\n ^PTR = nnn\n ^PTR = nnn <BYTES>\n ^PTR = \"filename\"\n ^PTR = (\"filename\")\n ^PTR = (\"f...
Please provide a description of the function: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 "overwrit...
[ "Save PDS3Image object as PDS3 file.\n\n Parameters\n ----------\n filename: Set filename for the pds image to be saved.\n Overwrite: Use this keyword to save image with same filename.\n\n Usage: image.save('temp.IMG', overwrite=True)\n\n " ]
Please provide a description of the function: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_...
[ "Create sample PDS3 label for NumPy Array.\n It is called by 'image.py' to create PDS3Image object\n from Numpy Array.\n\n Returns\n -------\n PVLModule label for the given NumPy array.\n\n Usage: self.label = _create_label(array)\n\n " ]
Please provide a description of the function: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)) en...
[ "Update PDS3 label for NumPy Array.\n It is called by '_create_label' to update label values\n such as,\n - ^IMAGE, RECORD_BYTES\n - STANDARD_DEVIATION\n - MAXIMUM, MINIMUM\n - MEDIAN, MEAN\n\n Returns\n -------\n Update label module for the NumPy array...
Please provide a description of the function:def dtype(self): try: return self.data.dtype except AttributeError: return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes))
[ "Pixel data type." ]
Please provide a description of the function:def derive_key(mode, version, salt, key, private_key, dh, auth_secret, keyid, keylabel="P-256"): context = b"" keyinfo = "" nonceinfo = "" def build_info(base, info_context): return b"Content-Encoding: " + base + b"...
[ "Derive the encryption key\n\n :param mode: operational mode (encrypt or decrypt)\n :type mode: enumerate('encrypt', 'decrypt)\n :param salt: encryption salt value\n :type salt: str\n :param key: raw key\n :type key: str\n :param private_key: DH private key\n :type key: object\n :param dh...
Please provide a description of the function: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.\n\n " ]
Please provide a description of the function:def decrypt(content, salt=None, key=None, private_key=None, dh=None, auth_secret=None, keyid=None, keylabel="P-256", rs=4096, version="aes128gcm"): def parse_content_header(content): id_len = struct.unpack("!B", c...
[ "\n Decrypt a data block\n\n :param content: Data to be decrypted\n :type content: str\n :param salt: Encryption salt\n :type salt: str\n :param key: local public key\n :type key: str\n :param private_key: DH private key\n :type key: object\n :param keyid: Internal key identifier for p...
Please provide a description of the function: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( ...
[ "\n Encrypt a data block\n\n :param content: block of data to encrypt\n :type content: str\n :param salt: Encryption salt\n :type salt: str\n :param key: Encryption key data\n :type key: str\n :param private_key: DH private key\n :type key: object\n :param keyid: Internal key identifie...
Please provide a description of the function: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" ]
Please provide a description of the function:def GetInfo(self): return { 'vendor': self.vendor, 'product': self.product, 'version': self.version, 'url': self.url, 'interfaces': list(self.interfaces.keys()) }
[ "The standardized org.varlink.service.GetInfo() varlink method." ]
Please provide a description of the function:def GetInterfaceDescription(self, interface): try: i = self.interfaces[interface] except KeyError: raise InterfaceNotFound(interface) return {'description': i.description}
[ "The standardized org.varlink.service.GetInterfaceDescription() varlink method." ]
Please provide a description of the function: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, _...
[ "This generator function handles any incoming message.\n\n Write any returned bytes to the output stream.\n\n >>> for outgoing_message in service.handle(incoming_message):\n >>> connection.write(outgoing_message)\n " ]
Please provide a description of the function:def server_bind(self): if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setblocking(True) if not self.listen_fd: self.socket.bind(self.server_address) ...
[ "Called by constructor to bind the socket.\n\n May be overridden.\n\n " ]
Please provide a description of the function: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.\n\n May be overridden.\n\n " ]
Please provide a description of the function:def shutdown_request(self, request): try: # explicitly shutdown. socket.close() merely releases # the socket and waits for GC to perform the actual close. request.shutdown(socket.SHUT_RDWR) except: pa...
[ "Called to shutdown and close an individual request." ]
Please provide a description of the function: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=connec...
[ "Open a new connection and get a client interface handle with the varlink methods installed.\n\n :param interface_name: an interface name, which the service this client object is\n connected to, provides.\n :param namespaced: If arguments and return values are instances o...
Please provide a description of the function:def get_interfaces(self, socket_connection=None): if not socket_connection: socket_connection = self.open_connection() close_socket = True else: close_socket = False # noinspection PyUnresolvedReferences ...
[ "Returns the a list of Interface objects the service implements." ]
Please provide a description of the function: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.\n\n :param interface: an Interface() object\n\n " ]
Please provide a description of the function:def rematch_entry(envkernel, gamma = 0.1, threshold = 1e-6): n, m = envkernel.shape K = np.exp(-(1 - envkernel) / gamma) # initialisation u = np.ones((n,)) / n v = np.ones((m,)) / m en = np.ones((n,)) / float(n) em = np.ones((m,)) / float(m...
[ "\n Compute the global similarity between two structures A and B.\n It uses the Sinkhorn algorithm as reported in:\n Phys. Chem. Chem. Phys., 2016, 18, p. 13768\n Args:\n envkernel: NxM matrix of structure A with \n N and structure B with M atoms\n gamma: parameter to control be...
Please provide a description of the function:def create(atoms_list,N, L, cutoff = 0, all_atomtypes=[]): myAlphas, myBetas = genBasis.getBasisFunc(cutoff, N) # get information about feature length n_datapoints = len(atoms_list) atoms = atoms_list[0] x = get_lastatom_soap(atoms, cutoff, myAlphas,...
[ "Takes a trajectory xyz file and writes soap features\n " ]
Please provide a description of the function: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)) # Calculate the overlap o...
[ "Used to calculate discrete vectors for the polynomial basis functions.\n\n Args:\n rCut(float): Radial cutoff\n nMax(int): Number of polynomial radial functions\n " ]
Please provide a description of the function:def _format_ase2clusgeo(obj, all_atomtypes=None): #atoms metadata 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(atomt...
[ " Takes an ase Atoms object and returns numpy arrays and integers\n which are read by the internal clusgeo. Apos is currently a flattened\n out numpy array\n\n Args:\n obj():\n all_atomtypes():\n sort():\n " ]
Please provide a description of the function:def _get_supercell(obj, rCut=5.0): rCutHard = rCut + 5 # Giving extra space for hard cutOff cell_vectors = obj.get_cell() a1, a2, a3 = cell_vectors[0], cell_vectors[1], cell_vectors[2] # vectors perpendicular to two cell vectors b1 = np.cross(a2, ...
[ " Takes atoms object (with a defined cell) and a radial cutoff.\n Returns a supercell centered around the original cell\n generously extended to contain all spheres with the given radial\n cutoff centered around the original atoms.\n " ]
Please provide a description of the function:def get_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): rCutHard = rCut + 5 assert Lmax <= 9, "l cannot exceed 9. Lmax={}".format(Lmax) assert Lmax >= 0, "l cannot be negative.Lmax={}".format(Lmax) ...
[ "Get the RBF basis SOAP output for the given positions in a finite system.\n\n Args:\n obj(ase.Atoms): Atomic structure for which the SOAP output is\n calculated.\n Hpos: Positions at which to calculate SOAP\n alp: Alphas\n bet: Betas\n rCut: Radial cutoff.\n ...
Please provide a description of the function: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) retur...
[ "Get the RBF basis SOAP output for atoms in a finite structure.\n\n Args:\n obj(ase.Atoms): Atomic structure for which the SOAP output is\n calculated.\n alp: Alphas\n bet: Betas\n rCut: Radial cutoff.\n nMax: Maximum nmber of radial basis functions\n Lmax: Ma...
Please provide a description of the function: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_atomty...
[ "Get the RBF basis SOAP output for the given position in a periodic system.\n\n Args:\n obj(ase.Atoms): Atomic structure for which the SOAP output is\n calculated.\n alp: Alphas\n bet: Betas\n rCut: Radial cutoff.\n nMax: Maximum nmber of radial basis functions\n ...
Please provide a description of the function:def get_nnsoap(obj, first_shell, alphas, betas, rcut=6, nmax=10, lmax=9, all_atomtypes=[]): soap_vector = [] nnn = len(first_shell) for tbh in range(0,3): try: atom_idx = first_shell[tbh] except: soap_vector.append(so...
[ "Takes cluster structure and nearest neighbour information of a datapoint,\n Returns concatenated soap vectors for each nearest\n neighbour (up to 3). Top, bridge, hollow fill the initial\n zero soap vector from left to right.\n " ]
Please provide a description of the function:def get_sitecenteredsoap(obj, first_shell, alphas, betas, rcut=6, nmax=10, lmax=9, all_atomtypes=[]): soap_vector = [] nnn = len(first_shell) center_of_atoms = 1.0 / nnn * np.mean(obj.get_positions()[first_shell], axis = 0) #print("center of atoms", cen...
[ "Takes cluster structure and nearest neighbour information of a datapoint,\n Returns concatenated soap vectors for each nearest\n neighbour (up to 3). Top, bridge, hollow fill the initial\n zero soap vector from left to right.\n " ]
Please provide a description of the function:def w(self, units=None): if units is None: if self.hamiltonian is None: units = dimensionless else: units = self.hamiltonian.units return super(Orbit, self).w(units=units)
[ "\n This returns a single array containing the phase-space positions.\n\n Parameters\n ----------\n units : `~gala.units.UnitSystem` (optional)\n The unit system to represent the position and velocity in\n before combining into the full array.\n\n Returns\n ...
Please provide a description of the function:def represent_as(self, new_pos, new_vel=None): o = super(Orbit, self).represent_as(new_pos=new_pos, new_vel=new_vel) return self.__class__(pos=o.pos, vel=o.vel, hamiltonian=self.hamiltonian...
[ "\n Represent the position and velocity of the orbit in an alternate\n coordinate system. Supports any of the Astropy coordinates\n representation classes.\n\n Parameters\n ----------\n new_pos : :class:`~astropy.coordinates.BaseRepresentation`\n The type of repr...
Please provide a description of the function:def to_hdf5(self, f): f = super(Orbit, self).to_hdf5(f) if self.potential is not None: import yaml from ..potential.potential.io import to_dict f['potential'] = yaml.dump(to_dict(self.potential)).encode('utf-8') ...
[ "\n Serialize this object to an HDF5 file.\n\n Requires ``h5py``.\n\n Parameters\n ----------\n f : str, :class:`h5py.File`\n Either the filename or an open HDF5 file.\n " ]
Please provide a description of the function:def from_hdf5(cls, f): # TODO: this is duplicated code from PhaseSpacePosition if isinstance(f, str): import h5py f = h5py.File(f) pos = quantity_from_hdf5(f['pos']) vel = quantity_from_hdf5(f['vel']) ...
[ "\n Load an object from an HDF5 file.\n\n Requires ``h5py``.\n\n Parameters\n ----------\n f : str, :class:`h5py.File`\n Either the filename or an open HDF5 file.\n " ]
Please provide a description of the function:def orbit_gen(self): if self.norbits == 1: yield self else: for i in range(self.norbits): yield self[:, i]
[ "\n Generator for iterating over each orbit.\n " ]
Please provide a description of the function:def potential_energy(self, potential=None): r if self.hamiltonian is None and potential is None: raise ValueError("To compute the potential energy, a potential" " object must be provided!") if potential is None...
[ "\n The potential energy *per unit mass*:\n\n .. math::\n\n E_\\Phi = \\Phi(\\boldsymbol{q})\n\n Returns\n -------\n E : :class:`~astropy.units.Quantity`\n The potential energy.\n " ]
Please provide a description of the function:def energy(self, hamiltonian=None): r if self.hamiltonian is None and hamiltonian is None: raise ValueError("To compute the total energy, a hamiltonian" " object must be provided!") from ..potential import Po...
[ "\n The total energy *per unit mass*:\n\n Returns\n -------\n E : :class:`~astropy.units.Quantity`\n The total energy.\n " ]
Please provide a description of the function:def _max_helper(self, arr, approximate=False, interp_kwargs=None, minimize_kwargs=None): assert self.norbits == 1 assert self.t[-1] > self.t[0] # time must increase _ix = argrelmax(arr.value, mode='wrap')[0] _ix =...
[ "\n Helper function for computing extrema (apocenter, pericenter, z_height)\n and times of extrema.\n\n Parameters\n ----------\n arr : `numpy.ndarray`\n " ]
Please provide a description of the function:def pericenter(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 pe...
[ "\n Estimate the pericenter(s) of the orbit by identifying local minima in\n the spherical radius and interpolating between timesteps near the\n minima.\n\n By default, this returns the mean of all local minima (pericenters). To\n get, e.g., the minimum pericenter, pass in ``func=...
Please provide a description of the function: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 " ...
[ "\n Estimate the maximum ``z`` height of the orbit by identifying local\n maxima in the absolute value of the ``z`` position and interpolating\n between timesteps near the maxima.\n\n By default, this returns the mean of all local maxima. To get, e.g., the\n largest ``z`` excursio...
Please provide a description of the function:def eccentricity(self, **kw): r ra = self.apocenter(**kw) rp = self.pericenter(**kw) return (ra - rp) / (ra + rp)
[ "\n Returns the eccentricity computed from the mean apocenter and\n mean pericenter.\n\n .. math::\n\n e = \\frac{r_{\\rm apo} - r_{\\rm per}}{r_{\\rm apo} + r_{\\rm per}}\n\n Parameters\n ----------\n **kw\n Any keyword arguments passed to ``apocenter...
Please provide a description of the function:def circulation(self): L = self.angular_momentum() # if only 2D, add another empty axis if L.ndim == 2: single_orbit = True L = L[...,None] else: single_orbit = False ndim,ntimes,norbits =...
[ "\n Determine which axes the Orbit circulates around by checking\n whether there is a change of sign of the angular momentum\n about an axis. Returns a 2D array with ``ndim`` integers per orbit\n point. If a box orbit, all integers will be 0. A 1 indicates\n circulation about the ...
Please provide a description of the function: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.vs...
[ "\n If the input orbit is a tube orbit, this function aligns the circulation\n axis with the z axis and returns a copy.\n\n Parameters\n ----------\n circulation : array_like (optional)\n Array of bits that specify the axis about which the orbit\n circulates....
Please provide a description of the function:def to_frame(self, frame, current_frame=None, **kwargs): kw = kwargs.copy() # TODO: need a better way to do this! from ..potential.frame.builtin import ConstantRotatingFrame for fr in [frame, current_frame, self.frame]: ...
[ "\n TODO:\n\n Parameters\n ----------\n frame : `gala.potential.CFrameBase`\n The frame to transform to.\n current_frame : `gala.potential.CFrameBase` (optional)\n If the Orbit has no associated Hamiltonian, this specifies the\n current frame of th...
Please provide a description of the function:def greatcircle_to_greatcircle(from_greatcircle_coord, to_greatcircle_frame): # This transform goes through the parent frames on each side. # from_frame -> from_frame.origin -> to_frame.origin -> to_frame intermediate_from = f...
[ "Transform between two greatcircle frames." ]
Please provide a description of the function:def reference_to_greatcircle(reference_frame, greatcircle_frame): # Define rotation matrices along the position angle vector, and # relative to the origin. pole = greatcircle_frame.pole.transform_to(coord.ICRS) ra0 = greatcircle_frame.ra0 center = g...
[ "Convert a reference coordinate to a great circle frame." ]
Please provide a description of the function: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.fram...
[ "Compute the pole from a great circle that connects the two specified\n coordinates.\n\n This assumes a right-handed rule from coord1 to coord2: the pole is the\n north pole under that assumption.\n\n Parameters\n ----------\n coord1 : `~astropy.coordinates.SkyCoord`\n Coordinate of one poi...
Please provide a description of the function: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.UnitSphericalRepres...
[ "Compute the midpoint between two points on the sphere.\n\n Parameters\n ----------\n coord1 : `~astropy.coordinates.SkyCoord`\n Coordinate of one point on a great circle.\n coord2 : `~astropy.coordinates.SkyCoord`\n Coordinate of the other point on a great circle.\n\n Returns\n ----...
Please provide a description of the function: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\n spherical coordinates.\n " ]
Please provide a description of the function:def get_transform_matrix(from_frame, to_frame): path, distance = coord.frame_transform_graph.find_shortest_path( from_frame, to_frame) matrices = [] currsys = from_frame for p in path[1:]: # first element is fromsys so we skip it trans ...
[ "Compose sequential matrix transformations (static or dynamic) to get a\n single transformation matrix from a given path through the Astropy\n transformation machinery.\n\n Parameters\n ----------\n from_frame : `~astropy.coordinates.BaseCoordinateFrame` subclass\n The *class* of the frame you...
Please provide a description of the function: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...
[ "Transform a proper motion covariance matrix to a new frame.\n\n Parameters\n ----------\n c : `~astropy.coordinates.SkyCoord`\n The sky coordinates of the sources in the initial coordinate frame.\n cov : array_like\n The covariance matrix of the proper motions. Must have same length as\n ...
Please provide a description of the function: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 ...
[ "\n Rotated the input vector or set of vectors `x` around the axis\n `vec` by the angle `theta`.\n\n Parameters\n ----------\n x : array_like\n The vector or array of vectors to transform. Must have shape\n\n\n " ]
Please provide a description of the function: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.T
[ "\n Rotated the input vector or set of vectors `xy` by the angle `theta`.\n\n Parameters\n ----------\n xy : array_like\n The vector or array of vectors to transform. Must have shape\n\n\n " ]
Please provide a description of the function: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.)
[ "\n Transform from an inertial static frame to a rotating frame.\n\n Parameters\n ----------\n frame_i : `~gala.potential.StaticFrame`\n frame_r : `~gala.potential.ConstantRotatingFrame`\n w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`\n t : quantity_like (optional)\n Re...
Please provide a description of the function: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.)
[ "\n Transform from a constantly rotating frame to a static, inertial frame.\n\n Parameters\n ----------\n frame_i : `~gala.potential.StaticFrame`\n frame_r : `~gala.potential.ConstantRotatingFrame`\n w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`\n t : quantity_like (optional)\...
Please provide a description of the function:def from_dict(d, module=None): # need this here for circular import from .. import potential as gala_potential if module is None: potential = gala_potential else: potential = module if 'type' in d and d['type'] == 'composite': ...
[ "\n Convert a dictionary potential specification into a\n :class:`~gala.potential.PotentialBase` subclass object.\n\n Parameters\n ----------\n d : dict\n Dictionary specification of a potential.\n module : namespace (optional)\n\n " ]
Please provide a description of the function: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_dic...
[ "\n Turn a potential object into a dictionary that fully specifies the\n state of the object.\n\n Parameters\n ----------\n potential : :class:`~gala.potential.PotentialBase`\n The instantiated :class:`~gala.potential.PotentialBase` object.\n\n " ]
Please provide a description of the function:def load(f, module=None): if hasattr(f, 'read'): p_dict = yaml.load(f.read()) else: with open(os.path.abspath(f), 'r') as fil: p_dict = yaml.load(fil.read()) return from_dict(p_dict, module=module)
[ "\n Read a potential specification file and return a\n :class:`~gala.potential.PotentialBase` object instantiated with parameters\n specified in the spec file.\n\n Parameters\n ----------\n f : str, file_like\n A block of text, filename, or file-like object to parse and read\n a pote...
Please provide a description of the function:def save(potential, f): d = to_dict(potential) if hasattr(f, 'write'): yaml.dump(d, f, default_flow_style=False) else: with open(f, 'w') as f2: yaml.dump(d, f2, default_flow_style=False)
[ "\n Write a :class:`~gala.potential.PotentialBase` object out to a text (YAML)\n file.\n\n Parameters\n ----------\n potential : :class:`~gala.potential.PotentialBase`\n The instantiated :class:`~gala.potential.PotentialBase` object.\n f : str, file_like\n A filename or file-like obj...
Please provide a description of the function: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 = ...
[ "\n Decide how to make the return array. If mmap is False, this returns a\n full array of zeros, but with the correct shape as the output. If mmap\n is True, return a pointer to a memory-mapped array. The latter is\n particularly useful for integrating a large number of orbits or\n ...
Please provide a description of the function: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...
[ "\n Compute the maximum Lyapunov exponent using a C-implemented estimator\n that uses the DOPRI853 integrator.\n\n Parameters\n ----------\n w0 : `~gala.dynamics.PhaseSpacePosition`, array_like\n Initial conditions.\n hamiltonian : `~gala.potential.Hamiltonian`\n dt : numeric\n Ti...
Please provide a description of the function: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 ye...
[ "\n Generate and return a surface of section from the given orbit.\n\n .. warning::\n\n This is an experimental function and the API may change.\n\n Parameters\n ----------\n orbit : `~gala.dynamics.Orbit`\n plane_ix : int\n Integer that represents the coordinate to record crossings ...
Please provide a description of the function:def _remove_units(self, x): if hasattr(x, 'unit'): x = x.decompose(self.units).value else: x = np.array(x) return x
[ "\n Always returns an array. If a Quantity is passed in, it converts to the\n units associated with this object and returns the value.\n " ]
Please provide a description of the function:def energy(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) ret_unit = self.units['energy'] / self.units['mass'] return self._energy(q, t=t...
[ "\n Compute the potential energy at the given position(s).\n\n Parameters\n ----------\n q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like\n The position to compute the value of the potential. If the\n input position object has no units ...
Please provide a description of the function:def gradient(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) ret_unit = self.units['length'] / self.units['time']**2 return (self._gradient...
[ "\n Compute the gradient of the potential at the given position(s).\n\n Parameters\n ----------\n q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like\n The position to compute the value of the potential. If the\n input position object has ...
Please provide a description of the function:def density(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) ret_unit = self.units['mass'] / self.units['length']**3 return (self._density(q...
[ "\n Compute the density value at the given position(s).\n\n Parameters\n ----------\n q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like\n The position to compute the value of the potential. If the\n input position object has no units (i....
Please provide a description of the function:def hessian(self, q, t=0.): if (self.R is not None and not np.allclose(np.diag(self.R), 1., atol=1e-15, rtol=0)): raise NotImplementedError("Computing Hessian matrices for rotated " "potential...
[ "\n Compute the Hessian of the potential at the given position(s).\n\n Parameters\n ----------\n q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like\n The position to compute the value of the potential. If the\n input position object has n...
Please provide a description of the function: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) # small step-size in direction of q h = 1E-3 # MAGIC NUMBER # R...
[ "\n Estimate the mass enclosed within the given position by assuming the potential\n is spherical.\n\n Parameters\n ----------\n q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like\n Position(s) to estimate the enclossed mass.\n\n Retur...
Please provide a description of the function:def circular_velocity(self, q, t=0.): q = self._remove_units_prepare_shape(q) # Radius 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)...
[ "\n Estimate the circular velocity at the given position assuming the\n potential is spherical.\n\n Parameters\n ----------\n q : array_like, numeric\n Position(s) to estimate the circular velocity.\n\n Returns\n -------\n vcirc : `~astropy.units.Qu...
Please provide a description of the function:def plot_contours(self, grid, filled=True, ax=None, labels=None, subplots_kw=dict(), **kwargs): import matplotlib.pyplot as plt from matplotlib import cm # figure out which elements are iterable, which are numeric ...
[ "\n Plot equipotentials contours. Computes the potential energy on a grid\n (specified by the array `grid`).\n\n .. warning:: Right now the grid input must be arrays and must already\n be in the unit system of the potential. Quantity support is coming...\n\n Parameters\n ...
Please provide a description of the function:def total_energy(self, x, v): warnings.warn("Use the energy methods on Orbit objects instead. In a future " "release this will be removed.", DeprecationWarning) v = atleast_2d(v, insert_axis=1) return self.energy(x) + 0...
[ "\n Compute the total energy (per unit mass) of a point in phase-space\n in this potential. Assumes the last axis of the input position /\n velocity is the dimension axis, e.g., for 100 points in 3-space,\n the arrays should have shape (100,3).\n\n Parameters\n ----------\n...
Please provide a description of the function:def replace_units(self, units, copy=True): if copy: pot = pycopy.deepcopy(self) else: pot = self PotentialBase.__init__(pot, parameters=self.parameters, or...
[ "Change the unit system of this potential.\n\n Parameters\n ----------\n units : `~gala.units.UnitSystem`\n Set of non-reducable units that specify (at minimum) the\n length, mass, time, and angle units.\n copy : bool (optional)\n If True, returns a copy,...
Please provide a description of the function:def replace_units(self, units, copy=True): _lock = self.lock if copy: pots = self.__class__() else: pots = self pots._units = None pots.lock = False for k, v in self.items(): pots[...
[ "Change the unit system of this potential.\n\n Parameters\n ----------\n units : `~gala.units.UnitSystem`\n Set of non-reducable units that specify (at minimum) the\n length, mass, time, and angle units.\n copy : bool (optional)\n If True, returns a copy,...
Please provide a description of the function:def from_equation(expr, vars, pars, name=None, hessian=False): r try: import sympy from sympy.utilities.lambdify import lambdify except ImportError: raise ImportError("sympy is required to use 'from_equation()' " ...
[ "\n Create a potential class from an expression for the potential.\n\n .. note::\n\n This utility requires having `Sympy <http://www.sympy.org/>`_ installed.\n\n .. warning::\n\n These potentials are *not* pickle-able and cannot be written\n out to YAML files (using `~gala.potential.Po...
Please provide a description of the function:def format_doc(*args, **kwargs): def set_docstring(obj): # None means: use the objects __doc__ doc = obj.__doc__ # Delete documentation in this case so we don't end up with # awkwardly self-inserted docs. obj.__doc__ = None ...
[ "\n Replaces the docstring of the decorated object and then formats it.\n\n Modeled after astropy.utils.decorators.format_doc\n " ]
Please provide a description of the function:def quantity_from_hdf5(dset): if 'unit' in dset.attrs and dset.attrs['unit'] is not None: unit = u.Unit(dset.attrs['unit']) else: unit = 1. return dset[:] * unit
[ "\n Return an Astropy Quantity object from a key in an HDF5 file,\n group, or dataset. This checks to see if the input file/group/dataset\n contains a ``'unit'`` attribute (e.g., in `f.attrs`).\n\n Parameters\n ----------\n dset : :class:`h5py.DataSet`\n\n Returns\n -------\n q : `astropy...
Please provide a description of the function: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'] = ""
[ "\n Turn an Astropy Quantity object into something we can write out to\n an HDF5 file.\n\n Parameters\n ----------\n f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet`\n key : str\n The name.\n q : float, `astropy.units.Quantity`\n The quantity.\n\n " ]
Please provide a description of the function:def decompose(self, q): try: ptype = q.unit.physical_type except AttributeError: raise TypeError("Object must be an astropy.units.Quantity, not " "a '{}'.".format(q.__class__.__name__)) if ...
[ "\n A thin wrapper around :meth:`astropy.units.Quantity.decompose` that\n knows how to handle Quantities with physical types with non-default\n representations.\n\n Parameters\n ----------\n q : :class:`~astropy.units.Quantity`\n An instance of an astropy Quantit...
Please provide a description of the function: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
[ "\n Retrieve a constant with specified name in this unit system.\n\n Parameters\n ----------\n name : str\n The name of the constant, e.g., G.\n\n Returns\n -------\n const : float\n The value of the constant represented in this unit system.\n\n...
Please provide a description of the function:def rolling_window(arr, window_size, stride=1, return_idx=False): window_size = int(window_size) stride = int(stride) if window_size < 0 or stride < 1: raise ValueError arr_len = len(arr) if arr_len < window_size: if return_idx: ...
[ "\n There is an example of an iterator for pure-Python objects in:\n http://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator-in-python\n This is a rolling-window iterator Numpy arrays, with window size and\n stride control. See examples below for demos.\n\n Parameters\n -----...