def root_poly3(a1, a2, a3): """Roots for a cubic polinomy, x^3 + a1*x^2 + a2*x + a3""" Q = (3 * a2 - a1**2) / 9. L = (9 * a1 * a2 - 27 * a3 - 2 * a1**3) / 54. D = Q**3 + L**2 if D < 0: tita = acos(L / (-Q**3)**0.5) z1 = 2 * (-Q)**0.5 * cos(tita / 3. + 2. * pi / 3) - a1 / 3. z2 = 2 * (-Q)**0.5 * cos(tita / 3. + 4. * pi / 3) - a1 / 3. z3 = 2 * (-Q)**0.5 * cos(tita / 3.) - a1 / 3. z = [z1, z2, z3] else: S1 = cbrt((L + D**0.5)) S2 = cbrt((L - D**0.5)) if D > 0: z = [S1 + S2 - a1 / 3.] else: z1 = cbrt(L) + cbrt(L) - a1 / 3. z2 = -cbrt(L) - a1 / 3. z = [z1, z2] # print z[0]+z[1]+z[2], -a1 # print z[0]*z[1]+z[1]*z[2]+z[2]*z[0], a2 # print z[0]*z[1]*z[2], -a3 z.sort() return z
def equivalent_diameter(target, pore_volume='pore.volume', pore_shape='sphere'): r""" Calculates the diameter of a sphere or edge-length of a cube with same volume as the pore. Parameters ---------- target : OpenPNM Geometry Object The Geometry object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary geometric properties. pore_volume : string The dictionary key containing the pore volume values pore_shape : string The shape of the pore body to assume when back-calculating from volume. Options are 'sphere' (default) or 'cube'. """ from scipy.special import cbrt pore_vols = target[pore_volume] if pore_shape.startswith('sph'): value = cbrt(6 * pore_vols / _np.pi) elif pore_shape.startswith('cub'): value = cbrt(pore_vols) return value
def nonlinear_resonator(f, f_0, Q, Q_e_real, Q_e_imag, a): Q_e = Q_e_real + 1j * Q_e_imag if np.isscalar(f): fmodel = np.linspace(f * 0.9999, f * 1.0001, 1000) scalar = True else: fmodel = f scalar = False y_0 = ((fmodel - f_0) / f_0) * Q y = (y_0 / 3. + (y_0**2 / 9 - 1 / 12) / cbrt(a / 8 + y_0 / 12 + np.sqrt( (y_0**3 / 27 + y_0 / 12 + a / 8)**2 - (y_0**2 / 9 - 1 / 12)**3) + y_0**3 / 27) + cbrt(a / 8 + y_0 / 12 + np.sqrt((y_0**3 / 27 + y_0 / 12 + a / 8)**2 - (y_0**2 / 9 - 1 / 12)**3) + y_0**3 / 27)) x = y / Q s21 = (1 - (Q / Q_e) / (1 + 2j * Q * x)) mask = np.isfinite(s21) if scalar or not np.all(mask): s21_interp_real = np.interp(f, fmodel[mask], s21[mask].real) s21_interp_imag = np.interp(f, fmodel[mask], s21[mask].imag) s21new = s21_interp_real + 1j * s21_interp_imag else: s21new = s21 return s21new
def root_poly3(a1, a2, a3): """Roots for a cubic polinomy, x^3 + a1*x^2 + a2*x + a3""" Q = (3*a2-a1**2)/9. L = (9*a1*a2-27*a3-2*a1**3)/54. D = Q**3+L**2 if D < 0: tita = acos(L/(-Q**3)**0.5) z1 = 2*(-Q)**0.5*cos(tita/3.+2.*pi/3)-a1/3. z2 = 2*(-Q)**0.5*cos(tita/3.+4.*pi/3)-a1/3. z3 = 2*(-Q)**0.5*cos(tita/3.)-a1/3. z = [z1, z2, z3] else: S1 = cbrt((L+D**0.5)) S2 = cbrt((L-D**0.5)) if D > 0: z = [S1+S2-a1/3.] else: z1 = cbrt(L)+cbrt(L)-a1/3. z2 = -cbrt(L)-a1/3. z = [z1, z2] # print z[0]+z[1]+z[2], -a1 # print z[0]*z[1]+z[1]*z[2]+z[2]*z[0], a2 # print z[0]*z[1]*z[2], -a3 z.sort() return z
def bifurcation_s21(params,f): """ Swenson paper: Equation: y = yo + A/(1+4*y**2) """ A = (params['A_mag'].value * np.exp(1j * params['A_phase'].value)) f_0 = params['f_0'].value Q = params['Q'].value Q_e = (params['Q_e_real'].value + 1j * params['Q_e_imag'].value) a = params['a'].value if np.isscalar(f): fmodel = np.linspace(f*0.9999,f*1.0001,1000) scalar = True else: fmodel = f scalar = False y_0 = ((fmodel - f_0)/f_0)*Q y = (y_0/3. + (y_0**2/9 - 1/12)/cbrt(a/8 + y_0/12 + np.sqrt((y_0**3/27 + y_0/12 + a/8)**2 - (y_0**2/9 - 1/12)**3) + y_0**3/27) + cbrt(a/8 + y_0/12 + np.sqrt((y_0**3/27 + y_0/12 + a/8)**2 - (y_0**2/9 - 1/12)**3) + y_0**3/27)) x = y/Q s21 = A*(1 - (Q/Q_e)/(1+2j*Q*x)) msk = np.isfinite(s21) if scalar or not np.all(msk): s21_interp_real = np.interp(f,fmodel[msk],s21[msk].real) s21_interp_imag = np.interp(f,fmodel[msk],s21[msk].imag) s21new = s21_interp_real+1j*s21_interp_imag else: s21new = s21 return s21new*cable_delay(params,f)
def bifurcation_s21(params, f): """ Swenson paper: Equation: y = yo + A/(1+4*y**2) """ A = (params['A_mag'].value * np.exp(1j * params['A_phase'].value)) f_0 = params['f_0'].value Q = params['Q'].value Q_e = (params['Q_e_real'].value + 1j * params['Q_e_imag'].value) a = params['a'].value if np.isscalar(f): fmodel = np.linspace(f * 0.9999, f * 1.0001, 1000) scalar = True else: fmodel = f scalar = False y_0 = ((fmodel - f_0) / f_0) * Q y = (y_0 / 3. + (y_0**2 / 9 - 1 / 12) / cbrt(a / 8 + y_0 / 12 + np.sqrt( (y_0**3 / 27 + y_0 / 12 + a / 8)**2 - (y_0**2 / 9 - 1 / 12)**3) + y_0**3 / 27) + cbrt(a / 8 + y_0 / 12 + np.sqrt((y_0**3 / 27 + y_0 / 12 + a / 8)**2 - (y_0**2 / 9 - 1 / 12)**3) + y_0**3 / 27)) x = y / Q s21 = A * (1 - (Q / Q_e) / (1 + 2j * Q * x)) mask = np.isfinite(s21) if scalar or not np.all(mask): s21_interp_real = np.interp(f, fmodel[mask], s21[mask].real) s21_interp_imag = np.interp(f, fmodel[mask], s21[mask].imag) s21new = s21_interp_real + 1j * s21_interp_imag else: s21new = s21 return s21new * cable_delay(params, f)
def equivalent_diameter(target, pore_volume='pore.volume', pore_shape='sphere'): r""" Calculates the diameter of a sphere or edge-length of a cube with same volume as the pore. Parameters ---------- target : OpenPNM Geometry Object The Geometry object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary geometric properties. pore_volume : string The dictionary key containing the pore volume values pore_shape : string The shape of the pore body to assume when back-calculating from volume. Options are 'sphere' (default) or 'cube'. Returns ------- D : NumPy ndarray Array containing pore diameter values. """ from scipy.special import cbrt pore_vols = target[pore_volume] if pore_shape.startswith('sph'): value = cbrt(6*pore_vols/_np.pi) elif pore_shape.startswith('cub'): value = cbrt(pore_vols) return value
def setUp(self): """Verify environment is setup properly data taken from the fitted params of the sweep 2013-12-03_174822.nc swps[0], swp.atten = 21.0, swp.power_dbm=-51 """ f = np.linspace(82.85, 82.90, 10000) f_0 = 82.881569344696032 A_mag = 0.045359757228080611 A_phase = 0 A = A_mag * np.exp(1j * A_phase) Q = 32253.035141948105 Q_e_real = 120982.33962292993 Q_e_imag = 51324.601136160083 Q_e = Q_e_real + 1j * Q_e_imag delay = 0.05255962136531532 phi = -1.3313606721103854 f_min = f[0] a = 0.56495480690974931 self.Q_i = (Q ** -1 - np.real(Q_e ** -1)) ** -1 y_0 = ((f - f_0) / f_0) * Q y = ( y_0 / 3.0 + (y_0 ** 2 / 9 - 1 / 12) / cbrt( a / 8 + y_0 / 12 + np.sqrt((y_0 ** 3 / 27 + y_0 / 12 + a / 8) ** 2 - (y_0 ** 2 / 9 - 1 / 12) ** 3) + y_0 ** 3 / 27 ) + cbrt( a / 8 + y_0 / 12 + np.sqrt((y_0 ** 3 / 27 + y_0 / 12 + a / 8) ** 2 - (y_0 ** 2 / 9 - 1 / 12) ** 3) + y_0 ** 3 / 27 ) ) x = y / Q s21 = A * (1 - (Q / Q_e) / (1 + 2j * Q * x)) msk = np.isfinite(s21) if not np.all(msk): s21_interp_real = np.interp(f, f[msk], s21[msk].real) s21_interp_imag = np.interp(f, f[msk], s21[msk].imag) s21new = s21_interp_real + 1j * s21_interp_imag else: s21new = s21 cable_delay = np.exp(1j * (-2 * np.pi * (f - f_min) * delay + phi)) bifurcation = s21new * cable_delay self.f_0 = f_0 self.f = f self.Q = Q self.bifurcation = bifurcation self.res = resonator.Resonator( self.f, self.bifurcation, model=khalil.bifurcation_s21, guess=khalil.bifurcation_guess )
def _distort_tsai(self, metric_image_coord): """ Distort centered metric image coordinates following Tsai model. See: Devernay, Frederic, and Olivier Faugeras. "Straight lines have to be straight." Machine vision and applications 13.1 (2001): 14-24. Section 2.1. (only for illustration, the formulas didn't work for me) http://www.cvg.rdg.ac.uk/PETS2009/sample.zip :CameraModel.cpp:CameraModel::undistortedToDistortedSensorCoord Analytical inverse of the undistort_tsai() function. :param metric_image_coord: centered metric image coordinates (metric image coordinate = image_xy * f / z) :type metric_image_coord: numpy.ndarray, shape=(2, n) :return: distorted centered metric image coordinates :rtype: numpy.ndarray, shape=(2, n) """ assert metric_image_coord.shape[0] == 2 x = metric_image_coord[0, :] # vector y = metric_image_coord[1, :] # vector r_u = np.sqrt(x**2 + y**2) # vector c = 1.0 / self.tsai_kappa # scalar d = -c * r_u # vector # solve polynomial of 3rd degree for r_distorted using Cardan method: # https://proofwiki.org/wiki/Cardano%27s_Formula # r_distorted ** 3 + c * r_distorted + d = 0 q = c / 3. # scalar r = -d / 2. # vector delta = q**3 + r**2 # polynomial discriminant, vector positive_mask = delta >= 0 r_distorted = np.zeros((metric_image_coord.shape[1])) # discriminant > 0 s = cbrt(r[positive_mask] + np.sqrt(delta[positive_mask])) t = cbrt(r[positive_mask] - np.sqrt(delta[positive_mask])) r_distorted[positive_mask] = s + t # discriminant < 0 delta_sqrt = np.sqrt(-delta[~positive_mask]) s = cbrt(np.sqrt(r[~positive_mask]**2 + delta_sqrt**2)) # s = cbrt(np.sqrt(r[~positive_mask] ** 2 + (-delta[~positive_mask]) ** 2)) t = 1. / 3 * np.arctan2(delta_sqrt, r[~positive_mask]) r_distorted[ ~positive_mask] = -s * np.cos(t) + s * np.sqrt(3) * np.sin(t) return metric_image_coord * r_distorted / r_u
def _distort_tsai(self, metric_image_coord): """ Distort centered metric image coordinates following Tsai model. See: Devernay, Frederic, and Olivier Faugeras. "Straight lines have to be straight." Machine vision and applications 13.1 (2001): 14-24. Section 2.1. (only for illustration, the formulas didn't work for me) http://www.cvg.rdg.ac.uk/PETS2009/sample.zip :CameraModel.cpp:CameraModel::undistortedToDistortedSensorCoord Analytical inverse of the undistort_tsai() function. :param metric_image_coord: centered metric image coordinates (metric image coordinate = image_xy * f / z) :type metric_image_coord: numpy.ndarray, shape=(2, n) :return: distorted centered metric image coordinates :rtype: numpy.ndarray, shape=(2, n) """ assert metric_image_coord.shape[0] == 2 x = metric_image_coord[0, :] # vector y = metric_image_coord[1, :] # vector r_u = np.sqrt(x ** 2 + y ** 2) # vector c = 1.0 / self.tsai_kappa # scalar d = -c * r_u # vector # solve polynomial of 3rd degree for r_distorted using Cardan method: # https://proofwiki.org/wiki/Cardano%27s_Formula # r_distorted ** 3 + c * r_distorted + d = 0 q = c / 3. # scalar r = -d / 2. # vector delta = q ** 3 + r ** 2 # polynomial discriminant, vector positive_mask = delta >= 0 r_distorted = np.zeros((metric_image_coord.shape[1])) # discriminant > 0 s = cbrt(r[positive_mask] + np.sqrt(delta[positive_mask])) t = cbrt(r[positive_mask] - np.sqrt(delta[positive_mask])) r_distorted[positive_mask] = s + t # discriminant < 0 delta_sqrt = np.sqrt(-delta[~positive_mask]) s = cbrt(np.sqrt(r[~positive_mask] ** 2 + delta_sqrt ** 2)) # s = cbrt(np.sqrt(r[~positive_mask] ** 2 + (-delta[~positive_mask]) ** 2)) t = 1. / 3 * np.arctan2(delta_sqrt, r[~positive_mask]) r_distorted[~positive_mask] = -s * np.cos(t) + s * np.sqrt(3) * np.sin(t) return metric_image_coord * r_distorted / r_u
def usr_moments(coords): """ Calculates the USR moments for a set of input coordinates as well as the four USR reference atoms. :param coords: numpy.ndarray """ # centroid of the input coordinates ctd = coords.mean(axis=0) # get the distances to the centroid dist_ctd = distance_to_point(coords, ctd) # get the closest and furthest coordinate to/from the centroid cst, fct = coords[dist_ctd.argmin()], coords[dist_ctd.argmax()] # get the distance distributions for the points that are closest/furthest # to/from the centroid dist_cst = distance_to_point(coords, cst) dist_fct = distance_to_point(coords, fct) # get the point that is the furthest from the point that is furthest from # the centroid ftf = coords[dist_fct.argmax()] dist_ftf = distance_to_point(coords, ftf) # calculate the first three moments for each of the four distance distributions moments = concatenate([(ar.mean(), ar.std(), cbrt(skew(ar))) for ar in (dist_ctd, dist_cst, dist_fct, dist_ftf)]) # return the USR moments as well as the four points for later re-use return (ctd, cst, fct, ftf), moments
def __call__(self, coords): # generate ellipsoid values based on parameters (mcx, mcy, mcz) = coords # start with random radius-like values x0 = randint(1, 4) y0 = randint(1, 4) z0 = randint(1, 4) v0 = 4/3 * pi * x0 * y0 * z0 # scale to match volume and round up scale = cbrt(self.size / v0) x1 = int(round(scale * x0)) y1 = int(round(scale * y0)) z1 = int(round(scale * z0)) # pre-calculate squares x2 = x1 * x1 y2 = y1 * y1 z2 = z1 * z1 # generate ranges xr = xrange(-1 * x1, x1) yr = xrange(-1 * y1, y1) zr = xrange(-1 * z1, z1) # calculate ellipsoid oreCoords = [[mcx+x, mcy+y, mcz+z] for x, y, z in product(xr, yr, zr) if x*x/x2+y*y/y2+z*z/z2 <= 1] # if len(oreCoords) > self.size+2: # print "warning: oreCoords larger than self.size -- %d > %d" % (len(oreCoords), self.size) # if len(oreCoords) < self.size-2: # print "warning: oreCoords smaller than self.size -- %d < %d" % (len(oreCoords), self.size) return oreCoords
def model_normalized(params, f): f_r = params['f_r'].value i = params['i'].value c = params['c'].value c_imag = params['c_imag'].value a = params['a'].value Q_r = (i + c)**-1 y_0 = (f / f_r - 1) * Q_r y = (y_0 / 3 + (y_0**2 / 9 - 1 / 12) / cbrt(a / 8 + y_0 / 12 + np.sqrt( (y_0**3 / 27 + y_0 / 12 + a / 8)**2 - (y_0**2 / 9 - 1 / 12)**3) + y_0**3 / 27) + cbrt(a / 8 + y_0 / 12 + np.sqrt( (y_0**3 / 27 + y_0 / 12 + a / 8)**2 - (y_0**2 / 9 - 1 / 12)**3) + y_0**3 / 27)) x = y / Q_r return (1 - ((c + 1j * c_imag) / (i + c + 2j * x)))
def direct_from_centered(mean, cov, skew): """ Follow the advice of Arellano-Valle, R. B. & Azzalini, A. The centred parametrization for the multivariate skew-normal distribution. J. Multivar. Anal. 99, 1362-1382 (2008). Given centered parameters, return direct parameters """ # Calculate mu_z from Eq. 5 c = cbrt((2 * skew) / (4 - np.pi)) u_z = c / np.sqrt(1 + c**2) # Calculate delta_z b = np.sqrt(2. / np.pi) delta_z = u_z / b sigma_z = np.diag(np.sqrt(1 - (b * delta_z)**2)) sigma = np.diag(np.sqrt(np.diag(cov))) w = sigma.dot(np.linalg.pinv(sigma_z)) wdotu_z = w.dot(u_z) dp_mean = mean - wdotu_z dp_cov = cov + np.outer(wdotu_z, u_z).dot(w) winv = np.linalg.pinv(w) omega_hat = winv.dot(dp_cov).dot(winv) omega_hat_inv = np.linalg.pinv(omega_hat) ohi_dot_delta = omega_hat_inv.dot(delta_z) dp_skew = ohi_dot_delta / np.sqrt(1 - ohi_dot_delta.dot(delta_z)) assert is_pos_def(dp_cov), "Covariance matrix must be pos-def" assert np.all(np.isfinite(dp_skew)), "Skew must be finite" return dp_mean, dp_cov, dp_skew
def _calc_epsTE01_int(self, Itke, theta): """ The integral, equation A13, in [TE01]. Parameters ---------- Itke : |np.ndarray| (beta in TE01) is the turbulence intensity ratio: \sigma_u / V theta : |np.ndarray| is the angle between the mean flow, and the primary axis of velocity fluctuations. """ x = np.arange(-20, 20, 1e-2) # I think this is a long enough range. out = np.empty_like(Itke.flatten()) for i, (b, t) in enumerate(zip(Itke.flatten(), theta.flatten())): out[i] = np.trapz( cbrt(x ** 2 - 2 / b * np.cos(t) * x + b ** (-2)) * np.exp(-0.5 * x ** 2), x) return out.reshape(Itke.shape) * \ (2 * np.pi) ** (-0.5) * Itke ** (2 / 3)
def compute_exchage_slater(rho): """Slater exchange energy functional.""" from scipy.special import cbrt cx = (3. / 4) * (3 / np.pi)**(1. / 3) ex = -cx * (np.power(rho, 4. / 3)) vx = -(4. / 3) * cx * cbrt(np.fabs(rho)) return ex, vx
def D(z, omega0): """ Growth Function """ a = 1/(1+z) v = scs.cbrt(omega0/(1.-omega0))/a return a*d1(v)
def scale(network, scale_factor=[1, 1, 1], preserve_vol=False, linear_scaling=[False, False, False]): r""" A method for scaling the coordinates and vertices to create anisotropic networks The original domain volume can be preserved by setting preserve_vol = True Example --------- >>> import OpenPNM >>> import OpenPNM.Utilities.vertexops as vo >>> import numpy as np >>> pn = OpenPNM.Network.Delaunay(num_pores=100, domain_size=[3,2,1]) >>> pn.add_boundaries() >>> B1 = pn.pores("left_boundary") >>> B2 = pn.pores("right_boundary") >>> Vol = vo.vertex_dimension(pn,B1,B2) >>> vo.scale(network=pn,scale_factor=[2,1,1],preserve_vol=True) >>> Vol2 = vo.vertex_dimension(pn,B1,B2) >>> np.around(Vol-Vol2,5) == 0.0 True >>> vo.scale(network=pn,scale_factor=[2,1,1],preserve_vol=False) >>> Vol3 = vo.vertex_dimension(pn,B1,B2) >>> np.around(Vol3/Vol,5) == 2.0 True """ from scipy.special import cbrt import scipy as sp minmax = np.around( vertex_dimension(network=network, face1=network.pores(), parm='minmax'), 10) scale_factor = np.asarray(scale_factor) if preserve_vol is True: scale_factor = scale_factor / (cbrt(sp.prod(scale_factor))) lin_scale = _linear_scale_factor(network["pore.coords"], minmax, scale_factor, linear_scaling) network["pore.coords"] = network["pore.coords"] * lin_scale # Cycle through all vertices of all pores updating vertex values for pore in network.pores(): for i, vert in network['pore.vert_index'][pore].items(): vert_scale = _linear_scale_factor(vert, minmax, scale_factor, linear_scaling) network["pore.vert_index"][pore][i] = vert * vert_scale # Cycle through all vertices of all throats updating vertex values for throat in network.throats(): for i, vert in network['throat.vert_index'][throat].items(): vert_scale = _linear_scale_factor(vert, minmax, scale_factor, linear_scaling) network["throat.vert_index"][throat][i] = vert * vert_scale # Scale the vertices on the voronoi diagram stored on the network # These are used for adding boundaries on the Delaunay network class vert = network._vor.vertices vert_scale = _linear_scale_factor(vert, minmax, scale_factor, linear_scaling) network._vor.vertices = vert * vert_scale
def placeoreintile(tile): # strictly speaking, this should be in class Tile somehow oreobjs = dict([(ore.name, ore) for ore in oreObjs]) tile.ores = dict([(name, list()) for name in oreobjs]) for ore in oreobjs: extent = cbrt(oreobjs[ore].size)*2 maxy = pow(2, oreobjs[ore].depth) numrounds = int(oreobjs[ore].rounds * (tile.size/16) * (tile.size/16)) oreID = materialNamed(oreobjs[ore].name) for dummy in xrange(numrounds): orex = randint(0, tile.size) orey = randint(0, maxy) orez = randint(0, tile.size) coords = [orex+tile.mcoffsetx, orey, orez+tile.mcoffsetz] if (orex < extent or (tile.size-orex) < extent or orez < extent or (tile.size-orez) < extent): try: tile.ores[ore] except KeyError: tile.ores[ore] = [] tile.ores[ore].append(coords) else: for x, y, z in oreobjs[ore](coords): if tile.world.blockAt(x, y, z) == Ore.stoneID: tile.world.setBlockAt(x, y, z, oreID)
def __call__(self, coords): # generate ellipsoid values based on parameters (mcx, mcy, mcz) = coords # start with random radius-like values x0 = randint(1, 4) y0 = randint(1, 4) z0 = randint(1, 4) v0 = 4 / 3 * pi * x0 * y0 * z0 # scale to match volume and round up scale = cbrt(self.size / v0) x1 = int(round(scale * x0)) y1 = int(round(scale * y0)) z1 = int(round(scale * z0)) # pre-calculate squares x2 = x1 * x1 y2 = y1 * y1 z2 = z1 * z1 # generate ranges xr = xrange(-1 * x1, x1) yr = xrange(-1 * y1, y1) zr = xrange(-1 * z1, z1) # calculate ellipsoid oreCoords = [[mcx + x, mcy + y, mcz + z] for x, y, z in product(xr, yr, zr) if x * x / x2 + y * y / y2 + z * z / z2 <= 1] # if len(oreCoords) > self.size+2: # print "warning: oreCoords larger than self.size -- %d > %d" % (len(oreCoords), self.size) # if len(oreCoords) < self.size-2: # print "warning: oreCoords smaller than self.size -- %d < %d" % (len(oreCoords), self.size) return oreCoords
def placeoreintile(tile): # strictly speaking, this should be in class Tile somehow oreobjs = dict([(ore.name, ore) for ore in oreObjs]) tile.ores = dict([(name, list()) for name in oreobjs]) for ore in oreobjs: extent = cbrt(oreobjs[ore].size) * 2 maxy = pow(2, oreobjs[ore].depth) numrounds = int(oreobjs[ore].rounds * (tile.size / 16) * (tile.size / 16)) oreID = materialNamed(oreobjs[ore].name) for dummy in xrange(numrounds): orex = randint(0, tile.size) orey = randint(0, maxy) orez = randint(0, tile.size) coords = [orex + tile.mcoffsetx, orey, orez + tile.mcoffsetz] if (orex < extent or (tile.size - orex) < extent or orez < extent or (tile.size - orez) < extent): try: tile.ores[ore] except KeyError: tile.ores[ore] = [] tile.ores[ore].append(coords) else: for x, y, z in oreobjs[ore](coords): if tile.world.blockAt(x, y, z) == Ore.stoneID: tile.world.setBlockAt(x, y, z, oreID)
def __init__(self, path_to_arc, rootUEP='/', **kwargs): """ :Parameters: path_to_arc : path Path to the HDF5 archive. rootUEP : str root in the archive used as the user entry path (UEP). :Keywords: see NeuronData :Exceptions: IOError: Error finding or reading in the archive. NosuchNodeError: Error finding a data node in the archive. see NeuronData """ # super super(SampledND, self).__init__(**kwargs) # read in data - may raise IOError or NoSuchNodeError arc = openFile(path_to_arc, mode='r', rootUEP=rootUEP) soma_v = arc.getNode('/soma_v').read() ap_phase = xrange(0, soma_v.size) # ap_phase = xrange(*get_eap_range(soma_v)) self.intra_v = arc.getNode('/soma_v').read()[..., ap_phase] # self.extra_v = arc.getNode('/LFP').read().T[..., ap_phase] self.extra_v = arc.getNode('/LFP').read()[..., ap_phase] # read temporary data x_pos = arc.getNode('/el_pos_x').read() y_pos = arc.getNode('/el_pos_y').read() z_pos = arc.getNode('/el_pos_z').read() params = {} for item in arc.getNode('/parameters'): params[item.name] = item.read() # close and delete archive arc.close() del arc # horizon calculation if not ( abs(x_pos.min()) == abs(x_pos.max()) == abs(y_pos.min()) == abs(y_pos.max()) == abs(z_pos.min()) == abs(z_pos.max()) ): raise ValueError('spatial shape is not cubic!') self.horizon = x_pos.max() # sample rate if 'timeres_python' in params: self.sample_rate = 1000.0 / params['timeres_python'] # spatial info - spatial resolution: x > y > z self.grid_step = abs(z_pos[1] - z_pos[0]) self.grid_size = cbrt(self.extra_v.shape[0]) # filename stuff self.description = 'Einevoll::%s' % osp.basename(path_to_arc)
def _ctd_alpha(Coordinates): ctd = np.array([np.mean(Coordinates, axis=0)]) ctd_distance = cdist(ctd, Coordinates)[0] ctd_alpha = {} ctd_alpha['ctd_1'] = round(np.mean(ctd_distance), 3) ctd_alpha['ctd_2'] = round(np.std(ctd_distance), 3) ctd_alpha['ctd_3'] = round(cbrt(stats.skew(ctd_distance)), 3) return ctd_alpha
def voronoi(geometry, pore_volume='pore.volume', **kwargs): r""" Calculate pore diameter from equivalent sphere - volumes must be calculated first """ from scipy.special import cbrt pore_vols = geometry[pore_volume] value = cbrt(6 * pore_vols / _sp.pi) return value
def growthrate(z,omega0): """ growth rate f = dln(D(a))/dln() """ a = 1/(1+z) v = scs.cbrt(omega0/(1.-omega0))/a return (omega0/(((1.-omega0)*a**3)+omega0))*((2.5/d1(v))-1.5)
def scale(network, scale_factor=[1, 1, 1], preserve_vol=False, linear_scaling=[False, False, False]): r""" A method for scaling the coordinates and vertices to create anisotropic networks The original domain volume can be preserved by setting preserve_vol = True Example --------- >>> import OpenPNM >>> import OpenPNM.Utilities.vertexops as vo >>> import numpy as np >>> pn = OpenPNM.Network.Delaunay(num_pores=100, domain_size=[3,2,1]) >>> pn.add_boundaries() >>> B1 = pn.pores("left_boundary") >>> B2 = pn.pores("right_boundary") >>> Vol = vo.vertex_dimension(pn,B1,B2) >>> vo.scale(network=pn,scale_factor=[2,1,1],preserve_vol=True) >>> Vol2 = vo.vertex_dimension(pn,B1,B2) >>> np.around(Vol-Vol2,5) == 0.0 True >>> vo.scale(network=pn,scale_factor=[2,1,1],preserve_vol=False) >>> Vol3 = vo.vertex_dimension(pn,B1,B2) >>> np.around(Vol3/Vol,5) == 2.0 True """ from scipy.special import cbrt import scipy as sp minmax = np.around(vertex_dimension(network=network, face1=network.pores(), parm='minmax'), 10) scale_factor = np.asarray(scale_factor) if preserve_vol is True: scale_factor = scale_factor/(cbrt(sp.prod(scale_factor))) lin_scale = _linear_scale_factor(network["pore.coords"], minmax, scale_factor, linear_scaling) network["pore.coords"] = network["pore.coords"]*lin_scale # Cycle through all vertices of all pores updating vertex values for pore in network.pores(): for i, vert in network['pore.vert_index'][pore].items(): vert_scale = _linear_scale_factor(vert, minmax, scale_factor, linear_scaling) network["pore.vert_index"][pore][i] = vert*vert_scale # Cycle through all vertices of all throats updating vertex values for throat in network.throats(): for i, vert in network['throat.vert_index'][throat].items(): vert_scale = _linear_scale_factor(vert, minmax, scale_factor, linear_scaling) network["throat.vert_index"][throat][i] = vert*vert_scale # Scale the vertices on the voronoi diagram stored on the network # These are used for adding boundaries on the Delaunay network class vert = network._vor.vertices vert_scale = _linear_scale_factor(vert, minmax, scale_factor, linear_scaling) network._vor.vertices = vert*vert_scale
def scott(data, ddof=0): """ Scott's rule for the number of bins in a histogram. """ if np.std(data, ddof=ddof) == 0: return sturges_rule(data) h = 3.5 * np.std(data, ddof=ddof) / cbrt(len(data)) return int((np.max(data) - np.min(data)) / h)
def voronoi(geometry, pore_volume='pore.volume', **kwargs): r""" Calculate pore diameter from equivalent sphere - volumes must be calculated first """ from scipy.special import cbrt pore_vols = geometry[pore_volume] value = cbrt(6*pore_vols/_sp.pi) return value
def cubeRatio(uspdO, uspdS, debug=False, plot=False): """ Estimates the cubed-ratio and returns it. """ ratio = sps.cbrt(np.mean(np.power(uspdO,3))/np.mean(np.power(uspdS,3))) if debug: print 'speed ratio is {}'.format(ratio) return ratio
def scott(data, ddof=0): """ Scott's rule for the number of bins in a histogram. """ if np.std(data, ddof=ddof) == 0: return sturges_rule(data) h = 3.5*np.std(data, ddof=ddof)/cbrt(len(data)) return int((np.max(data) - np.min(data))/h)
def __init__(self): u0 = cbrt(1 + sqrt(2)) / sqrt(3) r0 = u0 + 1 / (3*u0) lmbd = 2 * r0**2 - r0**4 + 8 * sqrt(2/27.) * r0 self.__norm_alpha = 2 / lmbd self.__norm_beta = 1 / lmbd self.__norm_kappa = -8 * sqrt(2/27.) / lmbd self.__phi_b = pi / 4. self.__qh_b = - sqrt(1/27.)
def diff_gaussian_offset_1d( self, sigma_e, sigma_i, size=7, origin=0 ): """Builds a 1D difference of gaussian kernel centered at the origin given""" f = empty( size ) x = arange( size ) - origin center = math.floor( size / 2 ) f = 1.0 / (sigma_e*math.sqrt(2*pi)) * \ exp( -square(x-center) / (2*sigma_e**2)) - \ 1.0 / (sigma_i*math.sqrt(2*pi)) * \ exp( -square(x-center) / (2*sigma_i**2)) f /= abs(sum(f.ravel())) # normalize f = cbrt( f ) # The result of this filter and a 2D filter should be normalized return f
def Gtilde(x): """ AKP10 Eq. D7 Factor ~2 performance gain in using cbrt(x)**n vs x**(n/3.) Invoking crbt only once reduced time by ~40% """ cb = cbrt(x) gt1 = 1.808 * cb / np.sqrt(1 + 3.4 * cb**2.) gt2 = 1 + 2.210 * cb**2. + 0.347 * cb**4. gt3 = 1 + 1.353 * cb**2. + 0.217 * cb**4. return gt1 * (gt2 / gt3) * np.exp(-x)
def __init__(self, radiiInitializer): # tunable parameters self.p1 = 2e6 # upstream pressure self.numberOfPipes = 10 # spatial resolution totalTime = 3.6e3*6 # simulation duration # physical parameters self.c0 = 0.0 # upstream concentration sampleLength = 2.62e-2 # sample length eta = 1.07e-3 # viscosity L = sampleLength/self.numberOfPipes # pipe length self.L = L # reference length self.K0 = np.pi*L*L*L/8/eta # reference proportional constant self.P0 = 1e5 # reference pressure self.p0 = 0.0 # downstream pressure self.V0 = np.pi*L*L*L # reference volume self.C0 = 35.0 # reference/saturation concentration self.T0 = self.V0/self.K0/self.P0 # reference time self.dt = 0.0 # time step nu = 9.0e-7 # kinetic viscosity kS = 1.87e-3/self.C0 # reaction constant M = 100.0e-3 # molar mass of CaCO3 rho = 2.7e3 # density of CaCO3 Dm = 7.9e-10; # molecular diffusivity Sc = nu/Dm u0 = self.K0 * self.P0 / (np.pi * L * L) Re0 = 2*u0*L/nu self.Sh_inf = 3.66 # Sherwood number self.Sh_0 = 0.7 * np.sqrt(Re0) * cbrt(Sc) # Sherwood number self.k_SC_0 = 2 * kS * L / Dm # reaction speed self.F0 = 2 * kS * self.T0 / L self.C_bound = rho/M/self.C0 # nondimensional concentration bound # state variables self.time = 0.0 self.maxTime = totalTime/self.T0 self.stepCount = 0 self.concentration = np.zeros(self.numberOfPipes) self.radii = np.empty(self.numberOfPipes) self.pressure = np.empty(self.numberOfPipes+1) self.pressure[self.numberOfPipes] = self.p0 / self.P0 # initialzation radiiInitializer.initialize(self.radii) self.flux = (self.p1 - self.p0) / \ np.sum(8*eta*L/np.pi/np.power(self.radii, 4)) print "flux", self.flux self.radii /= self.L # log simulation settings totalVolume = self.V0*np.sum(self.radii*self.radii)*1e6 logging.info("Total volume: %f cm3", totalVolume) injectVolume = self.flux*totalTime*1e6 logging.info("Volume injected: %f cm3 in %f hours", injectVolume, totalTime/3600) logging.info("Volume ratio: %d", injectVolume/totalVolume)
def _ctd_alpha(coords): """ :param coords: n * 3 :return: """ ctd = np.array([np.mean(coords, axis=0)]) ctd_distance = cdist(ctd, coords)[0] ctd_alpha = {} ctd_alpha['ctd_1'] = round(np.mean(ctd_distance), 3) ctd_alpha['ctd_2'] = round(np.std(ctd_distance), 3) ctd_alpha['ctd_3'] = round(cbrt(stats.skew(ctd_distance)), 3) return ctd_alpha
def _fct_alpha(Coordinates): ctd = np.array([np.mean(Coordinates, axis=0)]) ctd_distance = cdist(ctd, Coordinates)[0] fct_index = np.argmax(ctd_distance) fct = np.array([Coordinates[fct_index]]) fct_distance = cdist(fct, Coordinates)[0] fct_alpha = {} fct_alpha['fct_1'] = round(np.mean(fct_distance), 3) fct_alpha['fct_2'] = round(np.std(fct_distance), 3) fct_alpha['fct_3'] = round(cbrt(stats.skew(fct_distance)), 3) return fct_alpha
def _cst_alpha(Coordinates): ctd = np.array([np.mean(Coordinates, axis=0)]) ctd_distance = cdist(ctd, Coordinates)[0] cst_index = np.argmin(ctd_distance) cst = np.array([Coordinates[cst_index]]) cst_distance = cdist(cst, Coordinates)[0] cst_alpha = {} cst_alpha['cst_1'] = round(np.mean(cst_distance), 3) cst_alpha['cst_2'] = round(np.std(cst_distance), 3) cst_alpha['cst_3'] = round(cbrt(stats.skew(cst_distance)), 3) return cst_alpha
def diff_gaussian_offset_2d( self, sigma_e, sigma_i, shape=( 7, 7 ), origin=( 0, 0 ) ): """Builds a 2D difference of gaussian kernel centered at the origin given""" f = empty( shape ) x, y = meshgrid( arange( shape[0] ) - origin[0], arange( shape[1] ) - origin[1] ) center = ( math.floor( shape[0] / 2 ), math.floor( shape[1] / 2 ) ) f = 1.0 / ( 2* sigma_e**2 * pi ) * \ exp( (-( x - center[0])**2 - (y - center[1])**2 ) / (2*sigma_e**2)) - \ 1.0 / ( 2 * sigma_i**2 * pi ) * \ exp( (-( x - center[0])**2 - (y - center[1])**2 ) / (2*sigma_i**2)) f /= abs(sum(f.ravel())) # normalize #f = square( cbrt( f ) ) # The result of this filter and a 1D filter should be normalized f = cbrt( f ) # TEMP return f
def _Gtilde(self, x): """ Useful equation. Aharonian, Kelner, Prosekin 2010 Eq. D7 Taken from Naima. Factor ~2 performance gain in using cbrt(x)**n vs x**(n/3.) Invoking crbt only once reduced time by ~40% """ cb = cbrt(x) # x**1/3 gt1 = 1.808 * cb / np.sqrt(1 + 3.4 * cb**2.0) gt2 = 1 + 2.210 * cb**2.0 + 0.347 * cb**4.0 gt3 = 1 + 1.353 * cb**2.0 + 0.217 * cb**4.0 return gt1 * (gt2 / gt3) * np.exp(-x)
def json2png(fname): root, ext = os.path.splitext(fname) fopen = open if ext == '.gz': fopen = gzip.open root, ext = os.path.splitext(root) if ext != '.json': raise ValueError('Not a json file (%s): %s'%(ext, fname)) with fopen(fname, 'r') as injson: histo = np.array(json.load(injson)) histo = cbrt(histo) image = toimage(histo, high=65536, low=0, mode='I') image = image.transpose(Image.FLIP_TOP_BOTTOM) image.save(root+'.png', format='PNG', bits=16)
def __global_minimum_radius(self,phi): qh = self.__norm_kappa * abs(sin(phi)) / (8 * self.__norm_beta) signum_phi = np.sign(sin(phi)) if signum_phi == 0: signum_phi = 1 if (qh <= self.__qh_b): u = cbrt(-signum_phi*qh + sqrt(qh*qh - 1 / 27)) r0 = u + 1 / (3*u) else: r0 = signum_phi * sqrt(4/3) * cos(1/3 * arccos(-qh*sqrt(27)) ) return r0
def nonlinear_resonator(f,f_0,Q,Q_e_real,Q_e_imag,a): Q_e = Q_e_real + 1j*Q_e_imag if np.isscalar(f): fmodel = np.linspace(f * 0.9999, f * 1.0001, 1000) scalar = True else: fmodel = f scalar = False y_0 = ((fmodel - f_0) / f_0) * Q y = (y_0 / 3. + (y_0 ** 2 / 9 - 1 / 12) / cbrt(a / 8 + y_0 / 12 + np.sqrt( (y_0 ** 3 / 27 + y_0 / 12 + a / 8) ** 2 - (y_0 ** 2 / 9 - 1 / 12) ** 3) + y_0 ** 3 / 27) + cbrt(a / 8 + y_0 / 12 + np.sqrt( (y_0 ** 3 / 27 + y_0 / 12 + a / 8) ** 2 - (y_0 ** 2 / 9 - 1 / 12) ** 3) + y_0 ** 3 / 27)) x = y / Q s21 = (1 - (Q / Q_e) / (1 + 2j * Q * x)) mask = np.isfinite(s21) if scalar or not np.all(mask): s21_interp_real = np.interp(f, fmodel[mask], s21[mask].real) s21_interp_imag = np.interp(f, fmodel[mask], s21[mask].imag) s21new = s21_interp_real + 1j * s21_interp_imag else: s21new = s21 return s21new
def diff_gaussian_separable( self, dim_e, dim_i, sigma_e, sigma_i ): dim = max(dim_e, dim_i) f = empty( ( dim ) ) center = math.floor( dim / 2 ) for x in xrange( dim ): f[x] = ( 1 if x <= center + dim_e and x >= center - dim_e else 0 ) * \ 1.0 / (sigma_e*math.sqrt(2*pi)) * \ math.exp( -(x-center)**2 / (2*sigma_e**2)) - \ ( 1 if x <= center + dim_i and x >= center - dim_i else 0 ) * \ 1.0 / (sigma_i*math.sqrt(2*pi)) * \ math.exp( -(x-center)**2 / (2*sigma_i**2)) f /= abs(sum(f.ravel())) # normalize f = cbrt( f ) # Take the cubed root, so the filter applied 3 times will be normalized return f
def Gtilde(x): """ AKP10 Eq. D7 Factor ~2 performance gain in using cbrt(x)**n vs x**(n/3.) """ gt1 = 1.808 * cbrt(x) / np.sqrt(1 + 3.4 * cbrt(x) ** 2.) gt2 = 1 + 2.210 * cbrt(x) ** 2. + 0.347 * cbrt(x) ** 4. gt3 = 1 + 1.353 * cbrt(x) ** 2. + 0.217 * cbrt(x) ** 4. return gt1 * (gt2 / gt3) * np.exp(-x)
def fwhm(anat_file, mask_file, out_vox=False): """Calculate the FWHM of the input image using AFNI's 3dFWHMx. - Uses AFNI 3dFWHMx. More details here: https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dFWHMx.html :type anat_file: str :param anat_file: The filepath to the anatomical image NIFTI file. :type mask_file: str :param mask_file: The filepath to the binary head mask NIFTI file. :type out_vox: bool :param out_vox: (default: False) Output the FWHM as number of voxels instead of mm (the default). :rtype: tuple :return: A tuple of the FWHM values (x, y, z, and combined). """ import nibabel as nib import numpy as np from scipy.special import cbrt import subprocess fwhm_string_list = ["3dFWHMx", "-combined", "-mask", mask_file, "-input", anat_file] try: retcode = subprocess.check_output(fwhm_string_list) except Exception as e: err = "\n\n[!] Something went wrong with AFNI's 3dFWHMx. Error " \ "details: %s\n\n" % e raise Exception(err) # extract output vals = np.array(retcode.split(), dtype=np.float) if out_vox: # get pixel dimensions img = nib.load(anat_file) hdr = img.get_header() pixdim = hdr['pixdim'][1:4] # convert to voxels pixdim = np.append(pixdim, cbrt(pixdim.prod())) # get the geometrix mean vals = vals / pixdim return tuple(vals)
def fwhm(anat_file, mask_file, out_vox=False): """ Calculate the FWHM of the input image. Parameters ---------- anat_file: str path to anatomical file mask_file: str path to brain mask out_vox: bool output the FWHM as # of voxels (otherwise as mm) Returns ------- fwhm: tuple (x,y,z,combined) FWHM in the x, y, x, and combined direction """ import commands import nibabel as nib import numpy as np from scipy.special import cbrt # call AFNI command to get the FWHM in x,y,z and combined cmd = "3dFWHMx -combined -mask %s -input %s" % (mask_file, anat_file) out = commands.getoutput(cmd) # extract output line = out.splitlines()[-1].strip() vals = np.array(line.split(), dtype=np.float) if out_vox: # get pixel dimensions img = nib.load(anat_file) hdr = img.get_header() pixdim = hdr['pixdim'][1:4] # convert to voxels pixdim = np.append(pixdim, cbrt(pixdim.prod())) # get the geometrix mean vals = vals / pixdim return tuple(vals)
def equivalent_cube(geometry, pore_volume='pore.volume', **kwargs): r""" Calculate pore diameter as the width of a cube with an equivalent volume. Parameters ---------- geometry : OpenPNM Geometry Object The Geometry object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary geometric properties. pore_volume : string The dictionary key containing the pore volume values """ from scipy.special import cbrt pore_vols = geometry[pore_volume] value = cbrt(pore_vols) return value
def SimData_Breiman1(n, sigma=1): """ Breiman 1 model This is a 1-d model. y = exp(x^3 + \epsilon) \epsilon ~ N(0,1) x^3 ~ N(0,1) :param n: sample size :param sigma: :return: """ epsilon = sigma * np.random.randn(n) x3 = np.random.randn(n) y = np.exp(x3 + epsilon) x = cbrt(x3) return y, x
def neutron_radius(): data = np.genfromtxt("data/cross_section/neutron_rad.tsv", usecols=(0,1,2)) sigma = data[:,0] dsigma = data[:,1] A = data[:,2] ydata = np.sqrt(sigma/(2*np.pi)) xdata = cbrt(A) dy = np.sqrt(dsigma/(2*np.pi)) #print ydata def sim_data(nruns): r0 = [] dbw = [] # de broglie wavelength for i in range(0, nruns): yd = np.random.randn(len(ydata))*np.min(dy) + ydata popt = np.polyfit(xdata, yd, 1) r0.append(popt[0]) dbw.append(popt[1]) return r0, dbw r0, dbw = sim_data(1500) popt = [np.average(r0), np.average(dbw)] pcov = [np.std(r0), np.std(dbw)] yFit = linear(xdata, *popt) yFit_max = linear(xdata, *np.add(popt,pcov)) yFit_min = linear(xdata, *np.subtract(popt,pcov)) plt.figure(figsize=(10, 10)) plt.errorbar(xdata, ydata, yerr=dy, fmt='o') plt.plot(xdata, yFit, label="Best Fit") plt.plot(xdata, yFit_max, label="Plus 1$\sigma$") plt.plot(xdata, yFit_min, label="Minus 1$\sigma$") plt.text(xdata[0], ydata[0] + 1e-12, "$r_0A^{1/3} + \lambda$ \n $r_{0} = %.1f\,\pm\,%.1f\,fm$ \n $\lambda = %.0f\,\pm\,%.0f\,fm$" % (popt[0]*1e13, pcov[0]*1e13, popt[1]*1e13, pcov[1]*1e13)) plt.xlabel("$A^{1/3}$ $(g/mol)^{1/3}$") plt.ylabel(r"$\sqrt{\frac{\sigma}{2 \pi}}$ $(\sqrt{\frac{cm^2}{rad}})$") plt.title("Radius and deBroglie Wavelength of the Neutron") plt.legend(loc=3) plt.savefig("plots/neutron_radius.pdf") plt.show()
def SimData_Breiman1(n, sigma=1): """ Breiman 1 model This is a 1-d model. y = exp(x^3 + \epsilon) \epsilon ~ N(0,1) x^3 ~ N(0,1) :param n: sample size :param sigma: :return: """ epsilon = sigma * np.random.randn(n) x3 = np.random.randn(n) y = np.exp(x3 + epsilon) x = cbrt(x3) # Standard data structure is a matrix x = np.matrix(x).T y = np.matrix(y).T return y, x
def scale(network,scale_factor=[1,1,1],preserve_vol=True): r""" A method for scaling the coordinates and vertices to create anisotropic networks The original domain volume can be preserved by setting preserve_vol = True Example --------- >>> import OpenPNM >>> import OpenPNM.Utilities.vertexops as vo >>> import numpy as np >>> pn = OpenPNM.Network.Delaunay(num_pores=100, domain_size=[3,2,1]) >>> pn.add_boundaries() >>> B1 = pn.pores("left_boundary") >>> B2 = pn.pores("right_boundary") >>> Vol = vo.vertex_dimension(pn,B1,B2) >>> vo.scale(network=pn,scale_factor=[2,1,1]) >>> Vol2 = vo.vertex_dimension(pn,B1,B2) >>> np.around(Vol-Vol2,5) 0.0 >>> vo.scale(network=pn,scale_factor=[2,1,1],preserve_vol=False) >>> Vol3 = vo.vertex_dimension(pn,B1,B2) >>> np.around(Vol3/Vol,5) 2.0 """ from scipy.special import cbrt import scipy as sp scale_factor = np.asarray(scale_factor) if preserve_vol == True: scale_factor = scale_factor/(cbrt(sp.prod(scale_factor))) network["pore.coords"]=network["pore.coords"]*scale_factor #Cycle through all vertices of all pores updating vertex values for pore in network.pores(): for i,vert in network["pore.vert_index"][pore].items(): network["pore.vert_index"][pore][i] = network["pore.vert_index"][pore][i]*scale_factor #Cycle through all vertices of all throats updating vertex values for throat in network.throats(): for i,vert in network["throat.vert_index"][throat].items(): network["throat.vert_index"][throat][i] = network["throat.vert_index"][throat][i]*scale_factor
def ecef2geodetic(x, y, z, degrees=True): """ecef2geodetic(x, y, z) [m][m][m] Convert ECEF coordinates to geodetic. J. Zhu, "Conversion of Earth-centered Earth-fixed coordinates \ to geodetic coordinates," IEEE Transactions on Aerospace and \ Electronic Systems, vol. 30, pp. 957-961, 1994.""" r = sqrt(x * x + y * y) Esq = a * a - b * b F = 54 * b * b * z * z G = r * r + (1 - esq) * z * z - esq * Esq C = (esq * esq * F * r * r) / (pow(G, 3)) S = cbrt(1 + C + sqrt(C * C + 2 * C)) P = F / (3 * pow((S + 1 / S + 1), 2) * G * G) Q = sqrt(1 + 2 * esq * esq * P) r_0 = -(P * esq * r) / (1 + Q) + sqrt(0.5 * a * a*(1 + 1.0 / Q) - \ P * (1 - esq) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r) U = sqrt(pow((r - esq * r_0), 2) + z * z) V = sqrt(pow((r - esq * r_0), 2) + (1 - esq) * z * z) Z_0 = b * b * z / (a * V) h = U * (1 - b * b / (a * V)) lat = arctan((z + e1sq * Z_0) / r) lon = arctan2(y, x) return rad2deg(lat), rad2deg(lon), z
scaling = '' for o, a in myopts: if o == '-x': mx=a elif o == '-s': scaling = a else: print("Usage: %s -x cells -s scaling" % sys.argv[0]) size = PETSc.Comm.getSize(PETSc.COMM_WORLD) rank = PETSc.Comm.getRank(PETSc.COMM_WORLD) solver = 'classic' if scaling=='weak': mx = int(96 * cbrt(size/4)) tfinal_reduction = cbrt(size/4) # Initialize grid my = mz = mx out_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scaling_3d_{0}'.format(solver)) processList = [0, 3] if rank==0 and not os.path.isdir(out_folder): os.mkdir(out_folder) # Initialize log file logfile = MPI.File.Open(MPI.COMM_WORLD, os.path.join(out_folder,"results_"+str(size)+'_'+str(mx)+".log"), MPI.MODE_CREATE|MPI.MODE_WRONLY) tb1call = MPI.Wtime() reduced_mx = cbrt(size/4) * 8
from __future__ import division from numpy import sqrt from scipy.special import cbrt cardano = lambda a, b, c: cbrt(a + b * sqrt(c)) + cbrt(a - b * sqrt(c)) == 1 n = 1001 m = 0 for a in range(n): for b in range(n - a): for c in range(n - a - b): if cardano(a, b, c): print a, b, c print m