Compare commits
No commits in common. "scalashop" and "actorbintree" have entirely different histories.
scalashop
...
actorbintr
@ -25,7 +25,7 @@ grade:
|
|||||||
tags:
|
tags:
|
||||||
- cs206
|
- cs206
|
||||||
image:
|
image:
|
||||||
name: smarter3/moocs:parprog1-scalashop-2020-02-17
|
name: smarter3/moocs:reactive-actorbintree-2020-04-15
|
||||||
entrypoint: [""]
|
entrypoint: [""]
|
||||||
allow_failure: true
|
allow_failure: true
|
||||||
before_script:
|
before_script:
|
||||||
|
|||||||
@ -1,9 +1,4 @@
|
|||||||
// Student tasks (i.e. submit, packageSubmission)
|
// Student tasks (i.e. submit, packageSubmission)
|
||||||
enablePlugins(StudentTasks)
|
enablePlugins(StudentTasks)
|
||||||
|
|
||||||
courseraId := ch.epfl.lamp.CourseraId(
|
|
||||||
key = "OpSNmtC1EeWvXAr2bF16EQ",
|
|
||||||
itemId = "MhXvy",
|
|
||||||
premiumItemId = Some("NeGTv"),
|
|
||||||
partId = "Q2e1P"
|
|
||||||
)
|
|
||||||
|
|||||||
33
build.sbt
33
build.sbt
@ -1,13 +1,24 @@
|
|||||||
course := "parprog1"
|
course := "reactive"
|
||||||
assignment := "scalashop"
|
assignment := "actorbintree"
|
||||||
|
|
||||||
scalaVersion := "0.23.0-bin-20200211-5b006fb-NIGHTLY"
|
|
||||||
scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
|
|
||||||
libraryDependencies ++= Seq(
|
|
||||||
"com.storm-enroute" %% "scalameter-core" % "0.19",
|
|
||||||
"org.scala-lang.modules" %% "scala-parallel-collections" % "0.2.0",
|
|
||||||
"com.novocode" % "junit-interface" % "0.11" % Test
|
|
||||||
).map(_.withDottyCompat(scalaVersion.value))
|
|
||||||
|
|
||||||
testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s")
|
testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s")
|
||||||
testSuite := "scalashop.BlurSuite"
|
parallelExecution in Test := false
|
||||||
|
|
||||||
|
val akkaVersion = "2.6.0"
|
||||||
|
|
||||||
|
scalaVersion := "0.23.0-bin-20200211-5b006fb-NIGHTLY"
|
||||||
|
|
||||||
|
scalacOptions ++= Seq(
|
||||||
|
"-feature",
|
||||||
|
"-deprecation",
|
||||||
|
"-encoding", "UTF-8",
|
||||||
|
"-unchecked",
|
||||||
|
"-language:implicitConversions"
|
||||||
|
)
|
||||||
|
|
||||||
|
libraryDependencies ++= Seq(
|
||||||
|
"com.typesafe.akka" %% "akka-actor" % akkaVersion,
|
||||||
|
"com.typesafe.akka" %% "akka-testkit" % akkaVersion % Test,
|
||||||
|
"com.novocode" % "junit-interface" % "0.11" % Test
|
||||||
|
).map(_.withDottyCompat(scalaVersion.value))
|
||||||
|
testSuite := "actorbintree.BinaryTreeSuite"
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 118 KiB |
189
src/main/scala/actorbintree/BinaryTreeSet.scala
Normal file
189
src/main/scala/actorbintree/BinaryTreeSet.scala
Normal file
@ -0,0 +1,189 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
|
||||||
|
*/
|
||||||
|
package actorbintree
|
||||||
|
|
||||||
|
import akka.actor._
|
||||||
|
import scala.collection.immutable.Queue
|
||||||
|
|
||||||
|
object BinaryTreeSet {
|
||||||
|
|
||||||
|
trait Operation {
|
||||||
|
def requester: ActorRef
|
||||||
|
def id: Int
|
||||||
|
def elem: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
trait OperationReply {
|
||||||
|
def id: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Request with identifier `id` to insert an element `elem` into the tree.
|
||||||
|
* The actor at reference `requester` should be notified when this operation
|
||||||
|
* is completed.
|
||||||
|
*/
|
||||||
|
case class Insert(requester: ActorRef, id: Int, elem: Int) extends Operation
|
||||||
|
|
||||||
|
/** Request with identifier `id` to check whether an element `elem` is present
|
||||||
|
* in the tree. The actor at reference `requester` should be notified when
|
||||||
|
* this operation is completed.
|
||||||
|
*/
|
||||||
|
case class Contains(requester: ActorRef, id: Int, elem: Int) extends Operation
|
||||||
|
|
||||||
|
/** Request with identifier `id` to remove the element `elem` from the tree.
|
||||||
|
* The actor at reference `requester` should be notified when this operation
|
||||||
|
* is completed.
|
||||||
|
*/
|
||||||
|
case class Remove(requester: ActorRef, id: Int, elem: Int) extends Operation
|
||||||
|
|
||||||
|
/** Request to perform garbage collection */
|
||||||
|
case object GC
|
||||||
|
|
||||||
|
/** Holds the answer to the Contains request with identifier `id`.
|
||||||
|
* `result` is true if and only if the element is present in the tree.
|
||||||
|
*/
|
||||||
|
case class ContainsResult(id: Int, result: Boolean) extends OperationReply
|
||||||
|
|
||||||
|
/** Message to signal successful completion of an insert or remove operation. */
|
||||||
|
case class OperationFinished(id: Int) extends OperationReply
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BinaryTreeSet extends Actor {
|
||||||
|
import BinaryTreeSet._
|
||||||
|
import BinaryTreeNode._
|
||||||
|
|
||||||
|
def createRoot: ActorRef = context.actorOf(BinaryTreeNode.props(0, initiallyRemoved = true))
|
||||||
|
|
||||||
|
var root = createRoot
|
||||||
|
|
||||||
|
// optional
|
||||||
|
var pendingQueue = Queue.empty[Operation]
|
||||||
|
|
||||||
|
// optional
|
||||||
|
def receive = normal
|
||||||
|
|
||||||
|
// optional
|
||||||
|
/** Accepts `Operation` and `GC` messages. */
|
||||||
|
val normal: Receive = {
|
||||||
|
case op:Operation => root ! op
|
||||||
|
case GC => {
|
||||||
|
val newRoot = createRoot;
|
||||||
|
root ! CopyTo(newRoot)
|
||||||
|
context.become(garbageCollecting(newRoot))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// optional
|
||||||
|
/** Handles messages while garbage collection is performed.
|
||||||
|
* `newRoot` is the root of the new binary tree where we want to copy
|
||||||
|
* all non-removed elements into.
|
||||||
|
*/
|
||||||
|
def garbageCollecting(newRoot: ActorRef): Receive = {
|
||||||
|
case op:Operation => pendingQueue = pendingQueue.enqueue(op)
|
||||||
|
case CopyFinished =>
|
||||||
|
pendingQueue.foreach(newRoot ! _) //foreach preserves order of a queue (same as dequeueing)
|
||||||
|
root ! PoisonPill //Will also stop all of its children
|
||||||
|
pendingQueue = Queue.empty
|
||||||
|
root = newRoot;
|
||||||
|
context.become(normal)
|
||||||
|
//Ignore GC messages here
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object BinaryTreeNode {
|
||||||
|
trait Position
|
||||||
|
|
||||||
|
case object Left extends Position
|
||||||
|
case object Right extends Position
|
||||||
|
|
||||||
|
case class CopyTo(treeNode: ActorRef)
|
||||||
|
case object CopyFinished
|
||||||
|
|
||||||
|
def props(elem: Int, initiallyRemoved: Boolean) = Props(classOf[BinaryTreeNode], elem, initiallyRemoved)
|
||||||
|
}
|
||||||
|
|
||||||
|
class BinaryTreeNode(val elem: Int, initiallyRemoved: Boolean) extends Actor {
|
||||||
|
import BinaryTreeNode._
|
||||||
|
import BinaryTreeSet._
|
||||||
|
|
||||||
|
var subtrees = Map[Position, ActorRef]()
|
||||||
|
var removed = initiallyRemoved
|
||||||
|
|
||||||
|
// optional
|
||||||
|
def receive = normal
|
||||||
|
|
||||||
|
def goDownTo(elem : Int) : Position = if(elem < this.elem) Left else Right
|
||||||
|
// optional
|
||||||
|
/** Handles `Operation` messages and `CopyTo` requests. */
|
||||||
|
val normal: Receive = {
|
||||||
|
case Insert (requester, id, elem) =>
|
||||||
|
if(elem == this.elem && !removed){
|
||||||
|
requester ! OperationFinished(id)
|
||||||
|
}else{
|
||||||
|
val nextPos = goDownTo(elem)
|
||||||
|
|
||||||
|
subtrees get nextPos match{
|
||||||
|
case Some(node) => node ! Insert(requester, id, elem)
|
||||||
|
case None => {
|
||||||
|
val newActorSubtree = (nextPos, context.actorOf(BinaryTreeNode.props(elem, false)))
|
||||||
|
subtrees = subtrees + newActorSubtree
|
||||||
|
requester ! OperationFinished(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case Contains(requester, id, elem) =>
|
||||||
|
if(elem == this.elem && !removed)
|
||||||
|
requester ! ContainsResult(id, true)
|
||||||
|
else{
|
||||||
|
//Need to search subtrees
|
||||||
|
subtrees get goDownTo(elem) match{
|
||||||
|
case Some(node) => node ! Contains(requester, id, elem)
|
||||||
|
case None => requester ! ContainsResult(id, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case Remove (requester, id, elem) =>
|
||||||
|
if(elem == this.elem && !removed){
|
||||||
|
removed = true
|
||||||
|
requester ! OperationFinished(id)
|
||||||
|
}else{
|
||||||
|
subtrees get goDownTo(elem) match{
|
||||||
|
case Some(node) => node ! Remove(requester, id, elem)
|
||||||
|
case None => requester ! OperationFinished(id) // (elem isn't in the tree)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case CopyTo(newRoot) =>
|
||||||
|
//We are already done, nothing to do
|
||||||
|
if(removed && subtrees.isEmpty) context.parent ! CopyFinished
|
||||||
|
else{
|
||||||
|
if(!removed) newRoot ! Insert(self, elem, elem)
|
||||||
|
subtrees.values foreach(_ ! CopyTo(newRoot)) //Copy subtrees elems
|
||||||
|
//val insertConfirmed = if(removed) true else false, hence we can simply pass removed
|
||||||
|
context.become(copying(subtrees.values.toSet, removed))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// optional
|
||||||
|
/** `expected` is the set of ActorRefs whose replies we are waiting for,
|
||||||
|
* `insertConfirmed` tracks whether the copy of this node to the new tree has been confirmed.
|
||||||
|
*/
|
||||||
|
def copying(expected: Set[ActorRef], insertConfirmed: Boolean): Receive = {
|
||||||
|
//To catch the insert of this node into the new tree beeing finished
|
||||||
|
case OperationFinished(_) => {
|
||||||
|
if(expected.isEmpty) context.parent ! CopyFinished
|
||||||
|
else context.become(copying(expected, true))
|
||||||
|
}
|
||||||
|
|
||||||
|
case CopyFinished => {
|
||||||
|
val newExp = expected-sender
|
||||||
|
if(insertConfirmed && newExp.isEmpty){
|
||||||
|
context.parent ! CopyFinished
|
||||||
|
}else{
|
||||||
|
context.become(copying(newExp, insertConfirmed))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,65 +0,0 @@
|
|||||||
package scalashop
|
|
||||||
|
|
||||||
import org.scalameter._
|
|
||||||
|
|
||||||
object HorizontalBoxBlurRunner {
|
|
||||||
|
|
||||||
val standardConfig = config(
|
|
||||||
Key.exec.minWarmupRuns -> 5,
|
|
||||||
Key.exec.maxWarmupRuns -> 10,
|
|
||||||
Key.exec.benchRuns -> 10,
|
|
||||||
Key.verbose -> true
|
|
||||||
) withWarmer(new Warmer.Default)
|
|
||||||
|
|
||||||
def main(args: Array[String]): Unit = {
|
|
||||||
val radius = 3
|
|
||||||
val width = 1920
|
|
||||||
val height = 1080
|
|
||||||
val src = new Img(width, height)
|
|
||||||
val dst = new Img(width, height)
|
|
||||||
val seqtime = standardConfig measure {
|
|
||||||
HorizontalBoxBlur.blur(src, dst, 0, height, radius)
|
|
||||||
}
|
|
||||||
println(s"sequential blur time: $seqtime")
|
|
||||||
|
|
||||||
val numTasks = 32
|
|
||||||
val partime = standardConfig measure {
|
|
||||||
HorizontalBoxBlur.parBlur(src, dst, numTasks, radius)
|
|
||||||
}
|
|
||||||
println(s"fork/join blur time: $partime")
|
|
||||||
println(s"speedup: ${seqtime.value / partime.value}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A simple, trivially parallelizable computation. */
|
|
||||||
object HorizontalBoxBlur extends HorizontalBoxBlurInterface {
|
|
||||||
|
|
||||||
/** Blurs the rows of the source image `src` into the destination image `dst`,
|
|
||||||
* starting with `from` and ending with `end` (non-inclusive).
|
|
||||||
*
|
|
||||||
* Within each row, `blur` traverses the pixels by going from left to right.
|
|
||||||
*/
|
|
||||||
def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit = {
|
|
||||||
// TODO implement this method using the `boxBlurKernel` method
|
|
||||||
for(y <- from until end){
|
|
||||||
for(x <- 0 until src.width){
|
|
||||||
dst(x,y) = boxBlurKernel(src, x, y, radius)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Blurs the rows of the source image in parallel using `numTasks` tasks.
|
|
||||||
*
|
|
||||||
* Parallelization is done by stripping the source image `src` into
|
|
||||||
* `numTasks` separate strips, where each strip is composed of some number of
|
|
||||||
* rows.
|
|
||||||
*/
|
|
||||||
def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit = {
|
|
||||||
// TODO implement using the `task` construct and the `blur` method
|
|
||||||
val r = 0 to src.height by (src.height/(Math.min(numTasks, src.height)))
|
|
||||||
var ranges = r zip r.tail
|
|
||||||
val tasks = ranges.map( { case (from, to) => task(blur(src, dst, from, to, radius)) } )
|
|
||||||
tasks foreach {_.join}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,18 +0,0 @@
|
|||||||
package scalashop
|
|
||||||
|
|
||||||
// Interfaces used by the grading infrastructure. Do not change signatures
|
|
||||||
// or your submission will fail with a NoSuchMethodError.
|
|
||||||
|
|
||||||
trait HorizontalBoxBlurInterface {
|
|
||||||
def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit
|
|
||||||
def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit
|
|
||||||
}
|
|
||||||
|
|
||||||
trait VerticalBoxBlurInterface {
|
|
||||||
def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit
|
|
||||||
def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit
|
|
||||||
}
|
|
||||||
|
|
||||||
trait BoxBlurKernelInterface {
|
|
||||||
def boxBlurKernel(src: Img, x: Int, y: Int, radius: Int): RGBA
|
|
||||||
}
|
|
||||||
@ -1,85 +0,0 @@
|
|||||||
package scalashop
|
|
||||||
|
|
||||||
import java.awt._
|
|
||||||
import java.awt.event._
|
|
||||||
import java.awt.image._
|
|
||||||
import java.io._
|
|
||||||
import javax.imageio._
|
|
||||||
import javax.swing._
|
|
||||||
import javax.swing.event._
|
|
||||||
|
|
||||||
class PhotoCanvas extends JComponent {
|
|
||||||
|
|
||||||
var imagePath: Option[String] = None
|
|
||||||
|
|
||||||
var image = loadScalaImage()
|
|
||||||
|
|
||||||
override def getPreferredSize = {
|
|
||||||
new Dimension(image.width, image.height)
|
|
||||||
}
|
|
||||||
|
|
||||||
private def loadScalaImage(): Img = {
|
|
||||||
val stream = this.getClass.getResourceAsStream("/scalashop/scala.jpg")
|
|
||||||
try {
|
|
||||||
loadImage(stream)
|
|
||||||
} finally {
|
|
||||||
stream.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private def loadFileImage(path: String): Img = {
|
|
||||||
val stream = new FileInputStream(path)
|
|
||||||
try {
|
|
||||||
loadImage(stream)
|
|
||||||
} finally {
|
|
||||||
stream.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private def loadImage(inputStream: InputStream): Img = {
|
|
||||||
val bufferedImage = ImageIO.read(inputStream)
|
|
||||||
val width = bufferedImage.getWidth
|
|
||||||
val height = bufferedImage.getHeight
|
|
||||||
val img = new Img(width, height)
|
|
||||||
for (x <- 0 until width; y <- 0 until height) img(x, y) = bufferedImage.getRGB(x, y)
|
|
||||||
img
|
|
||||||
}
|
|
||||||
|
|
||||||
def reload(): Unit = {
|
|
||||||
image = imagePath match {
|
|
||||||
case Some(path) => loadFileImage(path)
|
|
||||||
case None => loadScalaImage()
|
|
||||||
}
|
|
||||||
repaint()
|
|
||||||
}
|
|
||||||
|
|
||||||
def loadFile(path: String): Unit = {
|
|
||||||
imagePath = Some(path)
|
|
||||||
reload()
|
|
||||||
}
|
|
||||||
|
|
||||||
def applyFilter(filterName: String, numTasks: Int, radius: Int): Unit = {
|
|
||||||
val dst = new Img(image.width, image.height)
|
|
||||||
filterName match {
|
|
||||||
case "horizontal-box-blur" =>
|
|
||||||
HorizontalBoxBlur.parBlur(image, dst, numTasks, radius)
|
|
||||||
case "vertical-box-blur" =>
|
|
||||||
VerticalBoxBlur.parBlur(image, dst, numTasks, radius)
|
|
||||||
case "" =>
|
|
||||||
}
|
|
||||||
image = dst
|
|
||||||
repaint()
|
|
||||||
}
|
|
||||||
|
|
||||||
override def paintComponent(gcan: Graphics) = {
|
|
||||||
super.paintComponent(gcan)
|
|
||||||
|
|
||||||
val width = image.width
|
|
||||||
val height = image.height
|
|
||||||
val bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
|
|
||||||
for (x <- 0 until width; y <- 0 until height) bufferedImage.setRGB(x, y, image(x, y))
|
|
||||||
|
|
||||||
gcan.drawImage(bufferedImage, 0, 0, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,140 +0,0 @@
|
|||||||
package scalashop
|
|
||||||
|
|
||||||
import org.scalameter._
|
|
||||||
import java.awt._
|
|
||||||
import java.awt.event._
|
|
||||||
import javax.swing._
|
|
||||||
import javax.swing.event._
|
|
||||||
import scala.collection.mutable.ArrayBuffer
|
|
||||||
import scala.reflect.ClassTag
|
|
||||||
|
|
||||||
object ScalaShop {
|
|
||||||
|
|
||||||
class ScalaShopFrame extends JFrame("ScalaShop\u2122") {
|
|
||||||
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
|
|
||||||
setSize(1024, 600)
|
|
||||||
setLayout(new BorderLayout)
|
|
||||||
|
|
||||||
val rightpanel = new JPanel
|
|
||||||
rightpanel.setBorder(BorderFactory.createEtchedBorder(border.EtchedBorder.LOWERED))
|
|
||||||
rightpanel.setLayout(new BorderLayout)
|
|
||||||
add(rightpanel, BorderLayout.EAST)
|
|
||||||
|
|
||||||
val controls = new JPanel
|
|
||||||
controls.setLayout(new GridLayout(0, 2))
|
|
||||||
rightpanel.add(controls, BorderLayout.NORTH)
|
|
||||||
|
|
||||||
val filterLabel = new JLabel("Filter")
|
|
||||||
controls.add(filterLabel)
|
|
||||||
|
|
||||||
val filterCombo = new JComboBox(Array(
|
|
||||||
"horizontal-box-blur",
|
|
||||||
"vertical-box-blur"
|
|
||||||
))
|
|
||||||
controls.add(filterCombo)
|
|
||||||
|
|
||||||
val radiusLabel = new JLabel("Radius")
|
|
||||||
controls.add(radiusLabel)
|
|
||||||
|
|
||||||
val radiusSpinner = new JSpinner(new SpinnerNumberModel(3, 1, 16, 1))
|
|
||||||
controls.add(radiusSpinner)
|
|
||||||
|
|
||||||
val tasksLabel = new JLabel("Tasks")
|
|
||||||
controls.add(tasksLabel)
|
|
||||||
|
|
||||||
val tasksSpinner = new JSpinner(new SpinnerNumberModel(32, 1, 128, 1))
|
|
||||||
controls.add(tasksSpinner)
|
|
||||||
|
|
||||||
val stepbutton = new JButton("Apply filter")
|
|
||||||
stepbutton.addActionListener(new ActionListener {
|
|
||||||
def actionPerformed(e: ActionEvent): Unit = {
|
|
||||||
val time = measure {
|
|
||||||
canvas.applyFilter(getFilterName, getNumTasks, getRadius)
|
|
||||||
}
|
|
||||||
updateInformationBox(time.value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
controls.add(stepbutton)
|
|
||||||
|
|
||||||
val clearButton = new JButton("Reload")
|
|
||||||
clearButton.addActionListener(new ActionListener {
|
|
||||||
def actionPerformed(e: ActionEvent): Unit = {
|
|
||||||
canvas.reload()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
controls.add(clearButton)
|
|
||||||
|
|
||||||
val info = new JTextArea(" ")
|
|
||||||
info.setBorder(BorderFactory.createLoweredBevelBorder)
|
|
||||||
rightpanel.add(info, BorderLayout.SOUTH)
|
|
||||||
|
|
||||||
val mainMenuBar = new JMenuBar()
|
|
||||||
|
|
||||||
val fileMenu = new JMenu("File")
|
|
||||||
val openMenuItem = new JMenuItem("Open...")
|
|
||||||
openMenuItem.addActionListener(new ActionListener {
|
|
||||||
def actionPerformed(e: ActionEvent): Unit = {
|
|
||||||
val fc = new JFileChooser()
|
|
||||||
if (fc.showOpenDialog(ScalaShopFrame.this) == JFileChooser.APPROVE_OPTION) {
|
|
||||||
canvas.loadFile(fc.getSelectedFile.getPath)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
fileMenu.add(openMenuItem)
|
|
||||||
val exitMenuItem = new JMenuItem("Exit")
|
|
||||||
exitMenuItem.addActionListener(new ActionListener {
|
|
||||||
def actionPerformed(e: ActionEvent): Unit = {
|
|
||||||
sys.exit(0)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
fileMenu.add(exitMenuItem)
|
|
||||||
|
|
||||||
mainMenuBar.add(fileMenu)
|
|
||||||
|
|
||||||
val helpMenu = new JMenu("Help")
|
|
||||||
val aboutMenuItem = new JMenuItem("About")
|
|
||||||
aboutMenuItem.addActionListener(new ActionListener {
|
|
||||||
def actionPerformed(e: ActionEvent): Unit = {
|
|
||||||
JOptionPane.showMessageDialog(null, "ScalaShop, the ultimate image manipulation tool\nBrought to you by EPFL, 2015")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
helpMenu.add(aboutMenuItem)
|
|
||||||
|
|
||||||
mainMenuBar.add(helpMenu)
|
|
||||||
|
|
||||||
setJMenuBar(mainMenuBar)
|
|
||||||
|
|
||||||
val canvas = new PhotoCanvas
|
|
||||||
|
|
||||||
val scrollPane = new JScrollPane(canvas)
|
|
||||||
|
|
||||||
add(scrollPane, BorderLayout.CENTER)
|
|
||||||
setVisible(true)
|
|
||||||
|
|
||||||
def updateInformationBox(time: Double): Unit = {
|
|
||||||
info.setText(s"Time: $time")
|
|
||||||
}
|
|
||||||
|
|
||||||
def getNumTasks: Int = tasksSpinner.getValue.asInstanceOf[Int]
|
|
||||||
|
|
||||||
def getRadius: Int = radiusSpinner.getValue.asInstanceOf[Int]
|
|
||||||
|
|
||||||
def getFilterName: String = {
|
|
||||||
filterCombo.getSelectedItem.asInstanceOf[String]
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
|
|
||||||
} catch {
|
|
||||||
case _: Exception => println("Cannot set look and feel, using the default one.")
|
|
||||||
}
|
|
||||||
|
|
||||||
val frame = new ScalaShopFrame
|
|
||||||
|
|
||||||
def main(args: Array[String]): Unit = {
|
|
||||||
frame.repaint()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,67 +0,0 @@
|
|||||||
package scalashop
|
|
||||||
|
|
||||||
import org.scalameter._
|
|
||||||
|
|
||||||
object VerticalBoxBlurRunner {
|
|
||||||
|
|
||||||
val standardConfig = config(
|
|
||||||
Key.exec.minWarmupRuns -> 5,
|
|
||||||
Key.exec.maxWarmupRuns -> 10,
|
|
||||||
Key.exec.benchRuns -> 10,
|
|
||||||
Key.verbose -> true
|
|
||||||
) withWarmer(new Warmer.Default)
|
|
||||||
|
|
||||||
def main(args: Array[String]): Unit = {
|
|
||||||
val radius = 3
|
|
||||||
val width = 1920
|
|
||||||
val height = 1080
|
|
||||||
val src = new Img(width, height)
|
|
||||||
val dst = new Img(width, height)
|
|
||||||
val seqtime = standardConfig measure {
|
|
||||||
VerticalBoxBlur.blur(src, dst, 0, width, radius)
|
|
||||||
}
|
|
||||||
println(s"sequential blur time: $seqtime")
|
|
||||||
|
|
||||||
val numTasks = 32
|
|
||||||
val partime = standardConfig measure {
|
|
||||||
VerticalBoxBlur.parBlur(src, dst, numTasks, radius)
|
|
||||||
}
|
|
||||||
println(s"fork/join blur time: $partime")
|
|
||||||
println(s"speedup: ${seqtime.value / partime.value}")
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A simple, trivially parallelizable computation. */
|
|
||||||
object VerticalBoxBlur extends VerticalBoxBlurInterface {
|
|
||||||
|
|
||||||
/** Blurs the columns of the source image `src` into the destination image
|
|
||||||
* `dst`, starting with `from` and ending with `end` (non-inclusive).
|
|
||||||
*
|
|
||||||
* Within each column, `blur` traverses the pixels by going from top to
|
|
||||||
* bottom.
|
|
||||||
*/
|
|
||||||
def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit = {
|
|
||||||
// TODO implement this method using the `boxBlurKernel` method
|
|
||||||
for(x <- from until end){
|
|
||||||
for(y <- 0 until src.height){
|
|
||||||
dst(x,y) = boxBlurKernel(src, x, y, radius)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Blurs the columns of the source image in parallel using `numTasks` tasks.
|
|
||||||
*
|
|
||||||
* Parallelization is done by stripping the source image `src` into
|
|
||||||
* `numTasks` separate strips, where each strip is composed of some number of
|
|
||||||
* columns.
|
|
||||||
*/
|
|
||||||
def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit = {
|
|
||||||
// TODO implement using the `task` construct and the `blur` method
|
|
||||||
val r = 0 to src.width by (src.width/(Math.min(numTasks, src.width)))
|
|
||||||
var ranges = r zip r.tail
|
|
||||||
val tasks = ranges.map( { case (from, to) => task(blur(src, dst, from, to, radius)) } )
|
|
||||||
tasks foreach {_.join}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,121 +0,0 @@
|
|||||||
import java.util.concurrent._
|
|
||||||
import scala.util.DynamicVariable
|
|
||||||
|
|
||||||
import org.scalameter._
|
|
||||||
|
|
||||||
package object scalashop extends BoxBlurKernelInterface {
|
|
||||||
|
|
||||||
/** The value of every pixel is represented as a 32 bit integer. */
|
|
||||||
type RGBA = Int
|
|
||||||
|
|
||||||
/** Returns the red component. */
|
|
||||||
def red(c: RGBA): Int = (0xff000000 & c) >>> 24
|
|
||||||
|
|
||||||
/** Returns the green component. */
|
|
||||||
def green(c: RGBA): Int = (0x00ff0000 & c) >>> 16
|
|
||||||
|
|
||||||
/** Returns the blue component. */
|
|
||||||
def blue(c: RGBA): Int = (0x0000ff00 & c) >>> 8
|
|
||||||
|
|
||||||
/** Returns the alpha component. */
|
|
||||||
def alpha(c: RGBA): Int = (0x000000ff & c) >>> 0
|
|
||||||
|
|
||||||
/** Used to create an RGBA value from separate components. */
|
|
||||||
def rgba(r: Int, g: Int, b: Int, a: Int): RGBA = {
|
|
||||||
(r << 24) | (g << 16) | (b << 8) | (a << 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Restricts the integer into the specified range. */
|
|
||||||
def clamp(v: Int, min: Int, max: Int): Int = {
|
|
||||||
if (v < min) min
|
|
||||||
else if (v > max) max
|
|
||||||
else v
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Image is a two-dimensional matrix of pixel values. */
|
|
||||||
class Img(val width: Int, val height: Int, private val data: Array[RGBA]) {
|
|
||||||
def this(w: Int, h: Int) = this(w, h, new Array(w * h))
|
|
||||||
def apply(x: Int, y: Int): RGBA = data(y * width + x)
|
|
||||||
def update(x: Int, y: Int, c: RGBA): Unit = data(y * width + x) = c
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Computes the blurred RGBA value of a single pixel of the input image. */
|
|
||||||
def boxBlurKernel(src: Img, x: Int, y: Int, radius: Int): RGBA = {
|
|
||||||
|
|
||||||
// TODO implement using while loops
|
|
||||||
var r = 0
|
|
||||||
var g = 0
|
|
||||||
var b = 0
|
|
||||||
var a = 0
|
|
||||||
|
|
||||||
var count = 0
|
|
||||||
|
|
||||||
var xi = clamp(x-radius, 0, src.width-1)
|
|
||||||
while(xi<=clamp(x+radius, 0, src.width-1)) {
|
|
||||||
var yi = clamp(y-radius, 0, src.height-1)
|
|
||||||
while(yi<=clamp(y+radius, 0, src.height-1)) {
|
|
||||||
r = r + red(src(xi, yi))
|
|
||||||
g = g + green(src(xi, yi))
|
|
||||||
b = b + blue(src(xi, yi))
|
|
||||||
a = a + alpha(src(xi, yi))
|
|
||||||
count = count + 1
|
|
||||||
yi = yi + 1
|
|
||||||
}
|
|
||||||
xi = xi + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
rgba(r/count, g/count, b/count, a/count)
|
|
||||||
}
|
|
||||||
|
|
||||||
val forkJoinPool = new ForkJoinPool
|
|
||||||
|
|
||||||
abstract class TaskScheduler {
|
|
||||||
def schedule[T](body: => T): ForkJoinTask[T]
|
|
||||||
def parallel[A, B](taskA: => A, taskB: => B): (A, B) = {
|
|
||||||
val right = task {
|
|
||||||
taskB
|
|
||||||
}
|
|
||||||
val left = taskA
|
|
||||||
(left, right.join())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class DefaultTaskScheduler extends TaskScheduler {
|
|
||||||
def schedule[T](body: => T): ForkJoinTask[T] = {
|
|
||||||
val t = new RecursiveTask[T] {
|
|
||||||
def compute = body
|
|
||||||
}
|
|
||||||
Thread.currentThread match {
|
|
||||||
case wt: ForkJoinWorkerThread =>
|
|
||||||
t.fork()
|
|
||||||
case _ =>
|
|
||||||
forkJoinPool.execute(t)
|
|
||||||
}
|
|
||||||
t
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val scheduler =
|
|
||||||
new DynamicVariable[TaskScheduler](new DefaultTaskScheduler)
|
|
||||||
|
|
||||||
def task[T](body: => T): ForkJoinTask[T] = {
|
|
||||||
scheduler.value.schedule(body)
|
|
||||||
}
|
|
||||||
|
|
||||||
def parallel[A, B](taskA: => A, taskB: => B): (A, B) = {
|
|
||||||
scheduler.value.parallel(taskA, taskB)
|
|
||||||
}
|
|
||||||
|
|
||||||
def parallel[A, B, C, D](taskA: => A, taskB: => B, taskC: => C, taskD: => D): (A, B, C, D) = {
|
|
||||||
val ta = task { taskA }
|
|
||||||
val tb = task { taskB }
|
|
||||||
val tc = task { taskC }
|
|
||||||
val td = taskD
|
|
||||||
(ta.join(), tb.join(), tc.join(), td)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Workaround Dotty's handling of the existential type KeyValue
|
|
||||||
implicit def keyValueCoerce[T](kv: (Key[T], T)): KeyValue = {
|
|
||||||
kv.asInstanceOf[KeyValue]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
126
src/test/scala/actorbintree/BinaryTreeSuite.scala
Normal file
126
src/test/scala/actorbintree/BinaryTreeSuite.scala
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
/**
|
||||||
|
* Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
|
||||||
|
*/
|
||||||
|
package actorbintree
|
||||||
|
|
||||||
|
import akka.actor.{ActorRef, ActorSystem, Props, actorRef2Scala, scala2ActorRef}
|
||||||
|
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.Assert._
|
||||||
|
|
||||||
|
import scala.util.Random
|
||||||
|
import scala.concurrent.duration._
|
||||||
|
|
||||||
|
class BinaryTreeSuite extends TestKit(ActorSystem("BinaryTreeSuite")) with ImplicitSender {
|
||||||
|
|
||||||
|
import actorbintree.BinaryTreeSet._
|
||||||
|
|
||||||
|
def receiveN(requester: TestProbe, ops: Seq[Operation], expectedReplies: Seq[OperationReply]): Unit =
|
||||||
|
requester.within(5.seconds) {
|
||||||
|
val repliesUnsorted = for (i <- 1 to ops.size) yield try {
|
||||||
|
requester.expectMsgType[OperationReply]
|
||||||
|
} catch {
|
||||||
|
case ex: Throwable if ops.size > 10 => sys.error(s"failure to receive confirmation $i/${ops.size}\n$ex")
|
||||||
|
case ex: Throwable => sys.error(s"failure to receive confirmation $i/${ops.size}\nRequests:" + ops.mkString("\n ", "\n ", "") + s"\n$ex")
|
||||||
|
}
|
||||||
|
val replies = repliesUnsorted.sortBy(_.id)
|
||||||
|
if (replies != expectedReplies) {
|
||||||
|
val pairs = (replies zip expectedReplies).zipWithIndex filter (x => x._1._1 != x._1._2)
|
||||||
|
fail("unexpected replies:" + pairs.map(x => s"at index ${x._2}: got ${x._1._1}, expected ${x._1._2}").mkString("\n ", "\n ", ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def verify(probe: TestProbe, ops: Seq[Operation], expected: Seq[OperationReply]): Unit = {
|
||||||
|
val topNode = system.actorOf(Props[BinaryTreeSet])
|
||||||
|
|
||||||
|
ops foreach { op =>
|
||||||
|
topNode ! op
|
||||||
|
}
|
||||||
|
|
||||||
|
receiveN(probe, ops, expected)
|
||||||
|
// the grader also verifies that enough actors are created
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test def `proper inserts and lookups (5pts)`(): Unit = {
|
||||||
|
val topNode = system.actorOf(Props[BinaryTreeSet])
|
||||||
|
|
||||||
|
topNode ! Contains(testActor, id = 1, 1)
|
||||||
|
expectMsg(ContainsResult(1, false))
|
||||||
|
|
||||||
|
topNode ! Insert(testActor, id = 2, 1)
|
||||||
|
topNode ! Contains(testActor, id = 3, 1)
|
||||||
|
|
||||||
|
expectMsg(OperationFinished(2))
|
||||||
|
expectMsg(ContainsResult(3, true))
|
||||||
|
()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test def `instruction example (5pts)`(): Unit = {
|
||||||
|
val requester = TestProbe()
|
||||||
|
val requesterRef = requester.ref
|
||||||
|
val ops = List(
|
||||||
|
Insert(requesterRef, id=100, 1),
|
||||||
|
Contains(requesterRef, id=50, 2),
|
||||||
|
Remove(requesterRef, id=10, 1),
|
||||||
|
Insert(requesterRef, id=20, 2),
|
||||||
|
Contains(requesterRef, id=80, 1),
|
||||||
|
Contains(requesterRef, id=70, 2)
|
||||||
|
)
|
||||||
|
|
||||||
|
val expectedReplies = List(
|
||||||
|
OperationFinished(id=10),
|
||||||
|
OperationFinished(id=20),
|
||||||
|
ContainsResult(id=50, false),
|
||||||
|
ContainsResult(id=70, true),
|
||||||
|
ContainsResult(id=80, false),
|
||||||
|
OperationFinished(id=100)
|
||||||
|
)
|
||||||
|
|
||||||
|
verify(requester, ops, expectedReplies)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test def `behave identically to built-in set (includes GC) (40pts)`(): Unit = {
|
||||||
|
val rnd = new Random()
|
||||||
|
def randomOperations(requester: ActorRef, count: Int): Seq[Operation] = {
|
||||||
|
def randomElement: Int = rnd.nextInt(100)
|
||||||
|
def randomOperation(requester: ActorRef, id: Int): Operation = rnd.nextInt(4) match {
|
||||||
|
case 0 => Insert(requester, id, randomElement)
|
||||||
|
case 1 => Insert(requester, id, randomElement)
|
||||||
|
case 2 => Contains(requester, id, randomElement)
|
||||||
|
case 3 => Remove(requester, id, randomElement)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (seq <- 0 until count) yield randomOperation(requester, seq)
|
||||||
|
}
|
||||||
|
|
||||||
|
def referenceReplies(operations: Seq[Operation]): Seq[OperationReply] = {
|
||||||
|
var referenceSet = Set.empty[Int]
|
||||||
|
def replyFor(op: Operation): OperationReply = op match {
|
||||||
|
case Insert(_, seq, elem) =>
|
||||||
|
referenceSet = referenceSet + elem
|
||||||
|
OperationFinished(seq)
|
||||||
|
case Remove(_, seq, elem) =>
|
||||||
|
referenceSet = referenceSet - elem
|
||||||
|
OperationFinished(seq)
|
||||||
|
case Contains(_, seq, elem) =>
|
||||||
|
ContainsResult(seq, referenceSet(elem))
|
||||||
|
}
|
||||||
|
|
||||||
|
for (op <- operations) yield replyFor(op)
|
||||||
|
}
|
||||||
|
|
||||||
|
val requester = TestProbe()
|
||||||
|
val topNode = system.actorOf(Props[BinaryTreeSet])
|
||||||
|
val count = 1000
|
||||||
|
|
||||||
|
val ops = randomOperations(requester.ref, count)
|
||||||
|
val expectedReplies = referenceReplies(ops)
|
||||||
|
|
||||||
|
ops foreach { op =>
|
||||||
|
topNode ! op
|
||||||
|
if (rnd.nextDouble() < 0.1) topNode ! GC
|
||||||
|
}
|
||||||
|
receiveN(requester, ops, expectedReplies)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,11 +0,0 @@
|
|||||||
package scalashop
|
|
||||||
|
|
||||||
import java.util.concurrent._
|
|
||||||
import scala.collection._
|
|
||||||
import org.junit._
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
|
|
||||||
class BlurSuite {
|
|
||||||
|
|
||||||
@Rule def individualTestTimeout = new org.junit.rules.Timeout(10 * 1000)
|
|
||||||
}
|
|
||||||
Loading…
Reference in New Issue
Block a user