Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function: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: result = ary[slc] else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res
[ "\n View inputs as arrays with at least two dimensions.\n\n Parameters\n ----------\n arys1, arys2, ... : array_like\n One or more array-like sequences. Non-array inputs are converted\n to arrays. Arrays that already have two or more dimensions are\n preserved.\n insert_axis : int (optional)\n Where to create a new axis if input array(s) have <2 dim.\n\n Returns\n -------\n res, res2, ... : ndarray\n An array, or tuple of arrays, each with ``a.ndim >= 2``.\n Copies are avoided where possible, and views with two or more\n dimensions are returned.\n\n Examples\n --------\n >>> atleast_2d(3.0) # doctest: +FLOAT_CMP\n array([[3.]])\n\n >>> x = np.arange(3.0)\n >>> atleast_2d(x) # doctest: +FLOAT_CMP\n array([[0., 1., 2.]])\n >>> atleast_2d(x, insert_axis=-1) # doctest: +FLOAT_CMP\n array([[0.],\n [1.],\n [2.]])\n >>> atleast_2d(x).base is x\n True\n\n >>> atleast_2d(1, [1, 2], [[1, 2]])\n [array([[1]]), array([[1, 2]]), array([[1, 2]])]\n\n " ]
Please provide a description of the function:def assert_angles_allclose(x, y, **kwargs): c2 = (np.sin(x)-np.sin(y))**2 + (np.cos(x)-np.cos(y))**2 diff = np.arccos((2.0 - c2)/2.0) # a = b = 1 assert np.allclose(diff, 0.0, **kwargs)
[ "\n Like numpy's assert_allclose, but for angles (in radians).\n " ]
Please provide a description of the function: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)
[ "\n Create a quaternion from unit vector v and rotation angle theta.\n\n Returns\n -------\n q : :class:`gala.coordinates.Quaternion`\n A ``Quaternion`` instance.\n\n " ]
Please provide a description of the function:def v_theta(self): # compute theta norm = np.sqrt(np.sum(self.wxyz**2)) theta = 2 * np.arccos(self.wxyz[0] / norm) # compute the unit vector v = np.array(self.wxyz[1:]) v = v / np.sqrt(np.sum(v**2)) return v, theta
[ "\n Return the ``(v, theta)`` equivalent of the (normalized) quaternion.\n\n Returns\n -------\n v : float\n theta : float\n\n " ]
Please provide a description of the function:def rotation_matrix(self): v, theta = self.v_theta c = np.cos(theta) s = np.sin(theta) return np.array([[v[0] * v[0] * (1. - c) + c, v[0] * v[1] * (1. - c) - v[2] * s, v[0] * v[2] * (1. - c) + v[1] * s], [v[1] * v[0] * (1. - c) + v[2] * s, v[1] * v[1] * (1. - c) + c, v[1] * v[2] * (1. - c) - v[0] * s], [v[2] * v[0] * (1. - c) - v[1] * s, v[2] * v[1] * (1. - c) + v[0] * s, v[2] * v[2] * (1. - c) + c]])
[ "\n Compute the rotation matrix of the (normalized) quaternion.\n\n Returns\n -------\n R : :class:`~numpy.ndarray`\n A 3 by 3 rotation matrix (has shape ``(3,3)``).\n\n " ]
Please provide a description of the function: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])
[ "\n Randomly sample a Quaternion from a distribution uniform in\n 3D rotation angles.\n\n https://www-preview.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf\n\n Returns\n -------\n q : :class:`gala.coordinates.Quaternion`\n A randomly sampled ``Quaternion`` instance.\n\n " ]
Please provide a description of the function: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
[ "\n Step forward the positions and velocities by the given timestep.\n\n Parameters\n ----------\n dt : numeric\n The timestep to move forward.\n " ]
Please provide a description of the function:def _init_v(self, t, w0, dt): # here is where we scoot the velocity at t=t1 to v(t+1/2) F0 = self.F(t.copy(), w0.copy(), *self._func_args) a0 = F0[self.ndim:] v_1_2 = w0[self.ndim:] + a0*dt/2. return v_1_2
[ "\n Leapfrog updates the velocities offset a half-step from the\n position updates. If we're given initial conditions aligned in\n time, e.g. the positions and velocities at the same 0th step,\n then we have to initially scoot the velocities forward by a half\n step to prime the integrator.\n\n Parameters\n ----------\n dt : numeric\n The first timestep.\n " ]
Please provide a description of the function:def generate_n_vectors(N_max, dx=1, dy=1, dz=1, half_lattice=True): r vecs = np.meshgrid(np.arange(-N_max, N_max+1, dx), np.arange(-N_max, N_max+1, dy), np.arange(-N_max, N_max+1, dz)) vecs = np.vstack(map(np.ravel, vecs)).T vecs = vecs[np.linalg.norm(vecs, axis=1) <= N_max] if half_lattice: ix = ((vecs[:, 2] > 0) | ((vecs[:, 2] == 0) & (vecs[:, 1] > 0)) | ((vecs[:, 2] == 0) & (vecs[:, 1] == 0) & (vecs[:, 0] > 0))) vecs = vecs[ix] vecs = np.array(sorted(vecs, key=lambda x: (x[0], x[1], x[2]))) return vecs
[ "\n Generate integer vectors, :math:`\\boldsymbol{n}`, with\n :math:`|\\boldsymbol{n}| < N_{\\rm max}`.\n\n If ``half_lattice=True``, only return half of the three-dimensional\n lattice. If the set N = {(i,j,k)} defines the lattice, we restrict to\n the cases such that ``(k > 0)``, ``(k = 0, j > 0)``, and\n ``(k = 0, j = 0, i > 0)``.\n\n .. todo::\n\n Return shape should be (3,N) to be consistent.\n\n Parameters\n ----------\n N_max : int\n Maximum norm of the integer vector.\n dx : int\n Step size in x direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n dy : int\n Step size in y direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n dz : int\n Step size in z direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n half_lattice : bool (optional)\n Only return half of the 3D lattice.\n\n Returns\n -------\n vecs : :class:`numpy.ndarray`\n A 2D array of integers with :math:`|\\boldsymbol{n}| < N_{\\rm max}`\n with shape (N,3).\n\n " ]
Please provide a description of the function: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 a single orbit.") def f(p, w): logm, logb = p potential = IsochronePotential(m=np.exp(logm), b=np.exp(logb), units=pot.units) H = (potential.value(w[:3]).decompose(pot.units).value + 0.5*np.sum(w[3:]**2, axis=0)) return np.sum(np.squeeze(H - np.mean(H))**2) logm0 = np.log(m0) logb0 = np.log(b0) if minimize_kwargs is None: minimize_kwargs = dict() minimize_kwargs['x0'] = np.array([logm0, logb0]) minimize_kwargs['method'] = minimize_kwargs.get('method', 'Nelder-Mead') res = minimize(f, args=(w,), **minimize_kwargs) if not res.success: raise ValueError("Failed to fit toy potential to orbit.") logm, logb = np.abs(res.x) m = np.exp(logm) b = np.exp(logb) return IsochronePotential(m=m, b=b, units=pot.units)
[ "\n Fit the toy Isochrone potential to the sum of the energy residuals relative\n to the mean energy by minimizing the function\n\n .. math::\n\n f(m,b) = \\sum_i (\\frac{1}{2}v_i^2 + \\Phi_{\\rm iso}(x_i\\,|\\,m,b) - <E>)^2\n\n TODO: This should fail if the Hamiltonian associated with the orbit has\n a frame other than StaticFrame\n\n Parameters\n ----------\n orbit : `~gala.dynamics.Orbit`\n m0 : numeric (optional)\n Initial mass guess.\n b0 : numeric (optional)\n Initial b guess.\n minimize_kwargs : dict (optional)\n Keyword arguments to pass through to `scipy.optimize.minimize`.\n\n Returns\n -------\n m : float\n Best-fit scale mass for the Isochrone potential.\n b : float\n Best-fit core radius for the Isochrone potential.\n\n " ]
Please provide a description of the function: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: raise ValueError("Input orbit object must be a single orbit.") def f(omega, w): potential = HarmonicOscillatorPotential(omega=omega, units=pot.units) H = (potential.value(w[:3]).decompose(pot.units).value + 0.5*np.sum(w[3:]**2, axis=0)) return np.sum(np.squeeze(H - np.mean(H))**2) if minimize_kwargs is None: minimize_kwargs = dict() minimize_kwargs['x0'] = omega0 minimize_kwargs['method'] = minimize_kwargs.get('method', 'Nelder-Mead') res = minimize(f, args=(w,), **minimize_kwargs) if not res.success: raise ValueError("Failed to fit toy potential to orbit.") best_omega = np.abs(res.x) return HarmonicOscillatorPotential(omega=best_omega, units=pot.units)
[ "\n Fit the toy harmonic oscillator potential to the sum of the energy\n residuals relative to the mean energy by minimizing the function\n\n .. math::\n\n f(\\boldsymbol{\\omega}) = \\sum_i (\\frac{1}{2}v_i^2 + \\Phi_{\\rm sho}(x_i\\,|\\,\\boldsymbol{\\omega}) - <E>)^2\n\n TODO: This should fail if the Hamiltonian associated with the orbit has\n a frame other than StaticFrame\n\n Parameters\n ----------\n orbit : `~gala.dynamics.Orbit`\n omega0 : array_like (optional)\n Initial frequency guess.\n minimize_kwargs : dict (optional)\n Keyword arguments to pass through to `scipy.optimize.minimize`.\n\n Returns\n -------\n omegas : float\n Best-fit harmonic oscillator frequencies.\n\n " ]
Please provide a description of the function:def fit_toy_potential(orbit, force_harmonic_oscillator=False): circulation = orbit.circulation() if np.any(circulation == 1) and not force_harmonic_oscillator: # tube orbit logger.debug("===== Tube orbit =====") logger.debug("Using Isochrone toy potential") toy_potential = fit_isochrone(orbit) logger.debug("Best m={}, b={}".format(toy_potential.parameters['m'], toy_potential.parameters['b'])) else: # box orbit logger.debug("===== Box orbit =====") logger.debug("Using triaxial harmonic oscillator toy potential") toy_potential = fit_harmonic_oscillator(orbit) logger.debug("Best omegas ({})" .format(toy_potential.parameters['omega'])) return toy_potential
[ "\n Fit a best fitting toy potential to the orbit provided. If the orbit is a\n tube (loop) orbit, use the Isochrone potential. If the orbit is a box\n potential, use the harmonic oscillator potential. An option is available to\n force using the harmonic oscillator (`force_harmonic_oscillator`).\n\n See the docstrings for ~`gala.dynamics.fit_isochrone()` and\n ~`gala.dynamics.fit_harmonic_oscillator()` for more information.\n\n Parameters\n ----------\n orbit : `~gala.dynamics.Orbit`\n force_harmonic_oscillator : bool (optional)\n Force using the harmonic oscillator potential as the toy potential.\n\n Returns\n -------\n potential : :class:`~gala.potential.IsochronePotential` or :class:`~gala.potential.HarmonicOscillatorPotential`\n The best-fit potential object.\n\n " ]
Please provide a description of the function:def check_angle_sampling(nvecs, angles): failed_nvecs = [] failures = [] for i, vec in enumerate(nvecs): # N = np.linalg.norm(vec) # X = np.dot(angles,vec) 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}" .format(vec)) failed_nvecs.append(vec.tolist()) # P.append(2.*np.pi - diff) failures.append(0) elif (diff/len(X)) > np.pi: warnings.warn("Need a finer sampling for mode {0}" .format(str(vec))) failed_nvecs.append(vec.tolist()) # P.append(np.pi - diff/len(X)) failures.append(1) return np.array(failed_nvecs), np.array(failures)
[ "\n Returns a list of the index of elements of n which do not have adequate\n toy angle coverage. The criterion is that we must have at least one sample\n in each Nyquist box when we project the toy angles along the vector n.\n\n Parameters\n ----------\n nvecs : array_like\n Array of integer vectors.\n angles : array_like\n Array of angles.\n\n Returns\n -------\n failed_nvecs : :class:`numpy.ndarray`\n Array of all integer vectors that failed checks. Has shape (N,3).\n failures : :class:`numpy.ndarray`\n Array of flags that designate whether this failed needing a longer\n integration window (0) or finer sampling (1).\n\n " ]
Please provide a description of the function:def _action_prepare(aa, N_max, dx, dy, dz, sign=1., throw_out_modes=False): # unroll the angles so they increase continuously instead of wrap angles = np.unwrap(aa[3:]) # generate integer vectors for fourier modes nvecs = generate_n_vectors(N_max, dx, dy, dz) # make sure we have enough angle coverage modes, P = check_angle_sampling(nvecs, angles) # throw out modes? # if throw_out_modes: # nvecs = np.delete(nvecs, (modes,P), axis=0) n = len(nvecs) + 3 b = np.zeros(shape=(n, )) A = np.zeros(shape=(n, n)) # top left block matrix: identity matrix summed over timesteps A[:3, :3] = aa.shape[1]*np.identity(3) actions = aa[:3] angles = aa[3:] # top right block matrix: transpose of C_nk matrix (Eq. 12) C_T = 2.*nvecs.T * np.sum(np.cos(np.dot(nvecs, angles)), axis=-1) A[:3,3:] = C_T A[3:, :3] = C_T.T # lower right block matrix: C_nk dotted with C_nk^T cosv = np.cos(np.dot(nvecs, angles)) A[3:,3:] = 4.*np.dot(nvecs, nvecs.T)*np.einsum('it,jt->ij', cosv, cosv) # b vector first three is just sum of toy actions b[:3] = np.sum(actions, axis=1) # rest of the vector is C dotted with actions b[3:] = 2*np.sum(np.dot(nvecs, actions)*np.cos(np.dot(nvecs, angles)), axis=1) return A, b, nvecs
[ "\n Given toy actions and angles, `aa`, compute the matrix `A` and\n vector `b` to solve for the vector of \"true\" actions and generating\n function values, `x` (see Equations 12-14 in Sanders & Binney (2014)).\n\n .. todo::\n\n Wrong shape for aa -- should be (6,n) as usual...\n\n Parameters\n ----------\n aa : array_like\n Shape ``(6,ntimes)`` array of toy actions and angles.\n N_max : int\n Maximum norm of the integer vector.\n dx : int\n Step size in x direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n dy : int\n Step size in y direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n dz : int\n Step size in z direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n sign : numeric (optional)\n Vector that defines direction of circulation about the axes.\n " ]
Please provide a description of the function:def _angle_prepare(aa, t, N_max, dx, dy, dz, sign=1.): # unroll the angles so they increase continuously instead of wrap angles = np.unwrap(aa[3:]) # generate integer vectors for fourier modes nvecs = generate_n_vectors(N_max, dx, dy, dz) # make sure we have enough angle coverage modes, P = check_angle_sampling(nvecs, angles) # TODO: throw out modes? # if(throw_out_modes): # n_vectors = np.delete(n_vectors,check_each_direction(n_vectors,angs),axis=0) nv = len(nvecs) n = 3 + 3 + 3*nv # angle(0)'s, freqs, 3 derivatives of Sn b = np.zeros(shape=(n,)) A = np.zeros(shape=(n, n)) # top left block matrix: identity matrix summed over timesteps A[:3, :3] = aa.shape[1]*np.identity(3) # identity matrices summed over times A[:3, 3:6] = A[3:6, :3] = np.sum(t)*np.identity(3) A[3:6, 3:6] = np.sum(t*t)*np.identity(3) # S1,2,3 A[6:6+nv, 0] = -2.*np.sum(np.sin(np.dot(nvecs, angles)), axis=1) A[6+nv:6+2*nv, 1] = A[6:6+nv, 0] A[6+2*nv:6+3*nv, 2] = A[6:6+nv, 0] # t*S1,2,3 A[6:6+nv, 3] = -2.*np.sum(t[None, :]*np.sin(np.dot(nvecs, angles)), axis=1) A[6+nv:6+2*nv, 4] = A[6:6+nv, 3] A[6+2*nv:6+3*nv, 5] = A[6:6+nv, 3] # lower right block structure: S dot S^T sinv = np.sin(np.dot(nvecs, angles)) SdotST = np.einsum('it,jt->ij', sinv, sinv) A[6:6+nv, 6:6+nv] = A[6+nv:6+2*nv, 6+nv:6+2*nv] = \ A[6+2*nv:6+3*nv, 6+2*nv:6+3*nv] = 4*SdotST # top rectangle A[:6, :] = A[:, :6].T b[:3] = np.sum(angles.T, axis=0) b[3:6] = np.sum(t[:, None]*angles.T, axis=0) b[6:6+nv] = -2.*np.sum(angles[0]*np.sin(np.dot(nvecs, angles)), axis=1) b[6+nv:6+2*nv] = -2.*np.sum(angles[1]*np.sin(np.dot(nvecs, angles)), axis=1) b[6+2*nv:6+3*nv] = -2.*np.sum(angles[2]*np.sin(np.dot(nvecs, angles)), axis=1) return A, b, nvecs
[ "\n Given toy actions and angles, `aa`, compute the matrix `A` and\n vector `b` to solve for the vector of \"true\" angles, frequencies, and\n generating function derivatives, `x` (see Appendix of\n Sanders & Binney (2014)).\n\n .. todo::\n\n Wrong shape for aa -- should be (6,n) as usual...\n\n Parameters\n ----------\n aa : array_like\n Shape ``(6,ntimes)`` array of toy actions and angles.\n t : array_like\n Array of times.\n N_max : int\n Maximum norm of the integer vector.\n dx : int\n Step size in x direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n dy : int\n Step size in y direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n dz : int\n Step size in z direction. Set to 1 for odd and even terms, set\n to 2 for just even terms.\n sign : numeric (optional)\n Vector that defines direction of circulation about the axes.\n " ]
Please provide a description of the function:def _single_orbit_find_actions(orbit, N_max, toy_potential=None, force_harmonic_oscillator=False): if orbit.norbits > 1: raise ValueError("must be a single orbit") if toy_potential is None: toy_potential = fit_toy_potential( orbit, force_harmonic_oscillator=force_harmonic_oscillator) else: logger.debug("Using *fixed* toy potential: {}" .format(toy_potential.parameters)) if isinstance(toy_potential, IsochronePotential): orbit_align = orbit.align_circulation_with_z() w = orbit_align.w() dxyz = (1, 2, 2) circ = np.sign(w[0, 0]*w[4, 0]-w[1, 0]*w[3, 0]) sign = np.array([1., circ, 1.]) orbit = orbit_align elif isinstance(toy_potential, HarmonicOscillatorPotential): dxyz = (2, 2, 2) sign = 1. w = orbit.w() else: raise ValueError("Invalid toy potential.") t = orbit.t.value # Now find toy actions and angles aaf = toy_potential.action_angle(orbit) if aaf[0].ndim > 2: aa = np.vstack((aaf[0].value[..., 0], aaf[1].value[..., 0])) else: aa = np.vstack((aaf[0].value, aaf[1].value)) if np.any(np.isnan(aa)): ix = ~np.any(np.isnan(aa), axis=0) aa = aa[:, ix] t = t[ix] warnings.warn("NaN value in toy actions or angles!") if sum(ix) > 1: raise ValueError("Too many NaN value in toy actions or angles!") t1 = time.time() A, b, nvecs = _action_prepare(aa, N_max, dx=dxyz[0], dy=dxyz[1], dz=dxyz[2]) actions = np.array(solve(A,b)) logger.debug("Action solution found for N_max={}, size {} symmetric" " matrix in {} seconds" .format(N_max, len(actions), time.time()-t1)) t1 = time.time() A, b, nvecs = _angle_prepare(aa, t, N_max, dx=dxyz[0], dy=dxyz[1], dz=dxyz[2], sign=sign) angles = np.array(solve(A, b)) logger.debug("Angle solution found for N_max={}, size {} symmetric" " matrix in {} seconds" .format(N_max, len(angles), time.time()-t1)) # Just some checks if len(angles) > len(aa): warnings.warn("More unknowns than equations!") J = actions[:3] # * sign theta = angles[:3] freqs = angles[3:6] # * sign return dict(actions=J*aaf[0].unit, angles=theta*aaf[1].unit, freqs=freqs*aaf[2].unit, Sn=actions[3:], dSn_dJ=angles[6:], nvecs=nvecs)
[ "\n Find approximate actions and angles for samples of a phase-space orbit,\n `w`, at times `t`. Uses toy potentials with known, analytic action-angle\n transformations to approximate the true coordinates as a Fourier sum.\n\n This code is adapted from Jason Sanders'\n `genfunc <https://github.com/jlsanders/genfunc>`_\n\n .. todo::\n\n Wrong shape for w -- should be (6,n) as usual...\n\n Parameters\n ----------\n orbit : `~gala.dynamics.Orbit`\n N_max : int\n Maximum integer Fourier mode vector length, |n|.\n toy_potential : Potential (optional)\n Fix the toy potential class.\n force_harmonic_oscillator : bool (optional)\n Force using the harmonic oscillator potential as the toy potential.\n " ]
Please provide a description of the function: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((3, norbits)) angles = np.zeros((3, norbits)) freqs = np.zeros((3, norbits)) for n in range(norbits): aaf = _single_orbit_find_actions( orbit[:, n], N_max, force_harmonic_oscillator=force_harmonic_oscillator, toy_potential=toy_potential) actions[n] = aaf['actions'].value angles[n] = aaf['angles'].value freqs[n] = aaf['freqs'].value return dict(actions=actions*aaf['actions'].unit, angles=angles*aaf['angles'].unit, freqs=freqs*aaf['freqs'].unit, Sn=actions[3:], dSn=angles[6:], nvecs=aaf['nvecs'])
[ "\n Find approximate actions and angles for samples of a phase-space orbit.\n Uses toy potentials with known, analytic action-angle transformations to\n approximate the true coordinates as a Fourier sum.\n\n This code is adapted from Jason Sanders'\n `genfunc <https://github.com/jlsanders/genfunc>`_\n\n Parameters\n ----------\n orbit : `~gala.dynamics.Orbit`\n N_max : int\n Maximum integer Fourier mode vector length, :math:`|\\boldsymbol{n}|`.\n force_harmonic_oscillator : bool (optional)\n Force using the harmonic oscillator potential as the toy potential.\n toy_potential : Potential (optional)\n Fix the toy potential class.\n\n Returns\n -------\n aaf : dict\n A Python dictionary containing the actions, angles, frequencies, and\n value of the generating function and derivatives for each integer\n vector. Each value of the dictionary is a :class:`numpy.ndarray` or\n :class:`astropy.units.Quantity`.\n\n " ]
Please provide a description of the function:def parse_time_specification(units, dt=None, n_steps=None, nsteps=None, t1=None, t2=None, t=None): if nsteps is not None: warn("The argument 'nsteps' is deprecated and will be removed in a future version." "Use 'n_steps' instead.") n_steps = nsteps if n_steps is not None: # parse and validate n_steps n_steps = int(n_steps) if hasattr(dt, 'unit'): dt = dt.decompose(units).value if hasattr(t1, 'unit'): t1 = t1.decompose(units).value if hasattr(t2, 'unit'): t2 = t2.decompose(units).value if hasattr(t, 'unit'): t = t.decompose(units).value # t : array_like if t is not None: times = t return times else: if dt is None and (t1 is None or t2 is None or n_steps is None): raise ValueError("Invalid spec. See docstring.") # dt, n_steps[, t1] : (numeric, int[, numeric]) elif dt is not None and n_steps is not None: if t1 is None: t1 = 0. times = parse_time_specification(units, dt=np.ones(n_steps+1)*dt, t1=t1) # dt, t1, t2 : (numeric, numeric, numeric) elif dt is not None and t1 is not None and t2 is not None: if t2 < t1 and dt < 0: t_i = t1 times = [] ii = 0 while (t_i > t2) and (ii < 1E6): times.append(t_i) t_i += dt if times[-1] != t2: times.append(t2) return np.array(times) elif t2 > t1 and dt > 0: t_i = t1 times = [] ii = 0 while (t_i < t2) and (ii < 1E6): times.append(t_i) t_i += dt return np.array(times) else: raise ValueError("If t2 < t1, dt must be negative. If t1 < t2, " "dt should be positive.") # dt, t1 : (array_like, numeric) elif isinstance(dt, np.ndarray) and t1 is not None: times = np.cumsum(np.append([0.], dt)) + t1 times = times[:-1] # n_steps, t1, t2 : (int, numeric, numeric) elif dt is None and not (t1 is None or t2 is None or n_steps is None): times = np.linspace(t1, t2, n_steps, endpoint=True) else: raise ValueError("Invalid options. See docstring.") return times
[ "\n Return an array of times given a few combinations of kwargs that are\n accepted -- see below.\n\n Parameters\n ----------\n dt, n_steps[, t1] : (numeric, int[, numeric])\n A fixed timestep dt and a number of steps to run for.\n dt, t1, t2 : (numeric, numeric, numeric)\n A fixed timestep dt, an initial time, and an final time.\n dt, t1 : (array_like, numeric)\n An array of timesteps dt and an initial time.\n n_steps, t1, t2 : (int, numeric, numeric)\n Number of steps between an initial time, and a final time.\n t : array_like\n An array of times (dts = t[1:] - t[:-1])\n\n " ]
Please provide a description of the function: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[i]+=np.pi return np.concatenate((action,angle % (2.*np.pi)))
[ " Calculate angle and action variable in sho potential with\n parameter omega " ]
Please provide a description of the function:def findbestparams_ho(xsamples): return np.abs(leastsq(deltaH_ho,np.array([10.,10.,10.]), Dfun = Jac_deltaH_ho, args=(xsamples,))[0])[:3]
[ " Minimize sum of square differences of H_sho-<H_sho> for timesamples " ]
Please provide a description of the function:def cart2spol(X): x,y,z,vx,vy,vz=X r=np.sqrt(x*x+y*y+z*z) p=np.arctan2(y,x) t=np.arccos(z/r) vr=(vx*np.cos(p)+vy*np.sin(p))*np.sin(t)+np.cos(t)*vz vp=-vx*np.sin(p)+vy*np.cos(p) vt=(vx*np.cos(p)+vy*np.sin(p))*np.cos(t)-np.sin(t)*vz return np.array([r,p,t,vr,vp,vt])
[ " Performs coordinate transformation from cartesian\n to spherical polar coordinates with (r,phi,theta) having\n usual meanings. " ]
Please provide a description of the function:def H_iso(x,params): #r = (np.sqrt(np.sum(x[:3]**2))-params[2])**2 r = np.sum(x[:3]**2) return 0.5*np.sum(x[3:]**2)-Grav*params[0]/(params[1]+np.sqrt(params[1]**2+r))
[ " Isochrone Hamiltonian = -GM/(b+sqrt(b**2+(r-r0)**2))" ]
Please provide a description of the function:def angact_iso(x,params): GM = Grav*params[0] E = H_iso(x,params) r,p,t,vr,vphi,vt=cart2spol(x) st=np.sin(t) Lz=r*vphi*st L=np.sqrt(r*r*vt*vt+Lz*Lz/st/st) if(E>0.): # Unbound return (np.nan,np.nan,np.nan,np.nan,np.nan,np.nan) Jr=GM/np.sqrt(-2*E)-0.5*(L+np.sqrt(L*L+4*GM*params[1])) action = np.array([Jr,Lz,L-abs(Lz)]) c=GM/(-2*E)-params[1] e=np.sqrt(1-L*L*(1+params[1]/c)/GM/c) eta=np.arctan2(r*vr/np.sqrt(-2.*E),params[1]+c-np.sqrt(params[1]**2+r*r)) OmR=np.power(-2*E,1.5)/GM Omp=0.5*OmR*(1+L/np.sqrt(L*L+4*GM*params[1])) thetar=eta-e*c*np.sin(eta)/(c+params[1]) if(abs(vt)>1e-10): psi=np.arctan2(np.cos(t),-np.sin(t)*r*vt/L) else: psi=np.pi/2. a=np.sqrt((1+e)/(1-e)) ap=np.sqrt((1+e+2*params[1]/c)/(1-e+2*params[1]/c)) F = lambda x,y: np.pi/2.-np.arctan(np.tan(np.pi/2.-0.5*y)/x) if y>np.pi/2. \ else -np.pi/2.+np.arctan(np.tan(np.pi/2.+0.5*y)/x) if y<-np.pi/2. \ else np.arctan(x*np.tan(0.5*y)) thetaz=psi+Omp*thetar/OmR-F(a,eta)-F(ap,eta)/np.sqrt(1+4*GM*params[1]/L/L) LR=Lz/L sinu = LR/np.sqrt(1.-LR**2)/np.tan(t) u = 0 if(sinu>1.): u=np.pi/2. elif(sinu<-1.): u = -np.pi/2. else: u = np.arcsin(sinu) if(vt>0.): u=np.pi-u thetap=p-u+np.sign(Lz)*thetaz angle = np.array([thetar,thetap,thetaz]) return np.concatenate((action,angle % (2.*np.pi)))
[ " Calculate angle and action variable in isochrone potential with\n parameters params = (M,b) " ]
Please provide a description of the function:def findbestparams_iso(xsamples): p = 0.5*np.sum(xsamples.T[3:]**2,axis=0) r = np.sum(xsamples.T[:3]**2,axis=0) return np.abs(leastsq(deltaH_iso,np.array([10.,10.]), Dfun = None , col_deriv=1,args=(p,r,))[0])
[ " Minimize sum of square differences of H_iso-<H_iso> for timesamples" ]
Please provide a description of the function: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 # find peaks max_ix = argrelmax(f, mode='wrap')[0] max_ix = max_ix[(max_ix != 0) & (max_ix != (len(f)-1))] # find troughs min_ix = argrelmin(f, mode='wrap')[0] min_ix = min_ix[(min_ix != 0) & (min_ix != (len(f)-1))] # neglect minor oscillations if abs(np.mean(f[max_ix]) - np.mean(f[min_ix])) < amplitude_threshold: return np.nan # compute mean peak-to-peak if len(max_ix) > 0: T_max = np.mean(t[max_ix[1:]] - t[max_ix[:-1]]) else: T_max = np.nan # now compute mean trough-to-trough if len(min_ix) > 0: T_min = np.mean(t[min_ix[1:]] - t[min_ix[:-1]]) else: T_min = np.nan # then take the mean of these two return np.mean([T_max, T_min]) * t_unit
[ "\n Estimate the period of the input time series by measuring the average\n peak-to-peak time.\n\n Parameters\n ----------\n t : array_like\n Time grid aligned with the input time series.\n f : array_like\n A periodic time series.\n amplitude_threshold : numeric (optional)\n A tolerance parameter. Fails if the mean amplitude of oscillations\n isn't larger than this tolerance.\n\n Returns\n -------\n period : float\n The mean peak-to-peak period.\n " ]
Please provide a description of the function: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) # integrate orbit dt = _autodetermine_initial_dt(w0, hamiltonian, dE_threshold=dE_threshold, **integrate_kwargs) n_steps = int(round(10000 / dt)) orbit = hamiltonian.integrate_orbit(w0, dt=dt, n_steps=n_steps, **integrate_kwargs) # if loop, align circulation with Z and take R period circ = orbit.circulation() if np.any(circ): orbit = orbit.align_circulation_with_z(circulation=circ) cyl = orbit.represent_as(coord.CylindricalRepresentation) # convert to cylindrical coordinates R = cyl.rho.value phi = cyl.phi.value z = cyl.z.value T = np.array([peak_to_peak_period(orbit.t, f).value for f in [R, phi, z]])*orbit.t.unit else: T = np.array([peak_to_peak_period(orbit.t, f).value for f in orbit.pos])*orbit.t.unit # timestep from number of steps per period T = func(T) if np.isnan(T): raise RuntimeError("Failed to find period.") T = T.decompose(hamiltonian.units).value dt = T / float(n_steps_per_period) n_steps = int(round(n_periods * T / dt)) if dt == 0. or dt < 1E-13: raise ValueError("Timestep is zero or very small!") return dt, n_steps
[ "\n Estimate the timestep and number of steps to integrate an orbit for\n given its initial conditions and a potential object.\n\n Parameters\n ----------\n w0 : `~gala.dynamics.PhaseSpacePosition`, array_like\n Initial conditions.\n potential : :class:`~gala.potential.PotentialBase`\n The potential to integrate the orbit in.\n n_periods : int\n Number of (max) orbital periods to integrate for.\n n_steps_per_period : int\n Number of steps to take per (max) orbital period.\n dE_threshold : numeric (optional)\n Maximum fractional energy difference -- used to determine initial\n timestep. Set to ``None`` to ignore this.\n func : callable (optional)\n Determines which period to use. By default, this takes the maximum\n period using :func:`~numpy.nanmax`. Other options could be\n :func:`~numpy.nanmin`, :func:`~numpy.nanmean`, :func:`~numpy.nanmedian`.\n\n Returns\n -------\n dt : float\n The timestep.\n n_steps : int\n The number of timesteps to integrate for.\n\n " ]
Please provide a description of the function:def combine(objs): from .orbit import Orbit # have to special-case this because they are iterable if isinstance(objs, PhaseSpacePosition) or isinstance(objs, Orbit): raise ValueError("You must pass a non-empty iterable to combine.") elif not isiterable(objs) or len(objs) < 1: raise ValueError("You must pass a non-empty iterable to combine.") elif len(objs) == 1: # short circuit return objs[0] # We only support these two types to combine: if objs[0].__class__ not in [PhaseSpacePosition, Orbit]: raise TypeError("Objects must be either PhaseSpacePosition or Orbit " "instances.") # Validate objects: # - check type # - check dimensionality # - check frame, potential # - Right now, we only support Cartesian for obj in objs: # Check to see if they are all the same type of object: if obj.__class__ != objs[0].__class__: raise TypeError("All objects must have the same type.") # Make sure they have same dimensionality if obj.ndim != objs[0].ndim: raise ValueError("All objects must have the same ndim.") # Check that all objects have the same reference frame if obj.frame != objs[0].frame: raise ValueError("All objects must have the same frame.") # Check that (for orbits) they all have the same potential if hasattr(obj, 'potential') and obj.potential != objs[0].potential: raise ValueError("All objects must have the same potential.") # For orbits, time arrays must be the same if (hasattr(obj, 't') and obj.t is not None and objs[0].t is not None and not quantity_allclose(obj.t, objs[0].t, atol=1E-13*objs[0].t.unit)): raise ValueError("All orbits must have the same time array.") if 'cartesian' not in obj.pos.get_name(): raise NotImplementedError("Currently, combine only works for " "Cartesian-represented objects.") # Now we prepare the positions, velocities: if objs[0].__class__ == PhaseSpacePosition: pos = [] vel = [] for i, obj in enumerate(objs): if i == 0: pos_unit = obj.pos.xyz.unit vel_unit = obj.vel.d_xyz.unit pos.append(atleast_2d(obj.pos.xyz.to(pos_unit).value, insert_axis=1)) vel.append(atleast_2d(obj.vel.d_xyz.to(vel_unit).value, insert_axis=1)) pos = np.concatenate(pos, axis=1) * pos_unit vel = np.concatenate(vel, axis=1) * vel_unit return PhaseSpacePosition(pos=pos, vel=vel, frame=objs[0].frame) elif objs[0].__class__ == Orbit: pos = [] vel = [] for i, obj in enumerate(objs): if i == 0: pos_unit = obj.pos.xyz.unit vel_unit = obj.vel.d_xyz.unit p = obj.pos.xyz.to(pos_unit).value v = obj.vel.d_xyz.to(vel_unit).value if p.ndim < 3: p = p.reshape(p.shape + (1,)) v = v.reshape(v.shape + (1,)) pos.append(p) vel.append(v) pos = np.concatenate(pos, axis=2) * pos_unit vel = np.concatenate(vel, axis=2) * vel_unit return Orbit(pos=pos, vel=vel, t=objs[0].t, frame=objs[0].frame, potential=objs[0].potential) else: raise RuntimeError("should never get here...")
[ "Combine the specified `~gala.dynamics.PhaseSpacePosition` or\n `~gala.dynamics.Orbit` objects.\n\n Parameters\n ----------\n objs : iterable\n An iterable of either `~gala.dynamics.PhaseSpacePosition` or\n `~gala.dynamics.Orbit` objects.\n " ]
Please provide a description of the function:def reflex_correct(coords, galactocentric_frame=None): c = coord.SkyCoord(coords) # If not specified, use the Astropy default Galactocentric frame 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_differentials() rep = rep.with_differentials(observed.cartesian.differentials['s'] + v_sun) fr = galactocentric_frame.realize_frame(rep).transform_to(c.frame) return coord.SkyCoord(fr)
[ "Correct the input Astropy coordinate object for solar reflex motion.\n\n The input coordinate instance must have distance and radial velocity information. If the radial velocity is not known, fill the\n\n Parameters\n ----------\n coords : `~astropy.coordinates.SkyCoord`\n The Astropy coordinate object with position and velocity information.\n galactocentric_frame : `~astropy.coordinates.Galactocentric` (optional)\n To change properties of the Galactocentric frame, like the height of the\n sun above the midplane, or the velocity of the sun in a Galactocentric\n intertial frame, set arguments of the\n `~astropy.coordinates.Galactocentric` object and pass in to this\n function with your coordinates.\n\n Returns\n -------\n coords : `~astropy.coordinates.SkyCoord`\n The coordinates in the same frame as input, but with solar motion\n removed.\n\n " ]
Please provide a description of the function:def _get_axes(dim, subplots_kwargs=dict()): import matplotlib.pyplot as plt if dim > 1: n_panels = int(dim * (dim - 1) / 2) else: n_panels = 1 figsize = subplots_kwargs.pop('figsize', (4*n_panels, 4)) fig, axes = plt.subplots(1, n_panels, figsize=figsize, **subplots_kwargs) if n_panels == 1: axes = [axes] else: axes = axes.flat return axes
[ "\n Parameters\n ----------\n dim : int\n Dimensionality of the orbit.\n subplots_kwargs : dict (optional)\n Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.\n " ]
Please provide a description of the function:def plot_projections(x, relative_to=None, autolim=True, axes=None, subplots_kwargs=dict(), labels=None, plot_function=None, **kwargs): # don't propagate changes back... x = np.array(x, copy=True) ndim = x.shape[0] # get axes object from arguments if axes is None: axes = _get_axes(dim=ndim, subplots_kwargs=subplots_kwargs) # if the quantities are relative if relative_to is not None: x -= relative_to # name of the plotting function plot_fn_name = plot_function.__name__ # automatically determine limits if autolim: lims = [] for i in range(ndim): max_,min_ = np.max(x[i]), np.min(x[i]) delta = max_ - min_ if delta == 0.: delta = 1. lims.append([min_ - delta*0.02, max_ + delta*0.02]) k = 0 for i in range(ndim): for j in range(ndim): if i >= j: continue # skip diagonal, upper triangle plot_func = getattr(axes[k], plot_fn_name) plot_func(x[i], x[j], **kwargs) if labels is not None: axes[k].set_xlabel(labels[i]) axes[k].set_ylabel(labels[j]) if autolim: axes[k].set_xlim(lims[i]) axes[k].set_ylim(lims[j]) k += 1 axes[0].figure.tight_layout() return axes[0].figure
[ "\n Given N-dimensional quantity, ``x``, make a figure containing 2D projections\n of all combinations of the axes.\n\n Parameters\n ----------\n x : array_like\n Array of values. ``axis=0`` is assumed to be the dimensionality,\n ``axis=1`` is the time axis. See :ref:`shape-conventions` for more\n information.\n relative_to : bool (optional)\n Plot the values relative to this value or values.\n autolim : bool (optional)\n Automatically set the plot limits to be something sensible.\n axes : array_like (optional)\n Array of matplotlib Axes objects.\n subplots_kwargs : dict (optional)\n Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.\n labels : iterable (optional)\n List or iterable of axis labels as strings. They should correspond to\n the dimensions of the input orbit.\n plot_function : callable (optional)\n The ``matplotlib`` plot function to use. By default, this is\n :func:`~matplotlib.pyplot.scatter`, but can also be, e.g.,\n :func:`~matplotlib.pyplot.plot`.\n **kwargs\n All other keyword arguments are passed to the ``plot_function``.\n You can pass in any of the usual style kwargs like ``color=...``,\n ``marker=...``, etc.\n\n Returns\n -------\n fig : `~matplotlib.Figure`\n\n " ]
Please provide a description of the function:def check_angle_solution(ang,n_vec,toy_aa,timeseries): f,a=plt.subplots(3,1) for i in range(3): a[i].plot(toy_aa.T[i+3],'.') size = len(ang[6:])/3 AA = np.array([np.sum(ang[6+i*size:6+(i+1)*size]*np.sin(np.sum(n_vec*K,axis=1))) for K in toy_aa.T[3:].T]) a[i].plot((ang[i]+ang[i+3]*timeseries-2.*AA) % (2.*np.pi),'.') a[i].set_ylabel(r'$\theta$'+str(i+1)) a[2].set_xlabel(r'$t$') plt.show()
[ " Plots the toy angle solution against the toy angles ---\n Takes true angles and frequencies ang,\n the Fourier vectors n_vec,\n the toy action-angles toy_aa\n and the timeseries " ]
Please provide a description of the function:def eval_mean_error_functions(act,ang,n_vec,toy_aa,timeseries,withplot=False): Err = np.zeros(6) NT = len(timeseries) size = len(ang[6:])/3 UA = ua(toy_aa.T[3:].T,np.ones(3)) fig,axis=None,None if(withplot): fig,axis=plt.subplots(3,2) plt.subplots_adjust(wspace=0.3) for K in range(3): ErrJ = np.array([(i[K]-act[K]-2.*np.sum(n_vec.T[K]*act[3:]*np.cos(np.dot(n_vec,i[3:]))))**2 for i in toy_aa]) Err[K] = np.sum(ErrJ) ErrT = np.array(((ang[K]+timeseries*ang[K+3]-UA.T[K]-2.*np.array([np.sum(ang[6+K*size:6+(K+1)*size]*np.sin(np.sum(n_vec*i,axis=1))) for i in toy_aa.T[3:].T])))**2) Err[K+3] = np.sum(ErrT) if(withplot): axis[K][0].plot(ErrJ,'.') axis[K][0].set_ylabel(r'$E$'+str(K+1)) axis[K][1].plot(ErrT,'.') axis[K][1].set_ylabel(r'$F$'+str(K+1)) if(withplot): for i in range(3): axis[i][0].set_xlabel(r'$t$') axis[i][1].set_xlabel(r'$t$') plt.show() EJ = np.sqrt(Err[:3]/NT) ET = np.sqrt(Err[3:]/NT) return np.array([EJ,ET])
[ " Calculates sqrt(mean(E)) and sqrt(mean(F)) " ]
Please provide a description of the function:def box_actions(results, times, N_matrix, ifprint): if(ifprint): print("\n=====\nUsing triaxial harmonic toy potential") t = time.time() # Find best toy parameters omega = toy.findbestparams_ho(results) if(ifprint): print("Best omega "+str(omega)+" found in "+str(time.time()-t)+" seconds") # Now find toy actions and angles AA = np.array([toy.angact_ho(i,omega) for i in results]) AA = AA[~np.isnan(AA).any(1)] if(len(AA)==0): return t = time.time() act = solver.solver(AA, N_matrix) if act==None: return if(ifprint): print("Action solution found for N_max = "+str(N_matrix)+", size "+str(len(act[0]))+" symmetric matrix in "+str(time.time()-t)+" seconds") np.savetxt("GF.Sn_box",np.vstack((act[1].T,act[0][3:])).T) ang = solver.angle_solver(AA,times,N_matrix,np.ones(3)) if(ifprint): print("Angle solution found for N_max = "+str(N_matrix)+", size "+str(len(ang))+" symmetric matrix in "+str(time.time()-t)+" seconds") # Just some checks if(len(ang)>len(AA)): print("More unknowns than equations") return act[0], ang, act[1], AA, omega
[ "\n Finds actions, angles and frequencies for box orbit.\n Takes a series of phase-space points from an orbit integration at times t and returns\n L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.\n " ]
Please provide a description of the function:def loop_actions(results, times, N_matrix, ifprint): if(ifprint): print("\n=====\nUsing isochrone toy potential") t = time.time() # First find the best set of toy parameters params = toy.findbestparams_iso(results) if(params[0]!=params[0]): params = np.array([10.,10.]) if(ifprint): print("Best params "+str(params)+" found in "+str(time.time()-t)+" seconds") # Now find the toy angles and actions in this potential AA = np.array([toy.angact_iso(i,params) for i in results]) AA = AA[~np.isnan(AA).any(1)] if(len(AA)==0): return t = time.time() act = solver.solver(AA, N_matrix,symNx = 1) if act==None: return if(ifprint): print("Action solution found for N_max = "+str(N_matrix)+", size "+str(len(act[0]))+" symmetric matrix in "+str(time.time()-t)+" seconds") # Store Sn np.savetxt("GF.Sn_loop",np.vstack((act[1].T,act[0][3:])).T) # Find angles sign = np.array([1.,np.sign(results[0][0]*results[0][4]-results[0][1]*results[0][3]),1.]) ang = solver.angle_solver(AA,times,N_matrix,sign,symNx = 1) if(ifprint): print("Angle solution found for N_max = "+str(N_matrix)+", size "+str(len(ang))+" symmetric matrix in "+str(time.time()-t)+" seconds") # Just some checks if(len(ang)>len(AA)): print("More unknowns than equations") return act[0], ang, act[1], AA, params
[ "\n Finds actions, angles and frequencies for loop orbit.\n Takes a series of phase-space points from an orbit integration at times t and returns\n L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.\n results must be oriented such that circulation is about the z-axis\n " ]
Please provide a description of the function:def angmom(x): return np.array([x[1]*x[5]-x[2]*x[4],x[2]*x[3]-x[0]*x[5],x[0]*x[4]-x[1]*x[3]])
[ " returns angular momentum vector of phase-space point x" ]
Please provide a description of the function:def assess_angmom(X): L=angmom(X[0]) loop = np.array([1,1,1]) for i in X[1:]: L0 = angmom(i) if(L0[0]*L[0]<0.): loop[0] = 0 if(L0[1]*L[1]<0.): loop[1] = 0 if(L0[2]*L[2]<0.): loop[2] = 0 return loop
[ "\n Checks for change of sign in each component of the angular momentum.\n Returns an array with ith entry 1 if no sign change in i component\n and 0 if sign change.\n Box = (0,0,0)\n S.A loop = (0,0,1)\n L.A loop = (1,0,0)\n " ]
Please provide a description of the function:def flip_coords(X,loop): if(loop[0]==1): return np.array(map(lambda i: np.array([i[2],i[1],i[0],i[5],i[4],i[3]]),X)) else: return X
[ " Align circulation with z-axis " ]
Please provide a description of the function:def find_actions(results, t, N_matrix=8, use_box=False, ifloop=False, ifprint = True): # Determine orbit class loop = assess_angmom(results) arethereloops = np.any(loop>0) if(arethereloops and not use_box): L = loop_actions(flip_coords(results,loop),t,N_matrix, ifprint) if(L==None): if(ifprint): print("Failed to find actions for this orbit") return # Used for switching J_2 and J_3 for long-axis loop orbits # This is so the orbit classes form a continuous plane in action space # if(loop[0]): # L[0][1],L[0][2]=L[0][2],L[0][1] # L[1][1],L[1][2]=L[1][2],L[1][1] # L[1][4],L[1][5]=L[1][5],L[1][4] # L[3].T[1],L[3].T[2]=L[3].T[2],L[3].T[1] else: L = box_actions(results,t,N_matrix, ifprint) if(L==None): if(ifprint): print("Failed to find actions for this orbit") return if(ifloop): return L,loop else: return L
[ "\n Main routine:\n Takes a series of phase-space points from an orbit integration at times t and returns\n L = (act,ang,n_vec,toy_aa, pars) where act is the actions, ang the initial angles and\n frequencies, n_vec the n vectors of the Fourier modes, toy_aa the toy action-angle\n coords, and pars are the toy potential parameters\n N_matrix sets the maximum |n| of the Fourier modes used,\n use_box forces the routine to use the triaxial harmonic oscillator as the toy potential,\n ifloop=True returns orbit classification,\n ifprint=True prints progress messages.\n " ]
Please provide a description of the function:def plot_Sn_timesamples(PSP): TT = pot.stackel_triax() f,a = plt.subplots(2,1,figsize=[3.32,3.6]) plt.subplots_adjust(hspace=0.,top=0.8) LowestPeriod = 2.*np.pi/38.86564386 Times = np.array([2.,4.,8.,12.]) Sr = np.arange(2,14,2) # Loop over length of integration window for i,P,C in zip(Times,['.','s','D','^'],['k','r','b','g']): diffact = np.zeros((len(Sr),3)) difffreq = np.zeros((len(Sr),3)) MAXGAPS = np.array([]) # Loop over N_max for k,j in enumerate(Sr): NT = choose_NT(j) timeseries=np.linspace(0.,i*LowestPeriod,NT) results = odeint(pot.orbit_derivs2,PSP,timeseries,args=(TT,),rtol=1e-13,atol=1e-13) act,ang,n_vec,toy_aa, pars = find_actions(results, timeseries,N_matrix=j,ifprint=False,use_box=True) # Check all modes checks,maxgap = ced(n_vec,ua(toy_aa.T[3:].T,np.ones(3))) if len(maxgap)>0: maxgap = np.max(maxgap) else: maxgap = 0 diffact[k] = act[:3]/TT.action(results[0]) MAXGAPS = np.append(MAXGAPS,maxgap) difffreq[k] = ang[3:6]/TT.freq(results[0]) size = 15 if(P=='.'): size = 30 LW = np.array(map(lambda i: 0.5+i*0.5, MAXGAPS)) a[0].scatter(Sr,np.log10(np.abs(diffact.T[2]-1)),marker=P,s=size, color=C,facecolors="none",lw=LW,label=r'$T =\,$'+str(i)+r'$\,T_F$') a[1].scatter(Sr,np.log10(np.abs(difffreq.T[2]-1)),marker=P,s=size, color=C,facecolors="none", lw=LW) a[1].get_yticklabels()[-1].set_visible(False) a[0].set_xticklabels([]) a[0].set_xlim(1,13) a[0].set_ylabel(r"$\log_{10}|J_3^\prime/J_{3, \rm true}-1|$") leg = a[0].legend(loc='upper center',bbox_to_anchor=(0.5,1.4),ncol=2, scatterpoints = 1) leg.draw_frame(False) a[1].set_xlim(1,13) a[1].set_xlabel(r'$N_{\rm max}$') a[1].set_ylabel(r"$\log_{10}|\Omega_3^\prime/\Omega_{3,\rm true}-1|$") plt.savefig('Sn_T_box.pdf',bbox_inches='tight')
[ " Plots Fig. 5 from Sanders & Binney (2014) " ]
Please provide a description of the function:def plot3D_stacktriax(initial,final_t,N_MAT,file_output): # Setup Stackel potential TT = pot.stackel_triax() times = choose_NT(N_MAT) timeseries=np.linspace(0.,final_t,times) # Integrate orbit results = odeint(pot.orbit_derivs2,initial,timeseries,args=(TT,),rtol=1e-13,atol=1e-13) # Find actions, angles and frequencies (act,ang,n_vec,toy_aa, pars),loop = find_actions(results, timeseries,N_matrix=N_MAT,ifloop=True) toy_pot = 0 if(loop[2]>0.5 or loop[0]>0.5): toy_pot = pot.isochrone(par=np.append(pars,0.)) else: toy_pot = pot.harmonic_oscillator(omega=pars[:3]) # Integrate initial condition in toy potential timeseries_2=np.linspace(0.,2.*final_t,3500) results_toy = odeint(pot.orbit_derivs2,initial,timeseries_2,args=(toy_pot,)) # and plot f,a = plt.subplots(2,3,figsize=[3.32,5.5]) a[0,0] = plt.subplot2grid((3,2), (0, 0)) a[1,0] = plt.subplot2grid((3,2), (0, 1)) a[0,1] = plt.subplot2grid((3,2), (1, 0)) a[1,1] = plt.subplot2grid((3,2), (1, 1)) a[0,2] = plt.subplot2grid((3,2), (2, 0),colspan=2) plt.subplots_adjust(wspace=0.5,hspace=0.45) # xy orbit a[0,0].plot(results.T[0],results.T[1],'k') a[0,0].set_xlabel(r'$x/{\rm kpc}$') a[0,0].set_ylabel(r'$y/{\rm kpc}$') a[0,0].xaxis.set_major_locator(MaxNLocator(5)) # xz orbit a[1,0].plot(results.T[0],results.T[2],'k') a[1,0].set_xlabel(r'$x/{\rm kpc}$') a[1,0].set_ylabel(r'$z/{\rm kpc}$') a[1,0].xaxis.set_major_locator(MaxNLocator(5)) # toy orbits a[0,0].plot(results_toy.T[0],results_toy.T[1],'r',alpha=0.2,linewidth=0.3) a[1,0].plot(results_toy.T[0],results_toy.T[2],'r',alpha=0.2,linewidth=0.3) # Toy actions a[0,2].plot(Conv*timeseries,toy_aa.T[0],'k:',label='Toy action') a[0,2].plot(Conv*timeseries,toy_aa.T[1],'r:') a[0,2].plot(Conv*timeseries,toy_aa.T[2],'b:') # Arrows to show approx. actions arrow_end = a[0,2].get_xlim()[1] arrowd = 0.08*(arrow_end-a[0,2].get_xlim()[0]) a[0,2].annotate('',(arrow_end+arrowd,act[0]),(arrow_end,act[0]),arrowprops=dict(arrowstyle='<-',color='k'),annotation_clip=False) a[0,2].annotate('',(arrow_end+arrowd,act[1]),(arrow_end,act[1]),arrowprops=dict(arrowstyle='<-',color='r'),annotation_clip=False) a[0,2].annotate('',(arrow_end+arrowd,act[2]),(arrow_end,act[2]),arrowprops=dict(arrowstyle='<-',color='b'),annotation_clip=False) # True actions a[0,2].plot(Conv*timeseries,TT.action(results[0])[0]*np.ones(len(timeseries)),'k',label='True action') a[0,2].plot(Conv*timeseries,TT.action(results[0])[1]*np.ones(len(timeseries)),'k') a[0,2].plot(Conv*timeseries,TT.action(results[0])[2]*np.ones(len(timeseries)),'k') a[0,2].set_xlabel(r'$t/{\rm Gyr}$') a[0,2].set_ylabel(r'$J/{\rm kpc\,km\,s}^{-1}$') leg = a[0,2].legend(loc='upper center',bbox_to_anchor=(0.5,1.2),ncol=3, numpoints = 1) leg.draw_frame(False) # Toy angle coverage a[0,1].plot(toy_aa.T[3]/(np.pi),toy_aa.T[4]/(np.pi),'k.',markersize=0.4) a[0,1].set_xlabel(r'$\theta_1/\pi$') a[0,1].set_ylabel(r'$\theta_2/\pi$') a[1,1].plot(toy_aa.T[3]/(np.pi),toy_aa.T[5]/(np.pi),'k.',markersize=0.4) a[1,1].set_xlabel(r'$\theta_1/\pi$') a[1,1].set_ylabel(r'$\theta_3/\pi$') plt.savefig(file_output,bbox_inches='tight') return act
[ " For producing plots from paper " ]
Please provide a description of the function:def cartesian_to_poincare_polar(w): r R = np.sqrt(w[...,0]**2 + w[...,1]**2) # phi = np.arctan2(w[...,1], w[...,0]) phi = np.arctan2(w[...,0], w[...,1]) vR = (w[...,0]*w[...,0+3] + w[...,1]*w[...,1+3]) / R vPhi = w[...,0]*w[...,1+3] - w[...,1]*w[...,0+3] # pg. 437, Papaphillipou & Laskar (1996) sqrt_2THETA = np.sqrt(np.abs(2*vPhi)) pp_phi = sqrt_2THETA * np.cos(phi) pp_phidot = sqrt_2THETA * np.sin(phi) z = w[...,2] zdot = w[...,2+3] new_w = np.vstack((R.T, pp_phi.T, z.T, vR.T, pp_phidot.T, zdot.T)).T return new_w
[ "\n Convert an array of 6D Cartesian positions to Poincaré\n symplectic polar coordinates. These are similar to cylindrical\n coordinates.\n\n Parameters\n ----------\n w : array_like\n Input array of 6D Cartesian phase-space positions. Should have\n shape ``(norbits,6)``.\n\n Returns\n -------\n new_w : :class:`~numpy.ndarray`\n Points represented in 6D Poincaré polar coordinates.\n\n " ]
Please provide a description of the function:def isochrone_to_aa(w, potential): if not isinstance(potential, PotentialBase): potential = IsochronePotential(**potential) usys = potential.units GM = (G*potential.parameters['m']).decompose(usys).value b = potential.parameters['b'].decompose(usys).value E = w.energy(Hamiltonian(potential)).decompose(usys).value E = np.squeeze(E) if np.any(E > 0.): raise ValueError("Unbound particle. (E = {})".format(E)) # convert position, velocity to spherical polar coordinates w_sph = w.represent_as(coord.PhysicsSphericalRepresentation) r,phi,theta = map(np.squeeze, [w_sph.r.decompose(usys).value, w_sph.phi.radian, w_sph.theta.radian]) ang_unit = u.radian/usys['time'] vr,phi_dot,theta_dot = map(np.squeeze, [w_sph.radial_velocity.decompose(usys).value, w_sph.pm_phi.to(ang_unit).value, w_sph.pm_theta.to(ang_unit).value]) vphi = r*np.sin(theta) * phi_dot vtheta = r*theta_dot # ---------------------------- # Compute the actions # ---------------------------- L_vec = np.squeeze(w.angular_momentum().decompose(usys).value) Lz = L_vec[2] L = np.linalg.norm(L_vec, axis=0) # Radial action Jr = GM / np.sqrt(-2*E) - 0.5*(L + np.sqrt(L*L + 4*GM*b)) # compute the three action variables actions = np.array([Jr, Lz, L - np.abs(Lz)]) # Jr, Jphi, Jtheta # ---------------------------- # Angles # ---------------------------- c = GM / (-2*E) - b e = np.sqrt(1 - L*L*(1 + b/c) / GM / c) # Compute theta_r using eta tmp1 = r*vr / np.sqrt(-2.*E) tmp2 = b + c - np.sqrt(b*b + r*r) eta = np.arctan2(tmp1,tmp2) thetar = eta - e*c*np.sin(eta) / (c + b) # same as theta3 # Compute theta_z psi = np.arctan2(np.cos(theta), -np.sin(theta)*r*vtheta/L) psi[np.abs(vtheta) <= 1e-10] = np.pi/2. # blows up for small vtheta omega_th = 0.5 * (1 + L/np.sqrt(L*L + 4*GM*b)) a = np.sqrt((1+e) / (1-e)) ap = np.sqrt((1 + e + 2*b/c) / (1 - e + 2*b/c)) def F(x, y): z = np.zeros_like(x) ix = y>np.pi/2. z[ix] = np.pi/2. - np.arctan(np.tan(np.pi/2.-0.5*y[ix])/x[ix]) ix = y<-np.pi/2. z[ix] = -np.pi/2. + np.arctan(np.tan(np.pi/2.+0.5*y[ix])/x[ix]) ix = (y<=np.pi/2) & (y>=-np.pi/2) z[ix] = np.arctan(x[ix]*np.tan(0.5*y[ix])) return z A = omega_th*thetar - F(a,eta) - F(ap,eta)/np.sqrt(1 + 4*GM*b/L/L) thetaz = psi + A LR = Lz/L sinu = (LR/np.sqrt(1.-LR*LR)/np.tan(theta)) uu = np.arcsin(sinu) uu[sinu > 1.] = np.pi/2. uu[sinu < -1.] = -np.pi/2. uu[vtheta > 0.] = np.pi - uu[vtheta > 0.] thetap = phi - uu + np.sign(Lz)*thetaz angles = np.array([thetar, thetap, thetaz]) angles = angles % (2*np.pi) # ---------------------------- # Frequencies # ---------------------------- freqs = np.zeros_like(actions) omega_r = GM**2 / (Jr + 0.5*(L + np.sqrt(L*L + 4*GM*b)))**3 freqs[0] = omega_r freqs[1] = np.sign(actions[1]) * omega_th * omega_r freqs[2] = omega_th * omega_r a_unit = (1*usys['angular momentum']/usys['mass']).decompose(usys).unit f_unit = (1*usys['frequency']).decompose(usys).unit return actions*a_unit, angles*u.radian, freqs*f_unit
[ "\n Transform the input cartesian position and velocity to action-angle\n coordinates in the Isochrone potential. See Section 3.5.2 in\n Binney & Tremaine (2008), and be aware of the errata entry for\n Eq. 3.225.\n\n This transformation is analytic and can be used as a \"toy potential\"\n in the Sanders & Binney (2014) formalism for computing action-angle\n coordinates in any potential.\n\n .. note::\n\n This function is included as a method of the\n :class:`~gala.potential.IsochronePotential` and it is recommended\n to call :meth:`~gala.potential.IsochronePotential.phase_space()`\n instead.\n\n Parameters\n ----------\n w : :class:`gala.dynamics.PhaseSpacePosition`, :class:`gala.dynamics.Orbit`\n potential : :class:`gala.potential.IsochronePotential`, dict\n An instance of the potential to use for computing the transformation\n to angle-action coordinates. Or, a dictionary of parameters used to\n define an :class:`gala.potential.IsochronePotential` instance.\n\n Returns\n -------\n actions : :class:`numpy.ndarray`\n An array of actions computed from the input positions and velocities.\n angles : :class:`numpy.ndarray`\n An array of angles computed from the input positions and velocities.\n freqs : :class:`numpy.ndarray`\n An array of frequencies computed from the input positions and velocities.\n " ]
Please provide a description of the function:def step(self, t, w, dt): # Runge-Kutta Fehlberg formulas (see: Numerical Recipes) F = lambda t, w: self.F(t, w, *self._func_args) K = np.zeros((6,)+w.shape) K[0] = dt * F(t, w) K[1] = dt * F(t + A[1]*dt, w + B[1][0]*K[0]) K[2] = dt * F(t + A[2]*dt, w + B[2][0]*K[0] + B[2][1]*K[1]) K[3] = dt * F(t + A[3]*dt, w + B[3][0]*K[0] + B[3][1]*K[1] + B[3][2]*K[2]) K[4] = dt * F(t + A[4]*dt, w + B[4][0]*K[0] + B[4][1]*K[1] + B[4][2]*K[2] + B[4][3]*K[3]) K[5] = dt * F(t + A[5]*dt, w + B[5][0]*K[0] + B[5][1]*K[1] + B[5][2]*K[2] + B[5][3]*K[3] + B[5][4]*K[4]) # shift dw = np.zeros_like(w) for i in range(6): dw = dw + C[i]*K[i] return w + dw
[ " Step forward the vector w by the given timestep.\n\n Parameters\n ----------\n dt : numeric\n The timestep to move forward.\n " ]
Please provide a description of the function:def check_each_direction(n,angs,ifprint=True): checks = np.array([]) P = np.array([]) if(ifprint): print("\nChecking modes:\n====") for k,i in enumerate(n): N_matrix = np.linalg.norm(i) X = np.dot(angs,i) if(np.abs(np.max(X)-np.min(X))<2.*np.pi): if(ifprint): print("Need a longer integration window for mode ", i) checks=np.append(checks,i) P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X)))) elif(np.abs(np.max(X)-np.min(X))/len(X)>np.pi): if(ifprint): print("Need a finer sampling for mode ", i) checks=np.append(checks,i) P = np.append(P,(2.*np.pi-np.abs(np.max(X)-np.min(X)))) if(ifprint): print("====\n") return checks,P
[ " returns a list of the index of elements of n which do not have adequate\n toy angle coverage. The criterion is that we must have at least one sample\n in each Nyquist box when we project the toy angles along the vector n " ]
Please provide a description of the function:def solver(AA, N_max, symNx = 2, throw_out_modes=False): # Find all integer component n_vectors which lie within sphere of radius N_max # Here we have assumed that the potential is symmetric x->-x, y->-y, z->-z # This can be relaxed by changing symN to 1 # Additionally due to time reversal symmetry S_n = -S_-n so we only consider # "half" of the n-vector-space angs = unroll_angles(AA.T[3:].T,np.ones(3)) symNz = 2 NNx = range(-N_max, N_max+1, symNx) NNy = range(-N_max, N_max+1, symNz) NNz = range(-N_max, N_max+1, symNz) n_vectors = np.array([[i,j,k] for (i,j,k) in product(NNx,NNy,NNz) if(not(i==0 and j==0 and k==0) # exclude zero vector and (k>0 # northern hemisphere or (k==0 and j>0) # half of x-y plane or (k==0 and j==0 and i>0)) # half of x axis and np.sqrt(i*i+j*j+k*k)<=N_max)]) # inside sphere xxx = check_each_direction(n_vectors,angs) if(throw_out_modes): n_vectors = np.delete(n_vectors,check_each_direction(n_vectors,angs),axis=0) n = len(n_vectors)+3 b = np.zeros(shape=(n, )) a = np.zeros(shape=(n,n)) a[:3,:3]=len(AA)*np.identity(3) for i in AA: a[:3,3:]+=2.*n_vectors.T[:3]*np.cos(np.dot(n_vectors,i[3:])) a[3:,3:]+=4.*np.dot(n_vectors,n_vectors.T)*np.outer(np.cos(np.dot(n_vectors,i[3:])),np.cos(np.dot(n_vectors,i[3:]))) b[:3]+=i[:3] b[3:]+=2.*np.dot(n_vectors,i[:3])*np.cos(np.dot(n_vectors,i[3:])) a[3:,:3]=a[:3,3:].T return np.array(solve(a,b)), n_vectors
[ " Constructs the matrix A and the vector b from a timeseries of toy\n action-angles AA to solve for the vector x = (J_0,J_1,J_2,S...) where\n x contains all Fourier components of the generating function with |n|<N_max " ]
Please provide a description of the function:def unroll_angles(A,sign): n = np.array([0,0,0]) P = np.zeros(np.shape(A)) P[0]=A[0] for i in range(1,len(A)): n = n+((A[i]-A[i-1]+0.5*sign*np.pi)*sign<0)*np.ones(3)*2.*np.pi P[i] = A[i]+sign*n return P
[ " Unrolls the angles, A, so they increase continuously " ]
Please provide a description of the function:def angle_solver(AA, timeseries, N_max, sign, symNx = 2, throw_out_modes=False): # First unroll angles angs = unroll_angles(AA.T[3:].T,sign) # Same considerations as above symNz = 2 NNx = range(-N_max, N_max+1, symNx) NNy = range(-N_max, N_max+1, symNz) NNz = range(-N_max, N_max+1, symNz) n_vectors = np.array([[i,j,k] for (i,j,k) in product(NNx,NNy,NNz) if(not(i==0 and j==0 and k==0) # exclude zero vector and (k>0 # northern hemisphere or (k==0 and j>0) # half of x-y plane or (k==0 and j==0 and i>0)) # half of x axis and np.sqrt(i*i+j*j+k*k)<=N_max # inside sphere )]) if(throw_out_modes): n_vectors = np.delete(n_vectors,check_each_direction(n_vectors,angs),axis=0) nv = len(n_vectors) n = 3*nv+6 b = np.zeros(shape=(n, )) a = np.zeros(shape=(n,n)) a[:3,:3]=len(AA)*np.identity(3) a[:3,3:6]=np.sum(timeseries)*np.identity(3) a[3:6,:3]=a[:3,3:6] a[3:6,3:6]=np.sum(timeseries*timeseries)*np.identity(3) for i,j in zip(angs,timeseries): a[6:6+nv,0]+=-2.*np.sin(np.dot(n_vectors,i)) a[6:6+nv,3]+=-2.*j*np.sin(np.dot(n_vectors,i)) a[6:6+nv,6:6+nv]+=4.*np.outer(np.sin(np.dot(n_vectors,i)),np.sin(np.dot(n_vectors,i))) b[:3]+=i b[3:6]+=j*i b[6:6+nv]+=-2.*i[0]*np.sin(np.dot(n_vectors,i)) b[6+nv:6+2*nv]+=-2.*i[1]*np.sin(np.dot(n_vectors,i)) b[6+2*nv:6+3*nv]+=-2.*i[2]*np.sin(np.dot(n_vectors,i)) a[6+nv:6+2*nv,1]=a[6:6+nv,0] a[6+2*nv:6+3*nv,2]=a[6:6+nv,0] a[6+nv:6+2*nv,4]=a[6:6+nv,3] a[6+2*nv:6+3*nv,5]=a[6:6+nv,3] a[6+nv:6+2*nv,6+nv:6+2*nv]=a[6:6+nv,6:6+nv] a[6+2*nv:6+3*nv,6+2*nv:6+3*nv]=a[6:6+nv,6:6+nv] a[:6,:]=a[:,:6].T return np.array(solve(a,b))
[ " Constructs the matrix A and the vector b from a timeseries of toy\n action-angles AA to solve for the vector x = (theta_0,theta_1,theta_2,omega_1,\n omega_2,omega_3, dSdx..., dSdy..., dSdz...) where x contains all derivatives\n of the Fourier components of the generating function with |n| < N_max " ]
Please provide a description of the function:def compute_coeffs(density_func, nmax, lmax, M, r_s, args=(), skip_odd=False, skip_even=False, skip_m=False, S_only=False, progress=False, **nquad_opts): from gala._cconfig import GSL_ENABLED if not GSL_ENABLED: raise ValueError("Gala was compiled without GSL and so this function " "will not work. See the gala documentation for more " "information about installing and using GSL with " "gala: http://gala.adrian.pw/en/latest/install.html") lmin = 0 lstride = 1 if skip_odd or skip_even: lstride = 2 if skip_even: lmin = 1 Snlm = np.zeros((nmax+1, lmax+1, lmax+1)) Snlm_e = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm_e = np.zeros((nmax+1, lmax+1, lmax+1)) nquad_opts.setdefault('limit', 256) nquad_opts.setdefault('epsrel', 1E-10) limits = [[0, 2*np.pi], # phi [-1, 1.], # X (cos(theta)) [-1, 1.]] # xsi nlms = [] for n in range(nmax+1): for l in range(lmin, lmax+1, lstride): for m in range(l+1): if skip_m and m > 0: continue nlms.append((n, l, m)) if progress: try: from tqdm import tqdm except ImportError as e: raise ImportError('tqdm is not installed - you can install it ' 'with `pip install tqdm`.\n' + str(e)) iterfunc = tqdm else: iterfunc = lambda x: x for n, l, m in iterfunc(nlms): Snlm[n, l, m], Snlm_e[n, l, m] = si.nquad( Snlm_integrand, ranges=limits, args=(density_func, n, l, m, M, r_s, args), opts=nquad_opts) if not S_only: Tnlm[n, l, m], Tnlm_e[n, l, m] = si.nquad( Tnlm_integrand, ranges=limits, args=(density_func, n, l, m, M, r_s, args), opts=nquad_opts) return (Snlm, Snlm_e), (Tnlm, Tnlm_e)
[ "\n Compute the expansion coefficients for representing the input density function using a basis\n function expansion.\n\n Computing the coefficients involves computing triple integrals which are computationally\n expensive. For an example of how to parallelize the computation of the coefficients, see\n ``examples/parallel_compute_Anlm.py``.\n\n Parameters\n ----------\n density_func : function, callable\n A function or callable object that evaluates the density at a given position. The call\n format must be of the form: ``density_func(x, y, z, M, r_s, args)`` where ``x,y,z`` are\n cartesian coordinates, ``M`` is a scale mass, ``r_s`` a scale radius, and ``args`` is an\n iterable containing any other arguments needed by the density function.\n nmax : int\n Maximum value of ``n`` for the radial expansion.\n lmax : int\n Maximum value of ``l`` for the spherical harmonics.\n M : numeric\n Scale mass.\n r_s : numeric\n Scale radius.\n args : iterable (optional)\n A list or iterable of any other arguments needed by the density\n function.\n skip_odd : bool (optional)\n Skip the odd terms in the angular portion of the expansion. For example, only\n take :math:`l=0,2,4,...`\n skip_even : bool (optional)\n Skip the even terms in the angular portion of the expansion. For example, only\n take :math:`l=1,3,5,...`\n skip_m : bool (optional)\n Ignore terms with :math:`m > 0`.\n S_only : bool (optional)\n Only compute the S coefficients.\n progress : bool (optional)\n If ``tqdm`` is installed, display a progress bar.\n **nquad_opts\n Any additional keyword arguments are passed through to\n `~scipy.integrate.nquad` as options, `opts`.\n\n Returns\n -------\n Snlm : float, `~numpy.ndarray`\n The value of the cosine expansion coefficient.\n Snlm_err : , `~numpy.ndarray`\n An estimate of the uncertainty in the coefficient value (from `~scipy.integrate.nquad`).\n Tnlm : , `~numpy.ndarray`\n The value of the sine expansion coefficient.\n Tnlm_err : , `~numpy.ndarray`\n An estimate of the uncertainty in the coefficient value. (from `~scipy.integrate.nquad`).\n\n " ]
Please provide a description of the function:def compute_coeffs_discrete(xyz, mass, nmax, lmax, r_s, skip_odd=False, skip_even=False, skip_m=False, compute_var=False): lmin = 0 lstride = 1 if skip_odd or skip_even: lstride = 2 if skip_even: lmin = 1 Snlm = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm = np.zeros((nmax+1, lmax+1, lmax+1)) if compute_var: Snlm_var = np.zeros((nmax+1, lmax+1, lmax+1)) Tnlm_var = np.zeros((nmax+1, lmax+1, lmax+1)) # positions and masses of point masses xyz = np.ascontiguousarray(np.atleast_2d(xyz)) mass = np.ascontiguousarray(np.atleast_1d(mass)) r = np.sqrt(np.sum(xyz**2, axis=-1)) s = r / r_s phi = np.arctan2(xyz[:,1], xyz[:,0]) X = xyz[:,2] / r for n in range(nmax+1): for l in range(lmin, lmax+1, lstride): for m in range(l+1): if skip_m and m > 0: continue # logger.debug("Computing coefficients (n,l,m)=({},{},{})".format(n,l,m)) Snlm[n,l,m], Tnlm[n,l,m] = STnlm_discrete(s, phi, X, mass, n, l, m) if compute_var: Snlm_var[n,l,m], Tnlm_var[n,l,m] = STnlm_var_discrete(s, phi, X, mass, n, l, m) if compute_var: return (Snlm,Snlm_var), (Tnlm,Tnlm_var) else: return Snlm, Tnlm
[ "\n Compute the expansion coefficients for representing the density distribution of input points\n as a basis function expansion. The points, ``xyz``, are assumed to be samples from the\n density distribution.\n\n Computing the coefficients involves computing triple integrals which are computationally\n expensive. For an example of how to parallelize the computation of the coefficients, see\n ``examples/parallel_compute_Anlm.py``.\n\n Parameters\n ----------\n xyz : array_like\n Samples from the density distribution. Should have shape ``(n_samples,3)``.\n mass : array_like\n Mass of each sample. Should have shape ``(n_samples,)``.\n nmax : int\n Maximum value of ``n`` for the radial expansion.\n lmax : int\n Maximum value of ``l`` for the spherical harmonics.\n r_s : numeric\n Scale radius.\n skip_odd : bool (optional)\n Skip the odd terms in the angular portion of the expansion. For example, only\n take :math:`l=0,2,4,...`\n skip_even : bool (optional)\n Skip the even terms in the angular portion of the expansion. For example, only\n take :math:`l=1,3,5,...`\n skip_m : bool (optional)\n Ignore terms with :math:`m > 0`.\n compute_var : bool (optional)\n Also compute the variances of the coefficients. This does not compute the full covariance\n matrix of the coefficients, just the individual variances.\n TODO: separate function to compute full covariance matrix?\n\n Returns\n -------\n Snlm : float\n The value of the cosine expansion coefficient.\n Tnlm : float\n The value of the sine expansion coefficient.\n\n " ]
Please provide a description of the function:def integrate_orbit(self, **time_spec): # Prepare the initial conditions pos = self.w0.xyz.decompose(self.units).value vel = self.w0.v_xyz.decompose(self.units).value w0 = np.ascontiguousarray(np.vstack((pos, vel)).T) # Prepare the time-stepping array t = parse_time_specification(self.units, **time_spec) ws = _direct_nbody_dop853(w0, t, self._ext_ham, self.particle_potentials) pos = np.rollaxis(np.array(ws[..., :3]), axis=2) vel = np.rollaxis(np.array(ws[..., 3:]), axis=2) orbits = Orbit( pos=pos * self.units['length'], vel=vel * self.units['length'] / self.units['time'], t=t * self.units['time']) return orbits
[ "\n Integrate the initial conditions in the combined external potential\n plus N-body forces.\n\n This integration uses the `~gala.integrate.DOPRI853Integrator`.\n\n Parameters\n ----------\n **time_spec\n Specification of how long to integrate. See documentation\n for `~gala.integrate.parse_time_specification`.\n\n Returns\n -------\n orbit : `~gala.dynamics.Orbit`\n The orbits of the particles.\n\n " ]
Please provide a description of the function:def mock_stream(hamiltonian, prog_orbit, prog_mass, k_mean, k_disp, release_every=1, Integrator=DOPRI853Integrator, Integrator_kwargs=dict(), snapshot_filename=None, output_every=1, seed=None): if isinstance(hamiltonian, CPotentialBase): warnings.warn("This function now expects a `Hamiltonian` instance " "instead of a `PotentialBase` subclass instance. If you " "are using a static reference frame, you just need to " "pass your potential object in to the Hamiltonian " "constructor to use, e.g., Hamiltonian(potential).", DeprecationWarning) hamiltonian = Hamiltonian(hamiltonian) # ------------------------------------------------------------------------ # Some initial checks to short-circuit if input is bad if Integrator not in [LeapfrogIntegrator, DOPRI853Integrator]: raise ValueError("Only Leapfrog and dop853 integration is supported for" " generating mock streams.") if not isinstance(hamiltonian, Hamiltonian) or not hamiltonian.c_enabled: raise TypeError("Input potential must be a CPotentialBase subclass.") if not isinstance(prog_orbit, Orbit): raise TypeError("Progenitor orbit must be an Orbit subclass.") if snapshot_filename is not None and Integrator != DOPRI853Integrator: raise ValueError("If saving snapshots, must use the DOP853Integrator.") k_mean = np.atleast_1d(k_mean) k_disp = np.atleast_1d(k_disp) if k_mean.ndim > 1: assert k_mean.shape[0] == prog_orbit.t.size assert k_disp.shape[0] == prog_orbit.t.size # ------------------------------------------------------------------------ if prog_orbit.t[1] < prog_orbit.t[0]: raise ValueError("Progenitor orbit goes backwards in time. Streams can " "only be generated on orbits that run forwards. Hint: " "you can reverse the orbit with prog_orbit[::-1], but " "make sure the array of k_mean values is ordered " "correctly.") c_w = np.squeeze(prog_orbit.w(hamiltonian.units)).T # transpose for Cython funcs prog_w = np.ascontiguousarray(c_w) prog_t = np.ascontiguousarray(prog_orbit.t.decompose(hamiltonian.units).value) if not hasattr(prog_mass, 'unit'): prog_mass = prog_mass * hamiltonian.units['mass'] if not prog_mass.isscalar: if len(prog_mass) != prog_orbit.ntimes: raise ValueError("If passing in an array of progenitor masses, it " "must have the same length as the number of " "timesteps in the input orbit.") prog_mass = prog_mass.decompose(hamiltonian.units).value if Integrator == LeapfrogIntegrator: stream_w = _mock_stream_leapfrog(hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) elif Integrator == DOPRI853Integrator: if snapshot_filename is not None: if os.path.exists(snapshot_filename): raise IOError("Mockstream save file '{}' already exists.") import h5py _mock_stream_animate(snapshot_filename, hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, output_every=output_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) with h5py.File(str(snapshot_filename), 'a') as h5f: h5f['pos'].attrs['unit'] = str(hamiltonian.units['length']) h5f['vel'].attrs['unit'] = str(hamiltonian.units['length']/hamiltonian.units['time']) h5f['t'].attrs['unit'] = str(hamiltonian.units['time']) return None else: stream_w = _mock_stream_dop853(hamiltonian, t=prog_t, prog_w=prog_w, release_every=release_every, _k_mean=k_mean, _k_disp=k_disp, G=hamiltonian.potential.G, _prog_mass=prog_mass, seed=seed, **Integrator_kwargs) else: raise RuntimeError("Should never get here...") return PhaseSpacePosition.from_w(w=stream_w.T, units=hamiltonian.units)
[ "\n Generate a mock stellar stream in the specified potential with a\n progenitor system that ends up at the specified position.\n\n Parameters\n ----------\n hamiltonian : `~gala.potential.Hamiltonian`\n The system Hamiltonian.\n prog_orbit : `~gala.dynamics.Orbit`\n The orbit of the progenitor system.\n prog_mass : numeric, array_like\n A single mass or an array of masses if the progenitor mass evolves\n with time.\n k_mean : `numpy.ndarray`\n Array of mean :math:`k` values (see Fardal et al. 2015). These are used\n to determine the exact prescription for generating the mock stream. The\n components are for: :math:`(R,\\phi,z,v_R,v_\\phi,v_z)`. If 1D, assumed\n constant in time. If 2D, time axis is axis 0.\n k_disp : `numpy.ndarray`\n Array of :math:`k` value dispersions (see Fardal et al. 2015). These are\n used to determine the exact prescription for generating the mock stream.\n The components are for: :math:`(R,\\phi,z,v_R,v_\\phi,v_z)`. If 1D,\n assumed constant in time. If 2D, time axis is axis 0.\n release_every : int (optional)\n Release particles at the Lagrange points every X timesteps.\n Integrator : `~gala.integrate.Integrator` (optional)\n Integrator to use.\n Integrator_kwargs : dict (optional)\n Any extra keyword argumets to pass to the integrator function.\n snapshot_filename : str (optional)\n Filename to save all incremental snapshots of particle positions and\n velocities. Warning: this can make very large files if you are not\n careful!\n output_every : int (optional)\n If outputing snapshots (i.e., if snapshot_filename is specified), this\n controls how often to output a snapshot.\n seed : int (optional)\n A random number seed for initializing the particle positions.\n\n Returns\n -------\n stream : `~gala.dynamics.PhaseSpacePosition`\n\n " ]
Please provide a description of the function:def streakline_stream(hamiltonian, prog_orbit, prog_mass, release_every=1, Integrator=DOPRI853Integrator, Integrator_kwargs=dict(), snapshot_filename=None, output_every=1, seed=None): k_mean = np.zeros(6) k_disp = np.zeros(6) k_mean[0] = 1. # R k_disp[0] = 0. k_mean[1] = 0. # phi k_disp[1] = 0. k_mean[2] = 0. # z k_disp[2] = 0. k_mean[3] = 0. # vR k_disp[3] = 0. k_mean[4] = 1. # vt k_disp[4] = 0. k_mean[5] = 0. # vz k_disp[5] = 0. return mock_stream(hamiltonian=hamiltonian, prog_orbit=prog_orbit, prog_mass=prog_mass, k_mean=k_mean, k_disp=k_disp, release_every=release_every, Integrator=Integrator, Integrator_kwargs=Integrator_kwargs, snapshot_filename=snapshot_filename, output_every=output_every, seed=seed)
[ "\n Generate a mock stellar stream in the specified potential with a\n progenitor system that ends up at the specified position.\n\n This uses the Streakline method from Kuepper et al. (2012).\n\n Parameters\n ----------\n hamiltonian : `~gala.potential.Hamiltonian`\n The system Hamiltonian.\n prog_orbit : `~gala.dynamics.Orbit`\n The orbit of the progenitor system.\n prog_mass : numeric, array_like\n A single mass or an array of masses if the progenitor mass evolves\n with time.\n release_every : int (optional)\n Release particles at the Lagrange points every X timesteps.\n Integrator : `~gala.integrate.Integrator` (optional)\n Integrator to use.\n Integrator_kwargs : dict (optional)\n Any extra keyword argumets to pass to the integrator function.\n snapshot_filename : str (optional)\n Filename to save all incremental snapshots of particle positions and\n velocities. Warning: this can make very large files if you are not\n careful!\n output_every : int (optional)\n If outputing snapshots (i.e., if snapshot_filename is specified), this\n controls how often to output a snapshot.\n seed : int (optional)\n A random number seed for initializing the particle positions.\n\n Returns\n -------\n stream : `~gala.dynamics.PhaseSpacePosition`\n\n " ]
Please provide a description of the function:def dissolved_fardal_stream(hamiltonian, prog_orbit, prog_mass, t_disrupt, release_every=1, Integrator=DOPRI853Integrator, Integrator_kwargs=dict(), snapshot_filename=None, output_every=1, seed=None): try: # the time index closest to when the disruption happens t = prog_orbit.t except AttributeError: raise TypeError("Input progenitor orbit must be an Orbit subclass instance.") disrupt_ix = np.abs(t - t_disrupt).argmin() k_mean = np.zeros((t.size, 6)) k_disp = np.zeros((t.size, 6)) k_mean[:, 0] = 2. # R k_mean[disrupt_ix:, 0] = 0. k_disp[:, 0] = 0.5 k_mean[:, 1] = 0. # phi k_disp[:, 1] = 0. k_mean[:, 2] = 0. # z k_disp[:, 2] = 0.5 k_mean[:, 3] = 0. # vR k_disp[:, 3] = 0. k_mean[:, 4] = 0.3 # vt k_disp[:, 4] = 0.5 k_mean[:, 5] = 0. # vz k_disp[:, 5] = 0.5 return mock_stream(hamiltonian=hamiltonian, prog_orbit=prog_orbit, prog_mass=prog_mass, k_mean=k_mean, k_disp=k_disp, release_every=release_every, Integrator=Integrator, Integrator_kwargs=Integrator_kwargs, snapshot_filename=snapshot_filename, output_every=output_every, seed=seed)
[ "\n Generate a mock stellar stream in the specified potential with a\n progenitor system that ends up at the specified position.\n\n This uses the prescription from Fardal et al. (2015), but at a specified\n time the progenitor completely dissolves and the radial offset of the\n tidal radius is reduced to 0 at fixed dispersion.\n\n Parameters\n ----------\n hamiltonian : `~gala.potential.Hamiltonian`\n The system Hamiltonian.\n prog_orbit : `~gala.dynamics.Orbit`\n The orbit of the progenitor system.\n prog_mass : numeric, array_like\n A single mass or an array of masses if the progenitor mass evolves\n with time.\n t_disrupt : numeric\n The time that the progenitor completely disrupts.\n release_every : int (optional)\n Release particles at the Lagrange points every X timesteps.\n Integrator : `~gala.integrate.Integrator` (optional)\n Integrator to use.\n Integrator_kwargs : dict (optional)\n Any extra keyword argumets to pass to the integrator function.\n snapshot_filename : str (optional)\n Filename to save all incremental snapshots of particle positions and\n velocities. Warning: this can make very large files if you are not\n careful!\n output_every : int (optional)\n If outputing snapshots (i.e., if snapshot_filename is specified), this\n controls how often to output a snapshot.\n seed : int (optional)\n A random number seed for initializing the particle positions.\n\n Returns\n -------\n stream : `~gala.dynamics.PhaseSpacePosition`\n\n " ]
Please provide a description of the function:def vgsr_to_vhel(coordinate, vgsr, vsun=None): if vsun is None: vsun = coord.Galactocentric.galcen_v_sun.to_cartesian().xyz return vgsr - _get_vproj(coordinate, vsun)
[ "\n Convert a radial velocity in the Galactic standard of rest (GSR) to\n a barycentric radial velocity.\n\n Parameters\n ----------\n coordinate : :class:`~astropy.coordinates.SkyCoord`\n An Astropy SkyCoord object or anything object that can be passed\n to the SkyCoord initializer.\n vgsr : :class:`~astropy.units.Quantity`\n GSR line-of-sight velocity.\n vsun : :class:`~astropy.units.Quantity`\n Full-space velocity of the sun in a Galactocentric frame. By default,\n uses the value assumed by Astropy in\n `~astropy.coordinates.Galactocentric`.\n\n Returns\n -------\n vhel : :class:`~astropy.units.Quantity`\n Radial velocity in a barycentric rest frame.\n\n " ]
Please provide a description of the function:def vhel_to_vgsr(coordinate, vhel, vsun): if vsun is None: vsun = coord.Galactocentric.galcen_v_sun.to_cartesian().xyz return vhel + _get_vproj(coordinate, vsun)
[ "\n Convert a velocity from a heliocentric radial velocity to\n the Galactic standard of rest (GSR).\n\n Parameters\n ----------\n coordinate : :class:`~astropy.coordinates.SkyCoord`\n An Astropy SkyCoord object or anything object that can be passed\n to the SkyCoord initializer.\n vhel : :class:`~astropy.units.Quantity`\n Barycentric line-of-sight velocity.\n vsun : :class:`~astropy.units.Quantity`\n Full-space velocity of the sun in a Galactocentric frame. By default,\n uses the value assumed by Astropy in\n `~astropy.coordinates.Galactocentric`.\n\n Returns\n -------\n vgsr : :class:`~astropy.units.Quantity`\n Radial velocity in a galactocentric rest frame.\n\n " ]
Please provide a description of the function:def _apply(self, method, *args, **kwargs): if callable(method): apply_method = lambda array: method(array, *args, **kwargs) else: apply_method = operator.methodcaller(method, *args, **kwargs) return self.__class__([apply_method(getattr(self, component)) for component in self.components], copy=False)
[ "Create a new representation with ``method`` applied to the arrays.\n\n In typical usage, the method is any of the shape-changing methods for\n `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those\n picking particular elements (``__getitem__``, ``take``, etc.), which\n are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be\n applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for\n `~astropy.coordinates.CartesianRepresentation`), with the results used\n to create a new instance.\n\n Internally, it is also used to apply functions to the components\n (in particular, `~numpy.broadcast_to`).\n\n Parameters\n ----------\n method : str or callable\n If str, it is the name of a method that is applied to the internal\n ``components``. If callable, the function is applied.\n args : tuple\n Any positional arguments for ``method``.\n kwargs : dict\n Any keyword arguments for ``method``.\n " ]
Please provide a description of the function:def get_xyz(self, xyz_axis=0): # Add new axis in x, y, z so one can concatenate them around it. # NOTE: just use np.stack once our minimum numpy version is 1.10. result_ndim = self.ndim + 1 if not -result_ndim <= xyz_axis < result_ndim: raise IndexError('xyz_axis {0} out of bounds [-{1}, {1})' .format(xyz_axis, result_ndim)) if xyz_axis < 0: xyz_axis += result_ndim # Get components to the same units (very fast for identical units) # since np.concatenate cannot deal with quantity. unit = self._x1.unit sh = self.shape sh = sh[:xyz_axis] + (1,) + sh[xyz_axis:] components = [getattr(self, '_'+name).reshape(sh).to(unit).value for name in self.attr_classes] xs_value = np.concatenate(components, axis=xyz_axis) return u.Quantity(xs_value, unit=unit, copy=False)
[ "Return a vector array of the x, y, and z coordinates.\n\n Parameters\n ----------\n xyz_axis : int, optional\n The axis in the final array along which the x, y, z components\n should be stored (default: 0).\n\n Returns\n -------\n xs : `~astropy.units.Quantity`\n With dimension 3 along ``xyz_axis``.\n " ]
Please provide a description of the function:def _get_c_valid_arr(self, x): orig_shape = x.shape x = np.ascontiguousarray(x.reshape(orig_shape[0], -1).T) return orig_shape, x
[ "\n Warning! Interpretation of axes is different for C code.\n " ]
Please provide a description of the function:def _validate_prepare_time(self, t, pos_c): if hasattr(t, 'unit'): t = t.decompose(self.units).value if not isiterable(t): t = np.atleast_1d(t) t = np.ascontiguousarray(t.ravel()) if len(t) > 1: if len(t) != pos_c.shape[0]: raise ValueError("If passing in an array of times, it must have a shape " "compatible with the input position(s).") return t
[ "\n Make sure that t is a 1D array and compatible with the C position array.\n " ]
Please provide a description of the function:def get_components(self, which): mappings = self.representation_mappings.get( getattr(self, which).__class__, []) old_to_new = dict() for name in getattr(self, which).components: for m in mappings: if isinstance(m, RegexRepresentationMapping): pattr = re.match(m.repr_name, name) old_to_new[name] = m.new_name.format(*pattr.groups()) elif m.repr_name == name: old_to_new[name] = m.new_name mapping = OrderedDict() for name in getattr(self, which).components: mapping[old_to_new.get(name, name)] = name return mapping
[ "\n Get the component name dictionary for the desired object.\n\n The returned dictionary maps component names on this class to component\n names on the desired object.\n\n Parameters\n ----------\n which : str\n Can either be ``'pos'`` or ``'vel'`` to get the components for the\n position or velocity object.\n " ]
Please provide a description of the function:def represent_as(self, new_pos, new_vel=None): if self.ndim != 3: raise ValueError("Can only change representation for " "ndim=3 instances.") # get the name of the desired representation if isinstance(new_pos, str): pos_name = new_pos else: pos_name = new_pos.get_name() if isinstance(new_vel, str): vel_name = new_vel elif new_vel is None: vel_name = pos_name else: vel_name = new_vel.get_name() Representation = coord.representation.REPRESENTATION_CLASSES[pos_name] Differential = coord.representation.DIFFERENTIAL_CLASSES[vel_name] new_pos = self.pos.represent_as(Representation) new_vel = self.vel.represent_as(Differential, self.pos) return self.__class__(pos=new_pos, vel=new_vel, frame=self.frame)
[ "\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 representation to generate. Must be a class (not an\n instance), or the string name of the representation class.\n new_vel : :class:`~astropy.coordinates.BaseDifferential` (optional)\n Class in which any velocities should be represented. Must be a class\n (not an instance), or the string name of the differential class. If\n None, uses the default differential for the new position class.\n\n Returns\n -------\n new_psp : `gala.dynamics.PhaseSpacePosition`\n " ]
Please provide a description of the function:def to_frame(self, frame, current_frame=None, **kwargs): from ..potential.frame.builtin import transformations as frame_trans if ((inspect.isclass(frame) and issubclass(frame, coord.BaseCoordinateFrame)) or isinstance(frame, coord.BaseCoordinateFrame)): import warnings warnings.warn("This function now expects a " "`gala.potential.FrameBase` instance. To transform to" " an Astropy coordinate frame, use the " "`.to_coord_frame()` method instead.", DeprecationWarning) return self.to_coord_frame(frame=frame, **kwargs) if self.frame is None and current_frame is None: raise ValueError("If no frame was specified when this {} was " "initialized, you must pass the current frame in " "via the current_frame argument to transform to a " "new frame.") elif self.frame is not None and current_frame is None: current_frame = self.frame name1 = current_frame.__class__.__name__.rstrip('Frame').lower() name2 = frame.__class__.__name__.rstrip('Frame').lower() func_name = "{}_to_{}".format(name1, name2) if not hasattr(frame_trans, func_name): raise ValueError("Unsupported frame transformation: {} to {}" .format(current_frame, frame)) else: trans_func = getattr(frame_trans, func_name) pos, vel = trans_func(current_frame, frame, self, **kwargs) return PhaseSpacePosition(pos=pos, vel=vel, frame=frame)
[ "\n Transform to a new reference frame.\n\n Parameters\n ----------\n frame : `~gala.potential.FrameBase`\n The frame to transform to.\n current_frame : `gala.potential.CFrameBase`\n The current frame the phase-space position is in.\n **kwargs\n Any additional arguments are passed through to the individual frame\n transformation functions (see:\n `~gala.potential.frame.builtin.transformations`).\n\n Returns\n -------\n psp : `gala.dynamics.CartesianPhaseSpacePosition`\n The phase-space position in the new reference frame.\n\n " ]
Please provide a description of the function:def to_coord_frame(self, frame, galactocentric_frame=None, **kwargs): if self.ndim != 3: raise ValueError("Can only change representation for " "ndim=3 instances.") if galactocentric_frame is None: galactocentric_frame = coord.Galactocentric() if 'vcirc' in kwargs or 'vlsr' in kwargs: import warnings warnings.warn("Instead of passing in 'vcirc' and 'vlsr', specify " "these parameters to the input Galactocentric frame " "using the `galcen_v_sun` argument.", DeprecationWarning) pos_keys = list(self.pos_components.keys()) vel_keys = list(self.vel_components.keys()) if (getattr(self, pos_keys[0]).unit == u.one or getattr(self, vel_keys[0]).unit == u.one): raise u.UnitConversionError("Position and velocity must have " "dimensioned units to convert to a " "coordinate frame.") # first we need to turn the position into a Galactocentric instance gc_c = galactocentric_frame.realize_frame( self.pos.with_differentials(self.vel)) c = gc_c.transform_to(frame) return c
[ "\n Transform the orbit from Galactocentric, cartesian coordinates to\n Heliocentric coordinates in the specified Astropy coordinate frame.\n\n Parameters\n ----------\n frame : :class:`~astropy.coordinates.BaseCoordinateFrame`\n The class or frame instance specifying the desired output frame.\n For example, :class:`~astropy.coordinates.ICRS`.\n galactocentric_frame : :class:`~astropy.coordinates.Galactocentric`\n This is the assumed frame that the position and velocity of this\n object are in. The ``Galactocentric`` instand should have parameters\n specifying the position and motion of the sun in the Galactocentric\n frame, but no data.\n\n Returns\n -------\n c : :class:`~astropy.coordinates.BaseCoordinateFrame`\n An instantiated coordinate frame containing the positions and\n velocities from this object transformed to the specified coordinate\n frame.\n\n " ]
Please provide a description of the function:def w(self, units=None): if self.ndim == 3: cart = self.cartesian else: cart = self xyz = cart.xyz d_xyz = cart.v_xyz x_unit = xyz.unit v_unit = d_xyz.unit if ((units is None or isinstance(units, DimensionlessUnitSystem)) and (x_unit == u.one and v_unit == u.one)): units = DimensionlessUnitSystem() elif units is None: raise ValueError("A UnitSystem must be provided.") x = xyz.decompose(units).value if x.ndim < 2: x = atleast_2d(x, insert_axis=1) v = d_xyz.decompose(units).value if v.ndim < 2: v = atleast_2d(v, insert_axis=1) return np.vstack((x,v))
[ "\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 -------\n w : `~numpy.ndarray`\n A numpy array of all positions and velocities, without units.\n Will have shape ``(2*ndim,...)``.\n\n " ]
Please provide a description of the function:def to_hdf5(self, f): if isinstance(f, str): import h5py f = h5py.File(f) if self.frame is not None: frame_group = f.create_group('frame') frame_group.attrs['module'] = self.frame.__module__ frame_group.attrs['class'] = self.frame.__class__.__name__ units = [str(x).encode('utf8') for x in self.frame.units.to_dict().values()] frame_group.create_dataset('units', data=units) d = frame_group.create_group('parameters') for k, par in self.frame.parameters.items(): quantity_to_hdf5(d, k, par) cart = self.represent_as('cartesian') quantity_to_hdf5(f, 'pos', cart.xyz) quantity_to_hdf5(f, 'vel', cart.v_xyz) return f
[ "\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): if isinstance(f, str): import h5py f = h5py.File(f) pos = quantity_from_hdf5(f['pos']) vel = quantity_from_hdf5(f['vel']) frame = None if 'frame' in f: g = f['frame'] frame_mod = g.attrs['module'] frame_cls = g.attrs['class'] frame_units = [u.Unit(x.decode('utf-8')) for x in g['units']] if u.dimensionless_unscaled in frame_units: units = DimensionlessUnitSystem() else: units = UnitSystem(*frame_units) pars = dict() for k in g['parameters']: pars[k] = quantity_from_hdf5(g['parameters/'+k]) exec("from {0} import {1}".format(frame_mod, frame_cls)) frame_cls = eval(frame_cls) frame = frame_cls(units=units, **pars) return cls(pos=pos, vel=vel, frame=frame)
[ "\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 energy(self, hamiltonian): r from ..potential import PotentialBase if isinstance(hamiltonian, PotentialBase): from ..potential import Hamiltonian warnings.warn("This function now expects a `Hamiltonian` instance " "instead of a `PotentialBase` subclass instance. If " "you are using a static reference frame, you just " "need to pass your potential object in to the " "Hamiltonian constructor to use, e.g., " "Hamiltonian(potential).", DeprecationWarning) hamiltonian = Hamiltonian(hamiltonian) return hamiltonian(self)
[ "\n The total energy *per unit mass* (e.g., kinetic + potential):\n\n Parameters\n ----------\n hamiltonian : `gala.potential.Hamiltonian`\n The Hamiltonian object to evaluate the energy.\n\n Returns\n -------\n E : :class:`~astropy.units.Quantity`\n The total energy.\n " ]
Please provide a description of the function:def angular_momentum(self): r cart = self.represent_as(coord.CartesianRepresentation) return cart.pos.cross(cart.vel).xyz
[ "\n Compute the angular momentum for the phase-space positions contained\n in this object::\n\n .. math::\n\n \\boldsymbol{{L}} = \\boldsymbol{{q}} \\times \\boldsymbol{{p}}\n\n See :ref:`shape-conventions` for more information about the shapes of\n input and output objects.\n\n Returns\n -------\n L : :class:`~astropy.units.Quantity`\n Array of angular momentum vectors.\n\n Examples\n --------\n\n >>> import numpy as np\n >>> import astropy.units as u\n >>> pos = np.array([1., 0, 0]) * u.au\n >>> vel = np.array([0, 2*np.pi, 0]) * u.au/u.yr\n >>> w = PhaseSpacePosition(pos, vel)\n >>> w.angular_momentum() # doctest: +FLOAT_CMP\n <Quantity [0. ,0. ,6.28318531] AU2 / yr>\n " ]
Please provide a description of the function:def _plot_prepare(self, components, units): # components to plot if components is None: components = self.pos.components n_comps = len(components) # if units not specified, get units from the components if units is not None: if isinstance(units, u.UnitBase): units = [units]*n_comps # global unit elif len(units) != n_comps: raise ValueError('You must specify a unit for each axis, or a ' 'single unit for all axes.') labels = [] x = [] for i,name in enumerate(components): val = getattr(self, name) if units is not None: val = val.to(units[i]) unit = units[i] else: unit = val.unit if val.unit != u.one: uu = unit.to_string(format='latex_inline') unit_str = ' [{}]'.format(uu) else: unit_str = '' # Figure out how to fancy display the component name if name.startswith('d_'): dot = True name = name[2:] else: dot = False if name in _greek_letters: name = r"\{}".format(name) if dot: name = "\dot{{{}}}".format(name) labels.append('${}$'.format(name) + unit_str) x.append(val.value) return x, labels
[ "\n Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting\n routine to plot all projections of the object.\n " ]
Please provide a description of the function:def plot(self, components=None, units=None, auto_aspect=True, **kwargs): try: import matplotlib.pyplot as plt except ImportError: msg = 'matplotlib is required for visualization.' raise ImportError(msg) if components is None: components = self.pos.components x,labels = self._plot_prepare(components=components, units=units) default_kwargs = { 'marker': '.', 'labels': labels, 'plot_function': plt.scatter, 'autolim': False } for k,v in default_kwargs.items(): kwargs[k] = kwargs.get(k, v) fig = plot_projections(x, **kwargs) if self.pos.get_name() == 'cartesian' and \ all([not c.startswith('d_') for c in components]) and \ auto_aspect: for ax in fig.axes: ax.set(aspect='equal', adjustable='datalim') return fig
[ "\n Plot the positions in all projections. This is a wrapper around\n `~gala.dynamics.plot_projections` for fast access and quick\n visualization. All extra keyword arguments are passed to that function\n (the docstring for this function is included here for convenience).\n\n Parameters\n ----------\n components : iterable (optional)\n A list of component names (strings) to plot. By default, this is the\n Cartesian positions ``['x', 'y', 'z']``. To plot Cartesian\n velocities, pass in the velocity component names\n ``['d_x', 'd_y', 'd_z']``.\n units : `~astropy.units.UnitBase`, iterable (optional)\n A single unit or list of units to display the components in.\n auto_aspect : bool (optional)\n Automatically enforce an equal aspect ratio.\n relative_to : bool (optional)\n Plot the values relative to this value or values.\n autolim : bool (optional)\n Automatically set the plot limits to be something sensible.\n axes : array_like (optional)\n Array of matplotlib Axes objects.\n subplots_kwargs : dict (optional)\n Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.\n labels : iterable (optional)\n List or iterable of axis labels as strings. They should correspond to\n the dimensions of the input orbit.\n plot_function : callable (optional)\n The ``matplotlib`` plot function to use. By default, this is\n :func:`~matplotlib.pyplot.scatter`, but can also be, e.g.,\n :func:`~matplotlib.pyplot.plot`.\n **kwargs\n All other keyword arguments are passed to the ``plot_function``.\n You can pass in any of the usual style kwargs like ``color=...``,\n ``marker=...``, etc.\n\n Returns\n -------\n fig : `~matplotlib.Figure`\n\n " ]
Please provide a description of the function:def create_account(self, email_address, password=None, client_id=None, client_secret=None): ''' Create a new account. If the account is created via an app, then Account.oauth will contain the OAuth data that can be used to execute actions on behalf of the newly created account. Args: email_address (str): Email address of the new account to create password (str): [DEPRECATED] This parameter will be ignored client_id (str, optional): Client id of the app to use to create this account client_secret (str, optional): Secret of the app to use to create this account Returns: The new Account object ''' request = self._get_request() params = { 'email_address': email_address } if client_id: params['client_id'] = client_id params['client_secret'] = client_secret response = request.post(self.ACCOUNT_CREATE_URL, params) if 'oauth_data' in response: response["account"]["oauth"] = response['oauth_data'] return response
[]
Please provide a description of the function:def get_account_info(self): ''' Get current account information The information then will be saved in `self.account` so that you can access the information like this: >>> hsclient = HSClient() >>> acct = hsclient.get_account_info() >>> print acct.email_address Returns: An Account object ''' request = self._get_request() response = request.get(self.ACCOUNT_INFO_URL) self.account.json_data = response["account"] return self.account
[]
Please provide a description of the function:def update_account_info(self): ''' Update current account information At the moment you can only update your callback_url. Returns: An Account object ''' request = self._get_request() return request.post(self.ACCOUNT_UPDATE_URL, { 'callback_url': self.account.callback_url })
[]
Please provide a description of the function:def verify_account(self, email_address): ''' Verify whether a HelloSign Account exists Args: email_address (str): Email address for the account to verify Returns: True or False ''' request = self._get_request() resp = request.post(self.ACCOUNT_VERIFY_URL, { 'email_address': email_address }) return ('account' in resp)
[]
Please provide a description of the function:def get_signature_request(self, signature_request_id, ux_version=None): ''' Get a signature request by its ID Args: signature_request_id (str): The id of the SignatureRequest to retrieve ux_version (int): UX version, either 1 (default) or 2. Returns: A SignatureRequest object ''' request = self._get_request() parameters = None if ux_version is not None: parameters = { 'ux_version': ux_version } return request.get(self.SIGNATURE_REQUEST_INFO_URL + signature_request_id, parameters=parameters)
[]
Please provide a description of the function:def get_signature_request_list(self, page=1, ux_version=None): ''' Get a list of SignatureRequest that you can access This includes SignatureRequests you have sent as well as received, but not ones that you have been CCed on. Args: page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1. ux_version (int): UX version, either 1 (default) or 2. Returns: A ResourceList object ''' request = self._get_request() parameters = { "page": page } if ux_version is not None: parameters['ux_version'] = ux_version return request.get(self.SIGNATURE_REQUEST_LIST_URL, parameters=parameters)
[]
Please provide a description of the function:def get_signature_request_file(self, signature_request_id, path_or_file=None, file_type=None, filename=None): ''' Download the PDF copy of the current documents Args: signature_request_id (str): Id of the signature request path_or_file (str or file): A writable File-like object or a full path to save the PDF file to. filename (str): [DEPRECATED] Filename to save the PDF file to. This should be a full path. file_type (str): Type of file to return. Either "pdf" for a single merged document or "zip" for a collection of individual documents. Defaults to "pdf" if not specified. Returns: True if file is downloaded and successfully written, False otherwise. ''' request = self._get_request() url = self.SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id if file_type: url += '?file_type=%s' % file_type return request.get_file(url, path_or_file or filename)
[]
Please provide a description of the function:def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ''' Creates and sends a new SignatureRequest with the submitted documents Creates and sends a new SignatureRequest with the submitted documents. If form_fields_per_document is not specified, a signature page will be affixed where all signers will be required to add their signature, signifying their agreement to all contained documents. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page cc_email_addresses (list, optional): A list of email addresses that should be CC'd form_fields_per_document (str): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) use_text_tags (bool, optional): Use text tags in the provided file(s) to create form fields hide_text_tags (bool, optional): Hide text tag areas metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline(bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' self._check_required_fields({ "signers": signers }, [{ "files": files, "file_urls": file_urls }] ) params = { 'test_mode': test_mode, 'files': files, 'file_urls': file_urls, 'title': title, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'cc_email_addresses': cc_email_addresses, 'form_fields_per_document': form_fields_per_document, 'use_text_tags': use_text_tags, 'hide_text_tags': hide_text_tags, 'metadata': metadata, 'allow_decline': allow_decline } if ux_version is not None: params['ux_version'] = ux_version return self._send_signature_request(**params)
[]
Please provide a description of the function:def send_signature_request_with_template(self, test_mode=False, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False): ''' Creates and sends a new SignatureRequest based off of a Template Creates and sends a new SignatureRequest based off of the Template specified with the template_id parameter. Args: test_mode (bool, optional): Whether this is a test, the signature request will not be legally binding if set to True. Defaults to False. template_id (str): The id of the Template to use when creating the SignatureRequest. Mutually exclusive with template_ids. template_ids (list): The ids of the Templates to use when creating the SignatureRequest. Mutually exclusive with template_id. title (str, optional): The title you want to assign to the SignatureRequest subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. signers (list of dict): A list of signers, which each has the following attributes: role_name (str): Signer role name (str): The name of the signer email_address (str): Email address of the signer pin (str, optional): The 4- to 12-character access code that will secure this signer's signature page ccs (list of str, optional): The email address of the CC filling the role of RoleName. Required when a CC role exists for the Template. Each dict has the following attributes: role_name (str): CC role name email_address (str): CC email address custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` metadata (dict, optional): Metadata to associate with the signature request ux_version (int): UX version, either 1 (default) or 2. allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: A SignatureRequest object ''' self._check_required_fields({ "signers": signers }, [{ "template_id": template_id, "template_ids": template_ids }] ) params = { 'test_mode': test_mode, 'template_id': template_id, 'template_ids': template_ids, 'title': title, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'ccs': ccs, 'custom_fields': custom_fields, 'metadata': metadata, 'allow_decline': allow_decline } if ux_version is not None: params['ux_version'] = ux_version return self._send_signature_request_with_template(**params)
[]
Please provide a description of the function:def remind_signature_request(self, signature_request_id, email_address): ''' Sends an email to the signer reminding them to sign the signature request Sends an email to the signer reminding them to sign the signature request. You cannot send a reminder within 1 hours of the last reminder that was sent. This includes manual AND automatic reminders. Args: signature_request_id (str): The id of the SignatureRequest to send a reminder for email_address (str): The email address of the signer to send a reminder to Returns: A SignatureRequest object ''' request = self._get_request() return request.post(self.SIGNATURE_REQUEST_REMIND_URL + signature_request_id, data={ "email_address": email_address })
[]
Please provide a description of the function:def cancel_signature_request(self, signature_request_id): ''' Cancels a SignatureRequest Cancels a SignatureRequest. After canceling, no one will be able to sign or access the SignatureRequest or its documents. Only the requester can cancel and only before everyone has signed. Args: signing_request_id (str): The id of the signature request to cancel Returns: None ''' request = self._get_request() request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False)
[]
Please provide a description of the function:def get_template(self, template_id): ''' Gets a Template which includes a list of Accounts that can access it Args: template_id (str): The id of the template to retrieve Returns: A Template object ''' request = self._get_request() return request.get(self.TEMPLATE_GET_URL + template_id)
[]
Please provide a description of the function:def get_template_list(self, page=1, page_size=None, account_id=None, query=None): ''' Lists your Templates Args: page (int, optional): Page number of the template List to return. Defaults to 1. page_size (int, optional): Number of objects to be returned per page, must be between 1 and 100, default is 20. account_id (str, optional): Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account. query (str, optional): String that includes search terms and/or fields to be used to filter the Template objects. Returns: A ResourceList object ''' request = self._get_request() parameters = { 'page': page, 'page_size': page_size, 'account_id': account_id, 'query': query } return request.get(self.TEMPLATE_GET_LIST_URL, parameters=parameters)
[]
Please provide a description of the function:def add_user_to_template(self, template_id, account_id=None, email_address=None): ''' Gives the specified Account access to the specified Template Args: template_id (str): The id of the template to give the account access to account_id (str): The id of the account to give access to the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to give access to. Returns: A Template object ''' return self._add_remove_user_template(self.TEMPLATE_ADD_USER_URL, template_id, account_id, email_address)
[]
Please provide a description of the function:def remove_user_from_template(self, template_id, account_id=None, email_address=None): ''' Removes the specified Account's access to the specified Template Args: template_id (str): The id of the template to remove the account's access from. account_id (str): The id of the account to remove access from the template. The account id prevails if both account_id and email_address are provided. email_address (str): The email address of the account to remove access from. Returns: An Template object ''' return self._add_remove_user_template(self.TEMPLATE_REMOVE_USER_URL, template_id, account_id, email_address)
[]
Please provide a description of the function:def delete_template(self, template_id): ''' Deletes the specified template Args: template_id (str): The id of the template to delete Returns: A status code ''' url = self.TEMPLATE_DELETE_URL request = self._get_request() response = request.post(url + template_id, get_json=False) return response
[]
Please provide a description of the function:def get_template_files(self, template_id, filename): ''' Download a PDF copy of a template's original files Args: template_id (str): The id of the template to retrieve. filename (str): Filename to save the PDF file to. This should be a full path. Returns: Returns a PDF file ''' url = self.TEMPLATE_GET_FILES_URL + template_id request = self._get_request() return request.get_file(url, filename)
[]
Please provide a description of the function:def create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Creates an embedded Template draft for further editing. Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to 1. Defaults to 0. client_id (str): Client id of the app you're using to create this draft. files (list of str): The file(s) to use for the template. file_urls (list of str): URLs of the file for HelloSign to use for the template. Use either `files` or `file_urls`, but not both. title (str, optional): The template title subject (str, optional): The default template email subject message (str, optional): The default template email message signer_roles (list of dict): A list of signer roles, each of which has the following attributes: name (str): The role name of the signer that will be displayed when the template is used to create a signature request. order (str, optional): The order in which this signer role is required to sign. cc_roles (list of str, optional): The CC roles that must be assigned when using the template to send a signature request merge_fields (list of dict, optional): The merge fields that can be placed on the template's document(s) by the user claiming the template draft. Each must have the following two parameters: name (str): The name of the merge field. Must be unique. type (str): Can only be "text" or "checkbox". use_preexisting_fields (bool): Whether to use preexisting PDF fields Returns: A Template object specifying the Id of the draft ''' params = { 'test_mode': test_mode, 'client_id': client_id, 'files': files, 'file_urls': file_urls, 'title': title, 'subject': subject, 'message': message, 'signer_roles': signer_roles, 'cc_roles': cc_roles, 'merge_fields': merge_fields, 'use_preexisting_fields': use_preexisting_fields } return self._create_embedded_template_draft(**params)
[]
Please provide a description of the function:def create_team(self, name): ''' Creates a new Team Creates a new Team and makes you a member. You must not currently belong to a team to invoke. Args: name (str): The name of your team Returns: A Team object ''' request = self._get_request() return request.post(self.TEAM_CREATE_URL, {"name": name})
[]
Please provide a description of the function:def update_team_name(self, name): ''' Updates a Team's name Args: name (str): The new name of your team Returns: A Team object ''' request = self._get_request() return request.post(self.TEAM_UPDATE_URL, {"name": name})
[]
Please provide a description of the function:def destroy_team(self): ''' Delete your Team Deletes your Team. Can only be invoked when you have a team with only one member left (yourself). Returns: None ''' request = self._get_request() request.post(url=self.TEAM_DESTROY_URL, get_json=False)
[]
Please provide a description of the function:def add_team_member(self, account_id=None, email_address=None): ''' Add or invite a user to your Team Args: account_id (str): The id of the account of the user to invite to your team. email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object ''' return self._add_remove_team_member(self.TEAM_ADD_MEMBER_URL, email_address, account_id)
[]
Please provide a description of the function:def remove_team_member(self, account_id=None, email_address=None): ''' Remove a user from your Team Args: account_id (str): The id of the account of the user to remove from your team. email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided. Returns: A Team object ''' return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id)
[]
Please provide a description of the function:def get_embedded_object(self, signature_id): ''' Retrieves a embedded signing object Retrieves an embedded object containing a signature url that can be opened in an iFrame. Args: signature_id (str): The id of the signature to get a signature url for Returns: An Embedded object ''' request = self._get_request() return request.get(self.EMBEDDED_OBJECT_GET_URL + signature_id)
[]
Please provide a description of the function:def get_template_edit_url(self, template_id): ''' Retrieves a embedded template for editing Retrieves an embedded object containing a template url that can be opened in an iFrame. Args: template_id (str): The id of the template to get a signature url for Returns: An Embedded object ''' request = self._get_request() return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id)
[]
Please provide a description of the function:def create_unclaimed_draft(self, test_mode=False, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, form_fields_per_document=None, metadata=None, use_preexisting_fields=False, allow_decline=False): ''' Creates a new Draft that can be claimed using the claim URL Creates a new Draft that can be claimed using the claim URL. The first authenticated user to access the URL will claim the Draft and will be shown either the "Sign and send" or the "Request signature" page with the Draft loaded. Subsequent access to the claim URL will result in a 404. If the type is "send_document" then only the file parameter is required. If the type is "request_signature", then the identities of the signers and optionally the location of signing elements on the page are also required. Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to True. Defaults to False. files (list of str): The uploaded file(s) to send for signature file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` draft_type (str): The type of unclaimed draft to create. Use "send_document" to create a claimable file, and "request_signature" for a claimable signature request. If the type is "request_signature" then signers name and email_address are not optional. subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in cc_email_addresses (list of str, optional): A list of email addresses that should be CC'd signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. form_fields_per_document (str, optional): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) metadata (dict, optional): Metadata to associate with the draft use_preexisting_fields (bool): Whether to use preexisting PDF fields allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: An UnclaimedDraft object ''' self._check_required_fields({ 'draft_type': draft_type }, [{ "files": files, "file_urls": file_urls }] ) params = { 'test_mode': test_mode, 'files': files, 'file_urls': file_urls, 'draft_type': draft_type, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'signers': signers, 'cc_email_addresses': cc_email_addresses, 'form_fields_per_document': form_fields_per_document, 'metadata': metadata, 'use_preexisting_fields': use_preexisting_fields, 'allow_decline': allow_decline } return self._create_unclaimed_draft(**params)
[]
Please provide a description of the function:def create_embedded_unclaimed_draft(self, test_mode=False, client_id=None, is_for_embedded_signing=False, requester_email_address=None, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, requesting_redirect_url=None, form_fields_per_document=None, metadata=None, use_preexisting_fields=False, allow_decline=False): ''' Creates a new Draft to be used for embedded requesting Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app used to create the embedded draft. is_for_embedded_signing (bool, optional): Whether this is also for embedded signing. Defaults to False. requester_email_address (str): Email address of the requester. files (list of str): The uploaded file(s) to send for signature. file_urls (list of str): URLs of the file for HelloSign to download to send for signature. Use either `files` or `file_urls` draft_type (str): The type of unclaimed draft to create. Use "send_document" to create a claimable file, and "request_signature" for a claimable signature request. If the type is "request_signature" then signers name and email_address are not optional. subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer order (str, optional): The order the signer is required to sign in cc_email_addresses (list of str, optional): A list of email addresses that should be CC'd signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. requesting_redirect_url (str, optional): The URL you want the signer to be redirected to after the request has been sent. form_fields_per_document (str, optional): The fields that should appear on the document, expressed as a serialized JSON data structure which is a list of lists of the form fields. Please refer to the API reference of HelloSign for more details (https://www.hellosign.com/api/reference#SignatureRequest) metadata (dict, optional): Metadata to associate with the draft use_preexisting_fields (bool): Whether to use preexisting PDF fields allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. Returns: An UnclaimedDraft object ''' self._check_required_fields({ 'client_id': client_id, 'requester_email_address': requester_email_address, 'draft_type': draft_type }, [{ "files": files, "file_urls": file_urls }] ) params = { 'test_mode': test_mode, 'client_id': client_id, 'requester_email_address': requester_email_address, 'is_for_embedded_signing': is_for_embedded_signing, 'files': files, 'file_urls': file_urls, 'draft_type': draft_type, 'subject': subject, 'message': message, 'signing_redirect_url': signing_redirect_url, 'requesting_redirect_url': requesting_redirect_url, 'signers': signers, 'cc_email_addresses': cc_email_addresses, 'form_fields_per_document': form_fields_per_document, 'metadata': metadata, 'use_preexisting_fields': use_preexisting_fields, 'allow_decline': allow_decline } return self._create_unclaimed_draft(**params)
[]
Please provide a description of the function:def create_embedded_unclaimed_draft_with_template(self, test_mode=False, client_id=None, is_for_embedded_signing=False, template_id=None, template_ids=None, requester_email_address=None, title=None, subject=None, message=None, signers=None, ccs=None, signing_redirect_url=None, requesting_redirect_url=None, metadata=None, custom_fields=None, allow_decline=False): ''' Creates a new Draft to be used for embedded requesting Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to True. Defaults to False. client_id (str): Client id of the app you're using to create this draft. Visit our embedded page to learn more about this parameter. template_id (str): The id of the Template to use when creating the Unclaimed Draft. Mutually exclusive with template_ids. template_ids (list of str): The ids of the Templates to use when creating the Unclaimed Draft. Mutually exclusive with template_id. requester_email_address (str): The email address of the user that should be designated as the requester of this draft, if the draft type is "request_signature." title (str, optional): The title you want to assign to the Unclaimed Draft subject (str, optional): The subject in the email that will be sent to the signers message (str, optional): The custom message in the email that will be sent to the signers signers (list of dict): A list of signers, which each has the following attributes: name (str): The name of the signer email_address (str): Email address of the signer ccs (list of str, optional): A list of email addresses that should be CC'd signing_redirect_url (str, optional): The URL you want the signer redirected to after they successfully sign. requesting_redirect_url (str, optional): The URL you want the signer to be redirected to after the request has been sent. is_for_embedded_signing (bool, optional): The request created from this draft will also be signable in embedded mode if set to True. The default is False. metadata (dict, optional): Metadata to associate with the draft. Each request can include up to 10 metadata keys, with key names up to 40 characters long and values up to 500 characters long. custom_fields (list of dict, optional): A list of custom fields. Required when a CustomField exists in the Template. An item of the list should look like this: `{'name: value'}` allow_decline (bool, optional): Allows signers to decline to sign a document if set to 1. Defaults to 0. ''' self._check_required_fields({ "client_id": client_id, "requester_email_address": requester_email_address }, [{ "template_id": template_id, "template_ids": template_ids }] ) params = { 'test_mode': test_mode, 'client_id': client_id, 'is_for_embedded_signing': is_for_embedded_signing, 'template_id': template_id, 'template_ids': template_ids, 'title': title, 'subject': subject, 'message': message, 'requester_email_address': requester_email_address, 'signing_redirect_url': signing_redirect_url, 'requesting_redirect_url': requesting_redirect_url, 'signers': signers, 'ccs': ccs, 'custom_fields': custom_fields, 'metadata': metadata, 'allow_decline': allow_decline } return self._create_embedded_unclaimed_draft_with_template(**params)
[]
Please provide a description of the function:def get_oauth_data(self, code, client_id, client_secret, state): ''' Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of the associated app Returns: A HSAccessTokenAuth object ''' request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "state": state, "code": code, "grant_type": "authorization_code", "client_id": client_id, "client_secret": client_secret }) return HSAccessTokenAuth.from_response(response)
[]
Please provide a description of the function:def refresh_access_token(self, refresh_token): ''' Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token ''' request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "grant_type": "refresh_token", "refresh_token": refresh_token }) self.auth = HSAccessTokenAuth.from_response(response) return self.auth.access_token
[]