Skip to content

Commit

Permalink
[LINALG] Implicits for scala scalar op matrix/vector operations.
Browse files Browse the repository at this point in the history
Allows user to write vector/matrix operations with scala primitives
as first operand, e.g. 1.0 * Matrix
  • Loading branch information
akunft committed Apr 29, 2016
1 parent 1937a9b commit da06d95
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package eu.stratosphere.emma.api

import spire.math._

import scala.reflect.ClassTag

package object lara {

implicit class VectorOps[A: Numeric : ClassTag](private val n: A) {
def +(v: Vector[A]): Vector[A] = v + n

def -(v: Vector[A]): Vector[A] = v - n

def *(v: Vector[A]): Vector[A] = v * n

def /(v: Vector[A]): Vector[A] = v / n
}

implicit class MatrixOps[A: Numeric : ClassTag](private val n: A) {
def +(v: Matrix[A]): Matrix[A] = v + n

def -(v: Matrix[A]): Matrix[A] = v - n

def *(v: Matrix[A]): Matrix[A] = v * n

def /(v: Matrix[A]): Matrix[A] = v / n
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package eu.stratosphere.emma.api.lara

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class ImplicitsTest extends BaseTest {

val vDouble = Vector(Array(1.0, 2.0, 3.0, 4.0))
val vInt = Vector(1 to 10)

val mDouble = Matrix(2, 2, Array(1.0, 2.0, 3.0, 4.0))
val mInt = Matrix(2, 2, Array(1, 2, 3, 4))

"Scalar op Vector" - {
"+" in {
val res = 2.0 + vDouble
res shouldBe vDouble.map(e => e + 2)

val res2 = 2 + vInt
res2 shouldBe vInt.map(e => e + 2)
}
"-" in {
val res = 2.0 - vDouble
res shouldBe vDouble.map(e => e - 2)

val res2 = 2 - vInt
res2 shouldBe vInt.map(e => e - 2)
}
"*" in {
val res = 2.0 * vDouble
res shouldBe vDouble.map(e => e * 2)

val res2 = 2 * vInt
res2 shouldBe vInt.map(e => e * 2)
}
"/" in {
val res = 2.0 / vDouble
res shouldBe vDouble.map(e => e / 2)

val res2 = 2 / vInt
res2 shouldBe vInt.map(e => e / 2)
}
}

"Scalar op Matrix" - {
"+" in {
val res = 2.0 + mDouble
res shouldBe mDouble.map(e => e + 2)

val res2 = 2 + mInt
res2 shouldBe mInt.map(e => e + 2)
}
"-" in {
val res = 2.0 - mDouble
res shouldBe mDouble.map(e => e - 2)

val res2 = 2 - mInt
res2 shouldBe mInt.map(e => e - 2)
}
"*" in {
val res = 2.0 * mDouble
res shouldBe mDouble.map(e => e * 2)

val res2 = 2 * mInt
res2 shouldBe mInt.map(e => e * 2)
}
"/" in {
val res = 2.0 / mDouble
res shouldBe mDouble.map(e => e / 2)

val res2 = 2 / mInt
res2 shouldBe mInt.map(e => e / 2)
}
}
}

0 comments on commit da06d95

Please sign in to comment.