import numpy as np import scipy def clamp(z, vmin=0, vmax=1): return np.minimum(vmax *…
- User
import numpy as np import scipy
def clamp(z, vmin=0, vmax=1): return np.minimum(vmax * np.ones(z.shape), np.maximum(vmin * np.ones(z.shape), z))
def gradient_angle(z): dx, dy = np.gradient(z, axis=0), np.gradient(z, axis=1) return np.arctan2(dy, dx)
def gradient_norm(z): dx, dy = np.gradient(z, axis=0), np.gradient(z, axis=1) return np.hypot(dx, dy)
def gaussian_curvature(z, sigma=2): z = scipy.ndimage.gaussian_filter(z, sigma=sigma)
zx, zy = np.gradient(z) zxx, zxy = np.gradient(zx) _, zyy = np.gradient(zy) # Gaussian curvature = K1 * K2 k = (zxx * zyy - (zxy**2)) / (1 + (zx**2) + (zy**2))**2 # mean curvature = (K1 + K2)/2 h = (zxx * (1 + zy**2) - 2 * zxy * zx * zy + zyy * (1 + zx**2)) / 2 / (1 + zx**2 + zy**2)**1.5 return k, hdef hillshade(z, azimuth, zenith, talus_ref): azimuth_rad = np.pi * azimuth / 180 zenith_rad = np.pi * zenith / 180
aspect = gradient_angle(z) dn = gradient_norm(z) / talus_ref slope = np.arctan(dn) sh = np.cos(zenith_rad) * np.cos(slope) \ + np.sin(zenith_rad) * np.sin(slope) * np.cos(azimuth_rad - aspect) return (sh - sh.min()) / sh.ptp()can you convert that code to rust
- Assistant
Sure! Here's the equivalent code in Rust:
extern crate ndarray; extern crate ndarray_stats; use ndarray::{Array, Array2}; use ndarray_stats::errors::MinMaxError; fn clamp(z: &Array2<f64>, vmin: f64, vmax: f64) -> Result<Array2<f64>, MinMaxError> { z.mapv(|val| val.max(vmin).min(vmax)) } fn gradient_angle(z: &Array2<f64>) -> Array2<f64> { let dx = nd::gradient::gradient(&z, None, None, None, Some(1))[0].clone(); let dy = nd::gradient::gradient(&z, None, None, Some(1), None)[1].clone(); dy.atan2(&dx) } fn gradient_norm(z: &Array2<f64>) -> Array2<f64> { let dx = nd::gradient::gradient(&z, None, None, None, Some(1))[0].clone(); let dy = nd::gradient::gradient(&z, None, None, Some(1), None)[1].clone(); let dx_sq = dx.mapv(|val| val.powi(2)); let dy_sq = dy.mapv(|val| val.powi(2)); dx_sq + dy_sq } fn gaussian_curvature(z: &Array2<f64>, sigma: f64) -> Result<(Array2<f64>, Array2<f64>), MinMaxError> { let z = ndarray::Array2::<f64>::from(ndarray::ArrayD::<f64>::from(z.clone().to_owned()).gaussian_filter(sigma)); let zx = nd::gradient::gradient(&z, None, None, None, Some(1))[0].clone(); let zy = nd::gradient::gradient(&z, None, None, Some(1), None)[1].clone(); let zxx = nd::gradient::gradient(&zx, None, None, None, Some(1))[0].clone(); let zxy = nd::gradient::gradient(&zx, None, None, Some(1), None)[1].clone(); let (_, zyy) = nd::gradient::gradient(&zy, None, None, Some(1), None); // Gaussian curvature = K1 * K2 let k = (zxx * zyy - (zxy.powi(2))) / (1.0 + (zx.powi(2)) + (zy.powi(2))).powi(2); // mean curvature = (K1 + K2)/2 let h = (zxx * (1.0 + zy.powi(2)) - 2.0 * zxy * zx * zy + zyy * (1.0 + zx.powi(2))) / 2.0 / (1.0 + zx.powi(2) + zy.powi(2)).powi(1); Ok((k, h)) } fn hillshade(z: &Array2<f64>, azimuth: f64, zenith: f64, talus_ref: f64) -> Result<Array2<f64>, MinMaxError> { let azimuth_rad = std::f64::consts::PI * azimuth / 180.0; let zenith_rad = std::f64::consts::PI * zenith / 180.0; let aspect = gradient_angle(z); let dn = gradient_norm(z).mapv(|val| val / talus_ref); let slope = dn.atan(); let sh = (zenith_rad.cos() * slope.cos()) + (zenith_rad.sin() * slope.sin() * (azimuth_rad - aspect).cos()); let sh_min = sh.fold(std::f64::INFINITY, f64::min); let sh_ptp = sh.fold(std::f64::NEG_INFINITY, f64::max) - sh_min; Ok((sh - sh_min) / sh_ptp) } fn main() { let z = Array::from_shape_vec((3, 3), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]).unwrap(); let clamped = clamp(&z, 0.0, 1.0).unwrap(); let grad_angle = gradient_angle(&z); let grad_norm = gradient_norm(&z); let gaussian_curvature = gaussian_curvature(&z, 2.0).unwrap(); let hillshade = hillshade(&z, 45.0, 30.0, 2.0).unwrap(); println!("Clamped: \n{}", clamped); println!("Gradient Angle: \n{}", grad_angle); println!("Gradient Norm: \n{}", grad_norm); println!("Gaussian Curvature: \n{:?}", gaussian_curvature); println!("Hillshade: \n{}", hillshade); }Please note that the above code requires adding the
ndarrayandndarray-statsdependencies to yourCargo.tomlfile. Also, since Rust does not have a built-in gaussian filter function like scipy, you will need to use a separate library likendarray-statsto perform the gaussian filtering in your code. - User
there is no gradient method
- Assistant
I apologize for the confusion. You are correct, there is no built-in
gradientmethod in thendarraycrate.To calculate gradients in Rust, you can use the
ndarray::gradient::Gradienttrait along with thendarray::Zipiterator to iterate over the array and calculate the gradients manually.Here's an updated version of the code:
use ndarray::{Array, Array2, Axis}; use ndarray_stats::errors::MinMaxError; use std::f64::consts::PI; fn clamp(z: &Array2<f64>, vmin: f64, vmax: f64) -> Result<Array2<f64>, MinMaxError> { Ok(z.mapv(|val| val.max(vmin).min(vmax))) } fn gradient_angle(z: &Array2<f64>) -> Array2<f64> { let dz_dx = z.indexed_iter() .map(|((r, c), _)| { let left = z.get((r, c.saturating_sub(1))).unwrap_or(&0.0); let right = z.get((r, c + 1)).unwrap_or(&0.0); right - left }) .collect(); let dz_dy = z.indexed_iter() .map(|((r, c), _)| { let up = z.get((r.saturating_sub(1), c)).unwrap_or(&0.0); let down = z.get((r + 1, c)).unwrap_or(&0.0); down - up }) .collect(); Array::from_shape_vec(z.dim(), dz_dy.into_iter().map(|dy| dy.atan2(dz_dx[0])).collect()).unwrap() } fn gradient_norm(z: &Array2<f64>) -> Array2<f64> { let dz_dx = z.indexed_iter() .map(|((r, c), _)| { let left = z.get((r, c.saturating_sub(1))).unwrap_or(&0.0); let right = z.get((r, c + 1)).unwrap_or(&0.0); right - left }) .collect(); let dz_dy = z.indexed_iter() .map(|((r, c), _)| { let up = z.get((r.saturating_sub(1), c)).unwrap_or(&0.0); let down = z.get((r + 1, c)).unwrap_or(&0.0); down - up }) .collect(); let dz_dx_sq: Vec<f64> = dz_dx.iter().map(|&dx| dx.powi(2)).collect(); let dz_dy_sq: Vec<f64> = dz_dy.iter().map(|&dy| dy.powi(2)).collect(); Array::from_shape_vec(z.dim(), dz_dx_sq.iter().zip(dz_dy_sq.iter()).map(|(&dx_sq, &dy_sq)| dx_sq + dy_sq).collect()).unwrap() } fn gaussian_curvature(z: &Array2<f64>, sigma: f64) -> Result<(Array2<f64>, Array2<f64>), MinMaxError> { let gaussian_filtered = ndarray::ArrayD::<f64>::from(z.clone().to_owned()).gaussian_filter(sigma); let z = Array::from_shape_vec(z.dim(), gaussian_filtered.into_raw_vec()).unwrap(); let zx = gradient_norm(&z); let zy = gradient_norm(&z.t()); let zxx = gradient_norm(&zx); let zxy = gradient_norm(&zy.t()); let zyy = gradient_norm(&zy.t()); // Gaussian curvature = K1 * K2 let k = (&zxx * &zyy - &zxy.powf(2.0)) / (1.0 + (&zx.powf(2.0)) + (&zy.powf(2.0))).powf(2.0); // mean curvature = (K1 + K2)/2 let h = (&zxx * (1.0 + &zy.powf(2.0)) - 2.0 * &zxy * &zx * &zy + &zyy * (1.0 + &zx.powf(2.0))) / (2.0 * (1.0 + &zx.powf(2.0) + &zy.powf(2.0))).sqrt(); Ok((k, h)) } fn hillshade(z: &Array2<f64>, azimuth: f64, zenith: f64, talus_ref: f64) -> Result<Array2<f64>, MinMaxError> { let azimuth_rad = PI * azimuth / 180.0; let zenith_rad = PI * zenith / 180.0; let aspect = gradient_angle(z); let dn = gradient_norm(z).mapv(|val| val / talus_ref); let slope = dn.mapv(|val| val.atan()); let sh = ((zenith_rad.cos() * &slope.cos()) + (zenith_rad.sin() * &slope.sin() * &(azimuth_rad - &aspect).cos())) .mapv(|val| (val - val.floor()).max(0.0) / (val.ceil() - val.floor()).max(1.0)); Ok(sh) } fn main() { let z = Array::from_shape_vec((3, 3), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]).unwrap(); let clamped = clamp(&z, 0.0, 1.0).unwrap(); let grad_angle = gradient_angle(&z); let grad_norm = gradient_norm(&z); let gaussian_curvature = gaussian_curvature(&z, 2.0).unwrap(); let hillshade = hillshade(&z, 45.0, 30.0, 2.0).unwrap(); println!("Clamped: \n{}", clamped); println!("Gradient Angle: \n{}", grad_angle); println!("Gradient Norm: \n{}", grad_norm); println!("Gaussian Curvature: \n{:?}", gaussian_curvature); println!("Hillshade: \n{}", hillshade); }This updated code manually calculates the gradients by iterating over the cells of the array and computing the differences. Keep in mind that this method assumes the array is a regular grid and that the cells in
zare evenly spaced.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.