Skip to content

Commit

Permalink
plotters - ln from framework
Browse files Browse the repository at this point in the history
  • Loading branch information
andrei-marinica committed Jun 18, 2024
1 parent bf406bf commit 3598efb
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 31 deletions.
26 changes: 13 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 10 additions & 3 deletions framework/base/src/types/managed/basic/big_uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,17 @@ impl<M: ManagedTypeApi> BigUint<M> {
api.bi_log2(self.handle.clone())
}

pub fn ln(&self) -> ManagedDecimal<M, ConstDecimals<9>> {
/// Natural logarithm of a number.
///
/// Returns `None` for 0.
pub fn ln(&self) -> Option<ManagedDecimal<M, ConstDecimals<9>>> {
if self == &0u32 {
return None;
}

let bit_log2 = self.log2(); // aproximate, based on position of the most significant bit
let scaling_factor_9 = ConstDecimals::<9>.scaling_factor();
let divisor = BigUint::from(1u64 << bit_log2);
let divisor = BigUint::from(1u64) << bit_log2 as usize;
let normalized = self * &*scaling_factor_9 / divisor;

let x = normalized
Expand Down Expand Up @@ -279,7 +286,7 @@ impl<M: ManagedTypeApi> BigUint<M> {
let mut result_bi = normalized; // reuse handle
result_bi.overwrite_u64(result as u64);

ManagedDecimal::const_decimals_from_raw(result_bi)
Some(ManagedDecimal::const_decimals_from_raw(result_bi))
}
}

Expand Down
4 changes: 4 additions & 0 deletions framework/base/src/types/managed/wrapped/managed_decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ impl<M: ManagedTypeApi, D: Decimals> ManagedDecimal<M, D> {
self.decimals.num_decimals()
}

pub fn scaling_factor(&self) -> ManagedRef<'static, M, BigUint<M>> {
self.decimals.scaling_factor()
}

pub fn rescale<T: Decimals>(self, scale_to: T) -> ManagedDecimal<M, T>
where
M: ManagedTypeApi,
Expand Down
3 changes: 2 additions & 1 deletion tools/plotter/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
[package]
name = "wasm-demo"
name = "sc-plotter-wasm"
version = "0.1.0"
authors = ["Hao Hou <haohou302@gmail.com>"]
edition = "2018"
publish = false

[lib]
crate-type=["cdylib"]
Expand Down
4 changes: 3 additions & 1 deletion tools/plotter/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#![allow(clippy::type_complexity)]

use wasm_bindgen::prelude::*;
use web_sys::HtmlCanvasElement;

mod func_plot;
pub mod logarithm;
mod plot3d;
mod logarithm;

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
Expand Down
33 changes: 29 additions & 4 deletions tools/plotter/src/logarithm.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
use crate::DrawResult;
use multiversx_sc::types::BigUint;
use multiversx_sc_scenario::api::StaticApi;
use plotters::prelude::*;
use plotters_canvas::CanvasBackend;
use web_sys::HtmlCanvasElement;

pub fn draw(canvas: HtmlCanvasElement, max_x: f32) -> DrawResult<impl Fn((i32, i32)) -> Option<(f32, f32)>> {
pub fn draw(
canvas: HtmlCanvasElement,
max_x: f32,
) -> DrawResult<impl Fn((i32, i32)) -> Option<(f32, f32)>> {
let root = CanvasBackend::with_canvas_object(canvas)
.unwrap()
.into_drawing_area();

let font: FontDesc = ("sans-serif", 20.0).into();

root.fill(&WHITE)?;
Expand All @@ -17,7 +22,7 @@ pub fn draw(canvas: HtmlCanvasElement, max_x: f32) -> DrawResult<impl Fn((i32, i
.caption(format!("y=ln(x), x=1..{max_x}"), font)
.x_label_area_size(30u32)
.y_label_area_size(30u32)
.build_cartesian_2d(0f32..max_x, -10f32..10f32)?;
.build_cartesian_2d(0f32..max_x, -1f32..5f32)?;

chart.configure_mesh().x_labels(3).y_labels(3).draw()?;

Expand All @@ -32,10 +37,30 @@ pub fn draw(canvas: HtmlCanvasElement, max_x: f32) -> DrawResult<impl Fn((i32, i
chart.draw_series(LineSeries::new(
(0..=RANGE_MAX)
.map(|x| x as f32 * max_x / RANGE_MAX as f32)
.map(|x| (x, x.log2())),
.map(|x| (x, sc_ln(x))),
&GREEN,
))?;

root.present()?;
return Ok(chart.into_coord_trans());
}

pub fn sc_ln(x: f32) -> f32 {
let bu = BigUint::<StaticApi>::from(x as u32);
if let Some(ln_dec) = bu.ln() {
let ln_units = ln_dec.into_raw_units().to_u64().unwrap();
let ln_sf = ln_dec.scaling_factor().to_u64().unwrap();
(ln_units as f64 / ln_sf as f64) as f32
} else {
0.0
}
}

#[cfg(test)]
mod test {
#[test]
fn sc_ln_test() {
let y = super::sc_ln(0.0);
println!("{y}");
}
}
2 changes: 1 addition & 1 deletion tools/plotter/src/plot3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn draw(canvas: HtmlCanvasElement, pitch: f64, yaw: f64) -> DrawResult<()> {
chart.configure_axes().draw()?;

chart.draw_series(
SurfaceSeries::xoz(x_axis.values(), z_axis.values(), |x:f64, z:f64| {
SurfaceSeries::xoz(x_axis.values(), z_axis.values(), |x: f64, z: f64| {
(x * x + z * z).cos()
})
.style(&BLUE.mix(0.2)),
Expand Down
8 changes: 1 addition & 7 deletions tools/plotter/www/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,6 @@ function updatePlot3d() {
coord.innerText = `Pitch:${pitch_value}, Yaw:${yaw_value}`
}

function updateLogarithm() {
}

/** Redraw currently selected plot. */
function updatePlot() {
const selected = plotType.selectedOptions[0];
Expand All @@ -94,11 +91,8 @@ function updatePlot() {
case "logarithm":
control.classList.add("hide");
logControl.classList.remove("hide");
updateLogarithm();
let logMaxValue = Number(logMax.value);
status.innerText = `Updated log: ${logMaxValue}`
chart = Chart.logarithm(canvas, Number(logMaxValue));
coord.innerText = `Updated log: ${logMaxValue}`
break;
case "3d-plot":
control.classList.remove("hide");
Expand All @@ -112,5 +106,5 @@ function updatePlot() {
}

const end = performance.now();
// status.innerText = `Rendered ${selected.innerText} in ${Math.ceil(end - start)}ms`;
status.innerText = `Rendered ${selected.innerText} in ${Math.ceil(end - start)}ms`;
}
2 changes: 1 addition & 1 deletion vm/src/tx_mock/blockchain_rng_unsupported.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub struct BlockchainRng;

impl BlockchainRng {
pub fn new(_tx_input: &TxInput, _tx_cache: &TxCache) -> Self {
panic!("BlockchainRng not supported for wasm builds, feature `wasm-incopatible` needs to be enabled")
BlockchainRng
}

pub fn next_bytes(&mut self, _length: usize) -> Vec<u8> {
Expand Down

0 comments on commit 3598efb

Please sign in to comment.