Code
stringlengths
103
85.9k
Summary
listlengths
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: 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 : ...
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,...
[ "\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] *...
[ "\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...
[ "\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 sam...
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...
[ "\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 i...
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, v...
[ "\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)``...
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: r...
[ "\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 ...
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...
[ "\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...
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...
[ "\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 ...
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() - ...
[ "\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 integ...
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, ...
[ "\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...
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 s...
[ "\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...
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...
[ "\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/jl...
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_potent...
[ "\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>`_\...
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_ste...
[ "\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 t...
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 r...
[ " 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 ...
[ " 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=...
[ " 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 !=...
[ "\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 ...
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 = PhaseS...
[ "\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 ...
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 is...
[ "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 = galactocen...
[ "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...
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_p...
[ "\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] ...
[ "\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`...
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 t...
[ " 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) ...
[ " 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...
[ "\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]): ...
[ "\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\...
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 ...
[ "\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,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 ...
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...
[ " 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,timeserie...
[ " 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[......
[ "\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 Ret...
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(...
[ "\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 S...
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]) ...
[ " 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(...
[ " 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 ...
[ " 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+...
[ " 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: rais...
[ "\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...
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 ski...
[ "\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...
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) # Prep...
[ "\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...
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(hamiltoni...
[ "\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 th...
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.z...
[ "\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...
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: ...
[ "\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 reduc...
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 ...
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 v...
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__([app...
[ "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 ar...
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_ndi...
[ "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...
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: ...
[ "\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 ...
[ "\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 co...
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 isinstanc...
[ "\n Represent the position and velocity of the orbit in an alternate\n coordinate system. Supports any of the Astropy coordinates\n representation classes.\n\n Parameters\n ----------\n new_pos : :class:`~astropy.coordinates.BaseRepresentation`\n The type of repr...
Please provide a description of the function:def to_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.B...
[ "\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 ...
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: ...
[ "\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 t...
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 isinst...
[ "\n This returns a single array containing the phase-space positions.\n\n Parameters\n ----------\n units : `~gala.units.UnitSystem` (optional)\n The unit system to represent the position and velocity in\n before combining into the full array.\n\n Returns\n ...
Please provide a description of the function:def 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__ ...
[ "\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'...
[ "\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 " ...
[ "\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 ...
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 obj...
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 ...
[ "\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) i...
[ "\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 Para...
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 o...
[]
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() ...
[]
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.ACC...
[]
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 = s...
[]
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 versio...
[]
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: ...
[]
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_f...
[]
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...
[]
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): '...
[]
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 remind...
[]
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 a...
[]
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 ''' reques...
[]
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): ...
[]
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 ac...
[]
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....
[]
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 reques...
[]
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 sho...
[]
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 ...
[]
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 ...
[]
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_U...
[]
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...
[]
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 ...
[]
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 ...
[]
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 sig...
[]
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...
[]
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_decl...
[]
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, ...
[]
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=Non...
[]
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...
[]
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 ne...
[]