The Kitchen Sink and Other Oddities

Atabey Kaygun

Uniform Sampling from Parametrized Submanifolds in Scala

Here is the code for yesterday’s post but written in scala language instead of lisp.

import scala.collection.immutable

def writeSampleToFile(n: Int, fn: () => IndexedSeq[Double], filename:String) = {
  val      out = new java.io.PrintWriter(filename)
  val mySample = (1 to n) map (x => fn())

  for(point <- mySample) 
     out.println(point.foldLeft("")( (a,b) => "%s %4.3f " format(a,b) ))

  out.close
}


def sampleFromSimplex() = {
  val x = math.sqrt(math.random)
  val y = math.random

  IndexedSeq(x*y,x-x*y,1-x)
}


def sampleFromSphere() = {
  val   rho = math.pow(math.random,1/3)
  val   phi = math.acos(2*(math.random - 0.5))
  val theta = 2*math.Pi*math.random

  IndexedSeq(rho*math.cos(theta)*math.sin(phi),
             rho*math.sin(theta)*math.sin(phi),
             rho*math.cos(phi))
}


def sampleFromTorus(a:Double, b:Double) = {
  val theta = 2*math.Pi*math.random
  val   phi = 2*math.Pi*math.random
  val   rho = a + b*math.cos(theta)

  IndexedSeq(rho*math.cos(phi),
             rho*math.sin(phi),
             rho*math.sin(theta))
} 

writeSampleToFile(400,sampleFromSimplex,"./simplex.csv")
writeSampleToFile(400,sampleFromSphere,"./sphere.csv")
writeSampleToFile(2000,(()=>sampleFromTorus(6.0,1.0)),"./torus-large.csv")
writeSampleToFile(2000,(()=>sampleFromTorus(2.1,1.0)),"./torus-small.csv")