Skip to content

Commit

Permalink
scala 3 code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
darrenjw committed Dec 29, 2024
1 parent dae5c99 commit 5f0aa5c
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 136 deletions.
2 changes: 1 addition & 1 deletion .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
version = 3.8.3
runner.dialect = scala213
runner.dialect = scala3
1 change: 0 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ libraryDependencies ++= Seq(
("org.ddahl" %% "rscala" % "3.2.19").cross(CrossVersion.for3Use2_13)
)


mdocIn := file("mdoc/")

mdocOut := file("docs/")
Expand Down
83 changes: 41 additions & 42 deletions examples/src/main/scala/FBm.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,47 @@ Fractional Brownian motion via and inverse Discrete Cosine Transform (DCT)

import scalaglm.Utils.*

import breeze.linalg.*
import breeze.numerics.*
import breeze.stats.distributions.*
import breeze.stats.distributions.Rand.VariableSeed.randBasis
import java.awt.image.BufferedImage

def dm2bi(m: DenseMatrix[Double]): BufferedImage =
val canvas = new BufferedImage(m.cols, m.rows, BufferedImage.TYPE_INT_RGB)
val wr = canvas.getRaster
val mx = max(m)
val mn = min(m)
(0 until m.cols).foreach { x =>
(0 until m.rows).foreach { y =>
val shade = round(255 * (m(y, x) - mn) / (mx - mn)).toInt
wr.setSample(x, y, 0, shade) // R
wr.setSample(x, y, 1, shade) // G
wr.setSample(x, y, 2, 255) // B
}
import breeze.linalg.*
import breeze.numerics.*
import breeze.stats.distributions.*
import breeze.stats.distributions.Rand.VariableSeed.randBasis
import java.awt.image.BufferedImage

def dm2bi(m: DenseMatrix[Double]): BufferedImage =
val canvas = new BufferedImage(m.cols, m.rows, BufferedImage.TYPE_INT_RGB)
val wr = canvas.getRaster
val mx = max(m)
val mn = min(m)
(0 until m.cols).foreach { x =>
(0 until m.rows).foreach { y =>
val shade = round(255 * (m(y, x) - mn) / (mx - mn)).toInt
wr.setSample(x, y, 0, shade) // R
wr.setSample(x, y, 1, shade) // G
wr.setSample(x, y, 2, 255) // B
}
canvas

def showImage(m: DenseMatrix[Double]): Unit =
import breeze.plot.*
val fig = Figure("fBm")
fig.width = 1200
fig.height = 1200
val p0 = fig.subplot(0)
p0 += image(m)
fig.refresh()

@main def fBmSim() =
val N = 1024
val H = 0.9
val sd = DenseMatrix.tabulate(N, N){(j, k) =>
if (j*j + k*k < 9) 0.0 else
math.pow(j*j + k*k, -(H + 1)/2) }
val M = sd map (s => Gaussian(0.0, s).draw())
val m = dct2(M, true)
javax.imageio.ImageIO.write(dm2bi(m), "png", new java.io.File("fBm.png"))
showImage(m)


}
canvas

def showImage(m: DenseMatrix[Double]): Unit =
import breeze.plot.*
val fig = Figure("fBm")
fig.width = 1200
fig.height = 1200
val p0 = fig.subplot(0)
p0 += image(m)
fig.refresh()

@main def fBmSim() =
val N = 1024
val H = 0.9
val sd = DenseMatrix.tabulate(N, N) { (j, k) =>
if (j * j + k * k < 9) 0.0
else
math.pow(j * j + k * k, -(H + 1) / 2)
}
val M = sd map (s => Gaussian(0.0, s).draw())
val m = dct2(M, true)
javax.imageio.ImageIO.write(dm2bi(m), "png", new java.io.File("fBm.png"))
showImage(m)

// eof

118 changes: 65 additions & 53 deletions examples/src/main/scala/IrisPca.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,64 +9,76 @@ import scalaglm.*

@main def irisPca() =

val url = "http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
val fileName = "iris.csv"
val imap = Map(
"Iris-setosa" -> 0,
"Iris-versicolor" -> 1,
"Iris-virginica" -> 2)
val url =
"http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
val fileName = "iris.csv"
val imap =
Map("Iris-setosa" -> 0, "Iris-versicolor" -> 1, "Iris-virginica" -> 2)

// download the file to disk if it hasn't been already
val file = new java.io.File(fileName)
if !file.exists then
val s = new java.io.PrintWriter(file)
val data = scala.io.Source.fromURL(url).getLines()
data.foreach(l => s.write(l.trim.split(',').
map(x => imap.getOrElse(x, x)).mkString("", ",", "\n")))
s.close
// download the file to disk if it hasn't been already
val file = new java.io.File(fileName)
if !file.exists then
val s = new java.io.PrintWriter(file)
val data = scala.io.Source.fromURL(url).getLines()
data.foreach(l =>
s.write(
l.trim.split(',').map(x => imap.getOrElse(x, x)).mkString("", ",", "\n")
)
)
s.close

// read the file from disk
val mat = csvread(file)
println("Mat Dim: " + mat.rows + " " + mat.cols)
val x = mat(::, 0 to 3)
println("X Dim: " + x.rows + " " + x.cols)
val clas = mat(::, 4).toDenseVector
// read the file from disk
val mat = csvread(file)
println("Mat Dim: " + mat.rows + " " + mat.cols)
val x = mat(::, 0 to 3)
println("X Dim: " + x.rows + " " + x.cols)
val clas = mat(::, 4).toDenseVector

println("PCA with built-in Breeze version (like R princomp):")
val pca = new PCA(x, covmat(x))
println("Loadings:")
println(pca.loadings)
println("Stdev:")
println(pca.sdev)
println(pca.scores(0 to 5, ::))
println("PCA with built-in Breeze version (like R princomp):")
val pca = new PCA(x, covmat(x))
println("Loadings:")
println(pca.loadings)
println("Stdev:")
println(pca.sdev)
println(pca.scores(0 to 5, ::))

println("Now my version (like R prcomp):")
val myPca = Pca(x, List("S-L","S-W","P-L","P-W"))
println(myPca.loadings) // loadings transposed
println(myPca.sdev)
myPca.summary
println("Scores:")
println(myPca.scores(0 to 5, ::))
myPca.plots.saveas("IrisPcaDiag.png")
println("Now my version (like R prcomp):")
val myPca = Pca(x, List("S-L", "S-W", "P-L", "P-W"))
println(myPca.loadings) // loadings transposed
println(myPca.sdev)
myPca.summary
println("Scores:")
println(myPca.scores(0 to 5, ::))
myPca.plots.saveas("IrisPcaDiag.png")

// scatter plot first 2 principal components
import breeze.plot.*
val fig = Figure("PCA")
val p = fig.subplot(0)
val ind0 = (0 until x.rows) filter (i => clas(i) == 0)
p += plot(myPca.scores(ind0, 0).toDenseVector,
myPca.scores(ind0, 1).toDenseVector, '.', colorcode = "blue")
val ind1 = (0 until x.rows) filter (i => clas(i) == 1)
p += plot(myPca.scores(ind1, 0).toDenseVector,
myPca.scores(ind1, 1).toDenseVector, '.', colorcode = "red")
val ind2 = (0 until x.rows) filter (i => clas(i) == 2)
p += plot(myPca.scores(ind2, 0).toDenseVector,
myPca.scores(ind2, 1).toDenseVector, '.', colorcode = "green")
fig.saveas("IrisPca.png")

// Test without variable names
Pca(x).summary
// scatter plot first 2 principal components
import breeze.plot.*
val fig = Figure("PCA")
val p = fig.subplot(0)
val ind0 = (0 until x.rows) filter (i => clas(i) == 0)
p += plot(
myPca.scores(ind0, 0).toDenseVector,
myPca.scores(ind0, 1).toDenseVector,
'.',
colorcode = "blue"
)
val ind1 = (0 until x.rows) filter (i => clas(i) == 1)
p += plot(
myPca.scores(ind1, 0).toDenseVector,
myPca.scores(ind1, 1).toDenseVector,
'.',
colorcode = "red"
)
val ind2 = (0 until x.rows) filter (i => clas(i) == 2)
p += plot(
myPca.scores(ind2, 0).toDenseVector,
myPca.scores(ind2, 1).toDenseVector,
'.',
colorcode = "green"
)
fig.saveas("IrisPca.png")

// Test without variable names
Pca(x).summary

// eof

54 changes: 28 additions & 26 deletions examples/src/main/scala/LinearRegression.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,31 +10,33 @@ import breeze.linalg.*

@main def linearRegression() =

val url = "http://archive.ics.uci.edu/ml/machine-learning-databases/00291/airfoil_self_noise.dat"
val fileName = "self-noise.csv"

// download the file to disk if it hasn't been already
val file = new java.io.File(fileName)
if !file.exists then
val s = new java.io.PrintWriter(file)
val data = scala.io.Source.fromURL(url).getLines()
data.foreach(l => s.write(l.trim.split('\t').filter(_ != "").mkString("", ",", "\n")))
s.close

// read the file from disk
val mat = csvread(file)
println("Dim: " + mat.rows + " " + mat.cols)
val fig = Utils.pairs(mat, List("Freq", "Angle", "Chord", "Velo", "Thick", "Sound"))
val y = mat(::, 5) // response is the final column
val X = mat(::, 0 to 4)
val mod = Lm(y, X, List("Freq", "Angle", "Chord", "Velo", "Thick"))
mod.summary
mod.plots.saveas("LinearRegression.png")

// test without name list
Lm(y,X,false).summary
Lm(y,X).summary

val url =
"http://archive.ics.uci.edu/ml/machine-learning-databases/00291/airfoil_self_noise.dat"
val fileName = "self-noise.csv"

// download the file to disk if it hasn't been already
val file = new java.io.File(fileName)
if !file.exists then
val s = new java.io.PrintWriter(file)
val data = scala.io.Source.fromURL(url).getLines()
data.foreach(l =>
s.write(l.trim.split('\t').filter(_ != "").mkString("", ",", "\n"))
)
s.close

// read the file from disk
val mat = csvread(file)
println("Dim: " + mat.rows + " " + mat.cols)
val fig =
Utils.pairs(mat, List("Freq", "Angle", "Chord", "Velo", "Thick", "Sound"))
val y = mat(::, 5) // response is the final column
val X = mat(::, 0 to 4)
val mod = Lm(y, X, List("Freq", "Angle", "Chord", "Velo", "Thick"))
mod.summary
mod.plots.saveas("LinearRegression.png")

// test without name list
Lm(y, X, false).summary
Lm(y, X).summary

// eof

9 changes: 4 additions & 5 deletions examples/src/main/scala/LogisticRegression.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@ import breeze.linalg.*

@main def logisticRegression() =

val url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00267/data_banknote_authentication.txt"
val url =
"https://archive.ics.uci.edu/ml/machine-learning-databases/00267/data_banknote_authentication.txt"
val fileName = "banknote.csv"

// download the file to disk if it hasn't been already
val file = new java.io.File(fileName)
if !file.exists then
val s = new java.io.PrintWriter(file)
val data = scala.io.Source.fromURL(url).getLines()
data.foreach(l => s.write(l+"\n"))
data.foreach(l => s.write(l + "\n"))
s.close

// read the file from disk
Expand All @@ -27,10 +28,8 @@ import breeze.linalg.*
val y = mat(::, 4) // response is the final column
val X = mat(::, 0 to 3)
// println(y)
val mod = Glm(y, X, List("Var","Skew","Kurt","Entropy"), LogisticGlm)
val mod = Glm(y, X, List("Var", "Skew", "Kurt", "Entropy"), LogisticGlm)
// println(mod.coefficients)
mod.summary


// eof

12 changes: 4 additions & 8 deletions examples/src/main/scala/PolyFit.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,33 @@ PolyFit.scala
*/


import breeze.linalg.*
import breeze.numerics.*
import breeze.stats.distributions.Gaussian
import breeze.stats.distributions.Rand.VariableSeed.randBasis
import scalaglm.*


@main def polyFit() =

// simulate some synthetic data
val n = 500
val x = linspace(2.0, 5.0, n)
val yt = 0.5*x + sin(x*x)
val yt = 0.5 * x + sin(x * x)
val y = yt + DenseVector(Gaussian(0.0, 1.0).sample(n).toArray)

// scatter plot
import breeze.plot.*
val fig = Figure("Synthetic data")
val p = fig.subplot(0)
p += plot(x, y, '+', name="Data")
p += plot(x, yt, name="Truth")
p += plot(x, y, '+', name = "Data")
p += plot(x, yt, name = "Truth")

// some polynomial fits
(1 to 17 by 4).foreach(i =>
val lm = Lm(y, Basis.poly(x, i))
p += plot(x, lm.fitted, name="P"+i)
p += plot(x, lm.fitted, name = "P" + i)
)
p.legend = true
p.title = "Polynomial fits"


// eof

0 comments on commit 5f0aa5c

Please sign in to comment.