eaebec39创建于 2024年10月24日历史提交
package scientific.matplot

import std.math.*
import std.unittest.*
import std.unittest.testmacro.*

import scientific.numbers.*
import scientific.linear.*
import scientific.stats.random.*
import scientific.stats.normal.*

/* Type for x and y: Float64 */
foreign func c_plotmatrix(
    x: CPointer<Unit>, x_row: Int64, x_col: Int64,
    y: CPointer<Unit>, y_row: Int64, y_col: Int64, line_spec: CString): Unit

foreign func c_plotmatrix_x(
    x: CPointer<Unit>, x_row: Int64, x_col: Int64,line_spec: CString): Unit

public func plotmatrix(x: Matrix<Float64>, y: Matrix<Float64>, line_spec!:String = "") {
    let x_row = x.getRows()
    let x_col = x.getCols()
    let y_row = y.getRows()
    let y_col = y.getCols()
    var cstr_line_spec = unsafe { LibC.mallocCString(line_spec) }
    unsafe { c_plotmatrix(x.ptr, x_row, x_col, y.ptr, y_row, y_col, cstr_line_spec) }
    unsafe { LibC.free(cstr_line_spec) }
}

public func plotmatrix(x: Matrix<Float64>, line_spec!:String = "") {
    let x_row = x.getRows()
    let x_col = x.getCols()
    var cstr_line_spec = unsafe { LibC.mallocCString(line_spec) }
    unsafe { c_plotmatrix_x(x.ptr, x_row, x_col, cstr_line_spec) }
    unsafe { LibC.free(cstr_line_spec) }
}

public func testPlotMatrix1() {
    var m: Random = Random(1)

    let X = empty<Float64>(3, 50)
    X[0] = randn(m, 50, 0.0, 1.0)
    X[1] = randn(m, 50, 0.0, 1.0)
    X[2] = randn(m, 50, 0.0, 1.0)

    let Y = empty<Float64>(3, 50)
    Y[0] = linspace(1.0, 50.0, num:50)
    Y[1] = linspace(51.0, 100.0, num:50)
    Y[2] = linspace(101.0, 150.0, num:50)

    plotmatrix(X, Y)

    save("./tests/imgs/plot_matrix/plot_matrix_1.png", "png")
    clear()
}

public func testPlotMatrix2() {
    var m: Random = Random(1)

    let X = empty<Float64>(3, 200)
    X[0] = randn(m, 200, 0.0, 1.0)
    X[1] = randn(m, 200, 0.0, 1.0)
    X[2] = randn(m, 200, 0.0, 1.0)

    plotmatrix(X)

    save("./tests/imgs/plot_matrix/plot_matrix_2.png", "png")
    clear()
}

public func testPlotMatrix3() {
    var m: Random = Random(1)

    let X = empty<Float64>(3, 200)
    X[0] = randn(m, 200, 0.0, 1.0)
    X[1] = randn(m, 200, 0.0, 1.0)
    X[2] = randn(m, 200, 0.0, 1.0)

    plotmatrix(X, line_spec: "*r")

    save("./tests/imgs/plot_matrix/plot_matrix_3.png", "png")
    clear()
}


public func testPlotMatrix() {
    print("  + testPlotMatrix\n")
    testPlotMatrix1()
    testPlotMatrix2()
    testPlotMatrix3()
}