Skip to content

Instantly share code, notes, and snippets.

@jerry73204
Created May 10, 2020 15:49
Show Gist options
  • Select an option

  • Save jerry73204/a2df6a93467c8da9c96ff3b16b7fcbe2 to your computer and use it in GitHub Desktop.

Select an option

Save jerry73204/a2df6a93467c8da9c96ff3b16b7fcbe2 to your computer and use it in GitHub Desktop.
use gnuplot::{AxesCommon, Figure};
use ndarray::{prelude::*, Array1};
use std::f64::consts::PI;
type RealFn = fn(f64) -> f64;
struct NamedFunction(String, RealFn);
struct Wave {
U: Array1<f64>,
f: Box<dyn Fn(f64) -> f64>,
df: Box<dyn Fn(f64) -> f64>,
dx: f64,
dt: f64,
grid: Array1<f64>,
duration: f64,
}
struct Domain {
time: f64,
space: [f64; 2],
}
impl Wave {
fn new(
init: Box<dyn Fn(f64) -> f64>,
domain: Domain,
dx: f64,
dt: f64,
f: Box<dyn Fn(f64) -> f64>,
df: Box<dyn Fn(f64) -> f64>,
) -> Self {
let Domain { time, space } = domain;
let grid = Array::range(space[0], space[1], dx);
Wave {
U: grid.mapv(init),
f: f,
df: df,
dx: dx,
dt: dt,
duration: time,
grid: grid,
}
}
fn plot(&self) {
let mut fg = Figure::new();
fg.set_title("Wave").set_offset(2.0, 0.0);
fg.axes2d()
// .set_aspect_ratio(AutoOption::Fix(0.5))
// .set_size(0.6, 0.4)
.set_x_grid(true)
.set_y_grid(true)
.lines(&self.grid, &self.U, &[]);
fg.show().unwrap();
}
// fn spreading_speed_plus(&self) -> Array1<f64> {
// let V = self.state.clone();
// }
// fn numerical_flux(self) -> Array1<f64> {
// }
}
fn main() {
let dx = 1e-2;
let CFL = 0.6;
let dt = CFL * dx;
let time = Array::range(0., 3., dt);
let space = Array::range(-5., 5., dx);
let initial_conditions = [
NamedFunction("Square wave".into(), |x| {
if x >= 0. && x <= 1. {
1.0
} else {
0.
}
}),
NamedFunction("Sine wave".into(), |x| (PI * x).sin()),
];
// let mut fg = Figure::new();
// fg.set_title("Initial conditions")
// .set_offset(2.0, 0.0)
// .set_multiplot_layout(2, 1);
// for ic in initial_conditions.iter() {
// let NamedFunction(name, fcn) = ic;
// let y = space.mapv(fcn);
// fg.axes2d()
// .set_title(name, &[])
// // .set_aspect_ratio(AutoOption::Fix(0.5))
// // .set_size(0.6, 0.4)
// .set_x_grid(true)
// .set_y_grid(true)
// .lines(&space, &y, &[]);
// }
// fg.save_to_png("initial_conditions.png", 640, 480).unwrap();
// fg.show().unwrap();
//
//
let domain = Domain {
time: 3.,
space: [-5., 5.],
};
// static A: f64 = 1.;
let my_wave = Wave::new(
Box::new(|x| if x >= 0. && x <= 1. { 1.0 } else { 0. }),
domain,
dx,
dt,
Box::new(|u: f64| 0.1 * u),
Box::new(|_| 0.1),
);
my_wave.plot();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment