Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • lamp/cs206
  • bwermeil/cs206-2020
  • zabifade/cs206-2020
  • cauderan/cs206-2020
  • malonga/cs206-2020
  • dumoncel/cs206
  • bounekhe/cs206
  • bergerault/cs206
  • flealsan/cs206
  • hsu/cs206
  • mouchel/cs206
  • vebraun/cs206
  • vcanard/cs206
  • ybelghmi/cs206
  • belghmi/cs206
  • bousbina/cs206
  • waked/cs206
  • gtagemou/cs206
  • arahmoun/cs206
  • elhachem/cs206
  • benrahha/cs206
  • benslima/cs206
22 results
Show changes
Showing
with 0 additions and 2590 deletions
labs/images/metals-import.png

30.4 KiB

labs/images/open-test.png

17.6 KiB

labs/images/pipeline-details.png

47.1 KiB

labs/images/pipeline-logs.png

157 KiB

labs/images/pipeline-tab.png

48.9 KiB

labs/images/sbt-test-error.png

44.4 KiB

labs/images/sum-def.png

6.75 KiB

labs/images/syntax-error-bug.png

47.3 KiB

labs/images/test-source.png

19 KiB

labs/images/warnings-errors.png

1.8 KiB

# Parallel Box Blur Filter
## Setup
Let's upgrade the IDE support first, close VSCode if it's open and run:
```shell
code --force --install-extension scalameta.metals
```
Use the following commands to make a fresh clone of your repository:
```
git clone -b scalashop git@gitlab.epfl.ch:lamp/student-repositories-s21/cs206-GASPAR.git cs206-scalashop
```
## Useful links
* [A guide to the Scala parallel collections](https://docs.scala-lang.org/overviews/parallel-collections/overview.html)
* [The API documentation of the Scala parallel collections](https://www.javadoc.io/doc/org.scala-lang.modules/scala-parallel-collections_2.13/latest/scala/collection/index.html)
* [The API documentation of the Scala standard library](https://www.scala-lang.org/files/archive/api/2.13.4)
* [The API documentation of the Java standard library](https://docs.oracle.com/en/java/javase/15/docs/api/index.html)
**If you have issues with the IDE, try [reimporting the
build](https://gitlab.epfl.ch/lamp/cs206/-/blob/master/labs/example-lab.md#ide-features-like-type-on-hover-or-go-to-definition-do-not-work),
if you still have problems, use `compile` in sbt instead.**
## Setup scalashop
In this assignment, we will implement a box blur filter, used in applications
like Adobe® PhotoShop® to blur images.
For the purposes of this assignment, a filter is an algorithm that takes an
input image and transforms it in some way into an output image.
The box blur filter outputs an image in which every pixel has an average value
of the surrounding pixels from the original image.
The box blur filter is an example of an *embarrassingly parallel* problem -- no
or very little effort is required to separate it into parallel tasks.
Every pixel of the output image can be computed independently of the other
pixels, and in parallel.
We will proceed in four steps. First, we will implement the kernel of the box
blur filter, a method used to compute a single pixel of the output image.
Then we will implement two versions of the parallel box blur, and measure the
performance difference.
Finally, we will try out our parallel box blur implementations on real images,
using ScalaShop -- the image manipulation tool that would impress even
the Adobe® folks.
By the time you are finished with this assignment, you will:
- understand how the box blur filter works
- be able to recognize embarrassingly parallel problems
- know how to measure the performance of a parallel algorithm
- see how to agglomerate parallel computations into batches
- better understand how memory access patterns affect performance of parallel
algorithms
## Preliminaries
Before we begin, we need to cover some basic data types and helper methods.
These utilities have already been implemented in the package object (in the file `package.scala`) for this
exercise.
First, we will use the `RGBA` type to refer to the value of an image pixel.
We will limit ourselves to 32-bit pixel depth images, so we define `RGBA` to
be equal to the 32-bit integer type:
```scala
type RGBA = Int
```
Why do we call this type `RGBA`?
This is because each pixel value is composed from 4 components - red, green,
blue and alpha, where alpha denotes the amount of transparency in the
respective pixel.
These components are referred to as *channels*.
The value of each channel is at least 0 and at most 255.
We can extract the red, green, blue and alpha channel using the following
utility methods, which use bit masking and bit shifting:
```scala
def red(c: RGBA): Int = (0xff000000 & c) >>> 24
def green(c: RGBA): Int = (0x00ff0000 & c) >>> 16
def blue(c: RGBA): Int = (0x0000ff00 & c) >>> 8
def alpha(c: RGBA): Int = (0x000000ff & c) >>> 0
```
Similarly, given the values of the four channels, we can obtain the pixel value
like this:
```scala
def rgba(r: Int, g: Int, b: Int, a: Int): RGBA =
(r << 24) | (g << 16) | (b << 8) | (a << 0)
```
Now that we know how to manipulate individual pixels, we can define our image
type `Img`:
```scala
class Img(val width: Int, val height: Int) {
private val data = new Array[RGBA](width * height)
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
}
```
The image is a two-dimensional entity -- to refer to a pixel in an image, we
need to specify an `x` and `y` component.
On the other hand, the underlying memory model is one-dimensional -- a single
offset value specifies the position in the array.
When we store the image into memory, we need to map between the
two-dimensional image model and the one-dimensional memory model.
We will do this by storing consecutive rows of the image one after another, as
illustrated in the following figure:
![mapping](mapping.png)
Thus, the offset of a pixel at coordinates `x` and `y`, is equal to
`y * width + x`, where `width` is the number of pixels in a single row.
Although there are other mappings used in practice, we will restrict to this
simple mapping throughout the exercise.
To ensure that the value of the `x` and `y` coordinates are confined to the
dimensions of the image, namely width and height, occasionally we have to call
the `clamp` method:
```scala
def clamp(v: Int, min: Int, max: Int): Int
```
Finally, we will use the `task` construct to start parallel computations.
Every `task` construct invocation returns an object on which we can call the
`join` method.
Calling the `join` method blocks the execution of the program until the parallel
computation ends.
Below, we calculate the expression `1 + 1` in parallel to the main program:
```scala
val computation = task {
val result = 1 + 1
println("Done!")
result
}
println("About to wait for some heavy calculation...")
computation.join()
```
We now have everything we need to start implementing the parallel box filter.
## The Box Blur Filter Kernel
In the first part of the assignment, we will implement the box blur filter
kernel method.
A kernel is a method that computes the resulting value of a single pixel.
The kernel method is typically computationally cheap and is not worth
parallelizing its implementation.
However, as we will later see, we can apply the same kernel method to different
pixels in parallel.
![kernel](kernel.png)
The `boxBlurKernel` method takes the source image `src`, coordinates `x` and `y`
of the pixel, and the `radius` of the blur.
It returns the resulting average value of the surrounding pixels.
We compute the average value by separating the pixel into four channels,
computing the average of each of the channels,
and using the four average values to produce the final pixel value.
In the previous figure, the `radius` parameter is equal to `1` and the average
is computed from `9` pixels.
You can find its signature in the package object of this assignment:
def boxBlurKernel(src: Img, x: Int, y: Int, radius: Int): RGBA
Implement the `boxBlurKernel` method.
Use two nested `while`-loops.
Make sure that the pixels at the image edges are affected only by the
pixels inside the image (hint: use the `clamp` method from the package object).
## Vertical Stripping Box Blur
We can now implement the parallel box blur filter.
Note that the `boxBlurKernel` method is relatively inexpensive.
Executing `boxBlurKernel` might be much faster than starting a parallel
computation, so having a separate parallel computation for the value of each
pixel would be far too expensive.
For this reason, we want to batch together many `boxBlurKernel` calls, and have
a smaller number of parallel tasks.
This is sometimes referred to as *agglomeration*, and is present in many
parallel algorithm implementations.
There are many different ways we can do agglomeration for the parallel box blur.
One is to divide the image into a fixed number of equally wide vertical strips.
For each strip, we start a parallel task, and wait for their completion.
Within each strip, we traverse the pixels going from the top to the bottom of
the image, as illustrated in the following figure:
![stripping](vertical.png)
We start by implementing the sequential `blur` method in the
`VerticalBoxBlur.scala` source file, which takes the source image `src`, the
destination image `dst`, the starting (included) and ending (excluded) `x` coordinates
(i.e, column indices) of the strip, called `from` and `end`, and the blur `radius`.
The `blur` method blurs the pixels from the `src` image and writes them to the
`dst` image:
```scala
def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit
```
The implementation of `blur` should rely on the previously defined `boxBlurKernel`.
Then, implement the `parBlur` method, which divides the image into `numTasks` vertical strips and runs each task in parallel:
```scala
def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit
```
Use Scala ranges to create a list of splitting points
(hint: use the `by` method on ranges).
Then use collection combinators on the list of splitting points to create a list
of start and end tuples, one for each strip
(hint: use the `zip` and `tail` methods).
Finally, use the `task` construct to start a parallel task for each strip,
and then call `join` on each task to wait for its completion.
### Benchmarking VerticalBoxBlur
Before running the benchmarking program, go to the top of `VerticalBoxBlur.scala`
and replace the line:
```scala
Key.verbose -> true
```
by:
```scala
Key.verbose -> false
```
Now you can run the `VerticalBoxBlur` program with the following sbt command:
```
> runMain scalashop.VerticalBoxBlurRunner
```
Change the number of tasks and the radius parameter.
How does the performance change?
## Horizontal Stripping Box Blur
In this part of the exercise we will pick an alternative agglomeration for the
box blur algorithm.
Instead of dividing the image into vertical strips, we will divide it into
horizontal strips in a similar way:
![stripping](horizontal.png)
We implement the two methods, `blur` and `parBlur` in a similar way as before:
```scala
def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit
def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit
```
Note that the arguments `from` (included) and `end` (excluded) this time denote the values of the
`y` coordinate (i.e, row indices), and that we traverse the pixels left-to-right within each strip.
### Benchmarking HorizontalBoxBlur
Before running the benchmarking program, go to the top of `HorizontalBoxBlur.scala`
and replace the line:
```scala
Key.verbose -> true
```
by:
```scala
Key.verbose -> false
```
Now you can now run the `HorizontalBoxBlur` program from sbt with:
```
> runMain scalashop.HorizontalBoxBlurRunner
```
If you implemented the two blur versions correctly, you should observe that the
horizontal stripping is slightly faster.
This is because the pixel traversal order visits the pixels which are closer
together in memory (remember the mapping between the pixel coordinates and the
memory addresses). As a result, each core can reuse some of the pixels that it
fetched from the memory during the previous invocation of `boxBlurKernel`.
The processor cores spend less time fetching pixels from memory and lower the
pressure on the memory bus.
## ScalaShop
Now we have everything we need to start ScalaShop, from sbt run:
```
> runMain scalashop.ScalaShop
```
Change the blur implementation, parallelism level and blur radius, and study the
effect your changes have on performance.
* Which of the two blur implementations is faster?
* For which values of the `radius` parameter is the difference most significant?
* Why?
* What if we split the image into rectangles? Will this be faster?
*"Adobe" and "Photoshop" are either registered trademarks or trademarks of Adobe
Systems Incorporated in the United States and/or other countries.*
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="210mm"
height="297mm"
viewBox="0 0 744.09448819 1052.3622047"
id="svg2"
version="1.1"
inkscape:version="0.91 r13725"
inkscape:export-filename="C:\cygwin\home\axel22\workspaces\scala\parprog\statements\scalashop\kernel.png"
inkscape:export-xdpi="16.044189"
inkscape:export-ydpi="16.044189"
sodipodi:docname="avg.svg">
<defs
id="defs4">
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker13978"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path13980" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker13264"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path13266" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker11620"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path11622" />
</marker>
<marker
inkscape:stockid="Arrow1Lend"
orient="auto"
refY="0.0"
refX="0.0"
id="marker11430"
style="overflow:visible;"
inkscape:isstock="true">
<path
id="path11432"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
transform="scale(0.8) rotate(180) translate(12.5,0)" />
</marker>
<marker
inkscape:stockid="Arrow1Lend"
orient="auto"
refY="0.0"
refX="0.0"
id="marker11220"
style="overflow:visible;"
inkscape:isstock="true">
<path
id="path11222"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
transform="scale(0.8) rotate(180) translate(12.5,0)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker8210"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path8212" />
</marker>
<marker
inkscape:stockid="Arrow1Lend"
orient="auto"
refY="0.0"
refX="0.0"
id="marker8122"
style="overflow:visible;"
inkscape:isstock="true">
<path
id="path8124"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
transform="scale(0.8) rotate(180) translate(12.5,0)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker8004"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path8006" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker7904"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path7906" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker7810"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path7812" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker5934"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path5936" />
</marker>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.55904437"
inkscape:cx="498.91476"
inkscape:cy="485.13131"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-nodes="false"
inkscape:snap-bbox="false"
inkscape:window-width="1600"
inkscape:window-height="877"
inkscape:window-x="-4"
inkscape:window-y="-4"
inkscape:window-maximized="1" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 569.48922,182.84133 0,536.93787"
id="path3342"
inkscape:connector-curvature="0" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 476.55518,182.84133 0,536.93787"
id="path3346"
inkscape:connector-curvature="0" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 390.18714,182.84133 0,536.93787"
id="path3350"
inkscape:connector-curvature="0" />
<path
inkscape:connector-curvature="0"
id="path3352"
d="m 304.82925,182.84133 0,536.93787"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 630.8714,268.75392 -419.48108,0"
id="path3354"
inkscape:connector-curvature="0" />
<path
inkscape:connector-curvature="0"
id="path3356"
d="m 630.8714,359.12582 -419.48108,0"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 630.8714,454.81371 -419.48108,0"
id="path3358"
inkscape:connector-curvature="0" />
<path
inkscape:connector-curvature="0"
id="path3360"
d="m 630.8714,550.05861 -419.48108,0"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 630.8714,649.73349 -419.48108,0"
id="path3362"
inkscape:connector-curvature="0" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 213.41044,182.84133 0,536.93787"
id="path3364"
inkscape:connector-curvature="0" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:37.4613266px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
x="643.29187"
y="549.94373"
id="text11422"
sodipodi:linespacing="125%"
transform="scale(1.0677679,0.93653312)"><tspan
sodipodi:role="line"
id="tspan11424"
x="643.29187"
y="549.94373"
style="font-size:65.55731964px">. . .</tspan></text>
<text
sodipodi:linespacing="125%"
id="text11426"
y="-384.24774"
x="803.21533"
style="font-style:normal;font-weight:normal;font-size:37.4613266px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
xml:space="preserve"
transform="matrix(0,0.93653312,-1.0677679,0,0,0)"><tspan
style="font-size:65.55731964px"
y="-384.24774"
x="803.21533"
id="tspan11428"
sodipodi:role="line">. . .</tspan></text>
<rect
style="fill:#000000;fill-opacity:0.85806454;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect3403"
width="87.649574"
height="97.272865"
x="389.95117"
y="453.85275" />
<rect
y="358.1488"
x="304.09036"
height="97.272865"
width="87.649574"
id="rect6045"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6047"
width="87.649574"
height="97.272865"
x="389.95117"
y="358.1488" />
<rect
y="358.1488"
x="479.3895"
height="97.272865"
width="87.649574"
id="rect6049"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6051"
width="87.649574"
height="97.272865"
x="304.09036"
y="453.85275" />
<rect
y="453.85275"
x="479.3895"
height="97.272865"
width="87.649574"
id="rect6053"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6055"
width="87.649574"
height="97.272865"
x="479.3895"
y="551.12567" />
<rect
y="551.12567"
x="388.16238"
height="97.272865"
width="87.649574"
id="rect6057"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6059"
width="87.649574"
height="97.272865"
x="302.30157"
y="551.12567" />
<path
inkscape:connector-curvature="0"
id="path6065"
d="m 630.8714,182.89311 -419.48108,0"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
</g>
</svg>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="210mm"
height="297mm"
viewBox="0 0 744.09448819 1052.3622047"
id="svg2"
version="1.1"
inkscape:version="0.91 r13725"
inkscape:export-filename="C:\cygwin\home\axel22\workspaces\scala\parprog\statements\scalashop\horizontal.png"
inkscape:export-xdpi="32.263706"
inkscape:export-ydpi="32.263706"
sodipodi:docname="horiz.svg">
<defs
id="defs4">
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker13978"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path13980" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker13264"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path13266" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker11620"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path11622" />
</marker>
<marker
inkscape:stockid="Arrow1Lend"
orient="auto"
refY="0.0"
refX="0.0"
id="marker11430"
style="overflow:visible;"
inkscape:isstock="true">
<path
id="path11432"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
transform="scale(0.8) rotate(180) translate(12.5,0)" />
</marker>
<marker
inkscape:stockid="Arrow1Lend"
orient="auto"
refY="0.0"
refX="0.0"
id="marker11220"
style="overflow:visible;"
inkscape:isstock="true">
<path
id="path11222"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
transform="scale(0.8) rotate(180) translate(12.5,0)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker8210"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path8212" />
</marker>
<marker
inkscape:stockid="Arrow1Lend"
orient="auto"
refY="0.0"
refX="0.0"
id="marker8122"
style="overflow:visible;"
inkscape:isstock="true">
<path
id="path8124"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
transform="scale(0.8) rotate(180) translate(12.5,0)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker8004"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path8006" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker7904"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path7906" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker7810"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path7812" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible;"
id="marker5934"
refX="0.0"
refY="0.0"
orient="auto"
inkscape:stockid="Arrow1Lend">
<path
transform="scale(0.8) rotate(180) translate(12.5,0)"
style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;stroke-opacity:1;fill:#000000;fill-opacity:1"
d="M 0.0,0.0 L 5.0,-5.0 L -12.5,0.0 L 5.0,5.0 L 0.0,0.0 z "
id="path5936" />
</marker>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.55904437"
inkscape:cx="498.91476"
inkscape:cy="485.13131"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-nodes="false"
inkscape:snap-bbox="false"
inkscape:window-width="1600"
inkscape:window-height="877"
inkscape:window-x="-4"
inkscape:window-y="-4"
inkscape:window-maximized="1" />
<metadata
id="metadata7">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 569.48922,182.84133 0,536.93787"
id="path3342"
inkscape:connector-curvature="0" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 476.55518,182.84133 0,536.93787"
id="path3346"
inkscape:connector-curvature="0" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 390.18714,182.84133 0,536.93787"
id="path3350"
inkscape:connector-curvature="0" />
<path
inkscape:connector-curvature="0"
id="path3352"
d="m 304.82925,182.84133 0,536.93787"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 630.8714,268.75392 -419.48108,0"
id="path3354"
inkscape:connector-curvature="0" />
<path
inkscape:connector-curvature="0"
id="path3356"
d="m 630.8714,359.12582 -419.48108,0"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 630.8714,454.81371 -419.48108,0"
id="path3358"
inkscape:connector-curvature="0" />
<path
inkscape:connector-curvature="0"
id="path3360"
d="m 630.8714,550.05861 -419.48108,0"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 630.8714,649.73349 -419.48108,0"
id="path3362"
inkscape:connector-curvature="0" />
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3.06535697;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 213.41044,182.84133 0,536.93787"
id="path3364"
inkscape:connector-curvature="0" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:37.4613266px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
x="643.29187"
y="549.94373"
id="text11422"
sodipodi:linespacing="125%"
transform="scale(1.0677679,0.93653312)"><tspan
sodipodi:role="line"
id="tspan11424"
x="643.29187"
y="549.94373"
style="font-size:65.55731964px">. . .</tspan></text>
<text
sodipodi:linespacing="125%"
id="text11426"
y="-384.24774"
x="803.21533"
style="font-style:normal;font-weight:normal;font-size:37.4613266px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
xml:space="preserve"
transform="matrix(0,0.93653312,-1.0677679,0,0,0)"><tspan
style="font-size:65.55731964px"
y="-384.24774"
x="803.21533"
id="tspan11428"
sodipodi:role="line">. . .</tspan></text>
<rect
style="fill:#000000;fill-opacity:0.85806454;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect3403"
width="87.649574"
height="97.272865"
x="389.95117"
y="453.85275" />
<rect
y="358.1488"
x="304.09036"
height="97.272865"
width="87.649574"
id="rect6045"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6047"
width="87.649574"
height="97.272865"
x="389.95117"
y="358.1488" />
<rect
y="358.1488"
x="479.3895"
height="97.272865"
width="87.649574"
id="rect6049"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6051"
width="87.649574"
height="97.272865"
x="304.09036"
y="453.85275" />
<rect
y="453.85275"
x="479.3895"
height="97.272865"
width="87.649574"
id="rect6053"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6055"
width="87.649574"
height="97.272865"
x="479.3895"
y="551.12567" />
<rect
y="551.12567"
x="388.16238"
height="97.272865"
width="87.649574"
id="rect6057"
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
<rect
style="fill:#000000;fill-opacity:0.45161288;fill-rule:evenodd;stroke:#000000;stroke-width:0.93653309px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="rect6059"
width="87.649574"
height="97.272865"
x="302.30157"
y="551.12567" />
<path
inkscape:connector-curvature="0"
id="path6065"
d="m 630.8714,182.89311 -419.48108,0"
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:2.53745508;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
</g>
</svg>
labs/lab1-parallel-box-blur-filter/horizontal.png

6.25 KiB

labs/lab1-parallel-box-blur-filter/kernel.png

872 B

labs/lab1-parallel-box-blur-filter/mapping.png

8.23 KiB

This diff is collapsed.
This diff is collapsed.
labs/lab1-parallel-box-blur-filter/vertical.png

7.31 KiB

# Reductions and Prefix Sums
Use the following commands to make a fresh clone of your repository:
```
git clone -b reductions git@gitlab.epfl.ch:lamp/student-repositories-s21/cs206-GASPAR.git cs206-reductions
```
## Useful links
* [A guide to the Scala parallel collections](https://docs.scala-lang.org/overviews/parallel-collections/overview.html)
* [The API documentation of the Scala parallel collections](https://www.javadoc.io/doc/org.scala-lang.modules/scala-parallel-collections_2.13/latest/scala/collection/index.html)
* [The API documentation of the Scala standard library](https://www.scala-lang.org/files/archive/api/2.13.4)
* [The API documentation of the Java standard library](https://docs.oracle.com/en/java/javase/15/docs/api/index.html)
**If you have issues with the IDE, try [reimporting the
build](https://gitlab.epfl.ch/lamp/cs206/-/blob/master/labs/example-lab.md#ide-features-like-type-on-hover-or-go-to-definition-do-not-work),
if you still have problems, use `compile` in sbt instead.**
## Introduction
In this assignment, you will implement several variants of reduction and prefix
sum algorithms. Each of the three parts of the assignment will exercise a
different aspect of parallel programming:
- choosing the right parallelization threshold
- identifying the correct reduction operator
- identifying the correct prefix sum operator
We will use the `parallel` construct, defined in the file `package.scala`, as in the lecture to start parallel
computations. Every `parallel` construct invocation takes two tasks as input and
outputs the corresponding results as a tuple of two elements. You are not allowed
to use the `task` construct in this assignment.
## Parallel Counting Change
If you took the course Functional Programming in Scala, you surely recall the
assignment in which you had to count the number of ways in which you can make
the change for a given amount of money.
The text of that assignment was as follows:
> Write a recursive function that counts how many different ways you can
> make change for an amount, given a list of coin denominations. For
> example, there are 3 ways to give change for 4 if you have coins with
> denomination 1 and 2: 1+1+1+1, 1+1+2, 2+2.
In this assignment, you will repeat the same task, but this time, your
implementation will be parallel.
Start with the sequential version of this problem once more -- the `countChange`
function takes the amount of money and the list of different coin denominations.
It returns the total number of different ways you can give change:
```scala
def countChange(money: Int, coins: List[Int]): Int
```
Note that the solution to this problem is recursive.
In every recursive call, we either decide to continue subtracting the next coin
in the `coins` list from the `money` amount, or we decide to drop the coin from the list of coins.
For example, if we have 4 CHF, and coin denominations of 1 and 2, the call
graph, in which every node depicts one invocation of the `countChange` method,
is as follows:
4,[1, 2]
3,[1, 2] + 4,[2]
2,[1, 2] + 3,[2] 2,[2] + 4,[]
1,[1, 2] + 2,[2] 1,[2] + 3,[] 0,[2] + 2,[] 0
0,[1, 2] + 1,[2] 1 0 0 1 0
1 0
We can take advantage of this recursive structure by evaluating different
subtrees in parallel.
This is the next part of the assignment -- implement the method `parCountChange`
that counts the amount of change in parallel:
```scala
def parCountChange(money: Int, coins: List[Int], threshold: Threshold): Int
```
As we learned in the lectures, the `parCountChange` should not spawn parallel
computations after reaching the leaf in the call graph -- the synchronization
costs of doing this are way too high.
Instead, we need to *agglomerate* parts of the computation.
We do this by calling the sequential `countChange` method when we decide that
the amount of work is lower than a certain value, called the *threshold*.
To separate the concern of deciding on the threshold value from the
implementation of our parallel algorithm, we implement the threshold
functionality in a separate function, described by the `Threshold` type alias:
```scala
type Threshold = (Int, List[Int]) => Boolean
```
When a `threshold` function returns `true` for a given amount of money and the
given list of coins, the sequential `countChange` implementation must be called.
Implement `parCountChange`!
Now that we have the `parCountChange` method, we ask ourselves what is the right
implementation of the `threshold` function?
Recall the examples from the lectures, such as summing the array values and
computing the norm, where this was easy -- we exactly knew the amount of work
required to traverse a subrange of the array, so `threshold` could return `true`
when the length of the subrange was smaller than a certain value.
Sadly, the total amount of work for a given `parCountChange` invocation is hard
to evaluate from the remaining amount of money and a list of coins.
In fact, the amount of work directly corresponds to the count that
`parCountChange` returns, which is the value that we are trying to compute.
Counting change is a canonical example of a task-parallel problem in which the
partitioning the workload across processors is *solution-driven* -- to know how
to optimally partition the work, we would first need to solve the problem
itself.
For this reason, many parallel algorithms in practice rely on heuristics to
assess the amount of work in a subtask.
We will implement several such heuristics in this exercise, and assess the
effect on performance.
First, implement the `moneyThreshold` method, which creates a threshold function
that returns `true` when the amount of money is less than or equal to `2 / 3` of
the starting amount:
```scala
def moneyThreshold(startingMoney: Int): Threshold
```
Remember that `a / b` will return the integer division of `a` and `b` when both
operands are `Int`s. To avoid this problem, be sure to always do the multiplication of
`startingMoney` by `2` before doing the division by `3`.
Now run the `ParallelCountChange` application in sbt and observe the speedup:
```
> runMain reductions.ParallelCountChangeRunner
```
The previous heuristic did not take into account how many coins were left on the
coins list, so try two other heuristics.
Implement the method `totalCoinsThreshold`, which returns a threshold function
that returns `true` when the number of coins is less than or equal to the `2 / 3` of the
initial number of coins:
```scala
def totalCoinsThreshold(totalCoins: Int): Threshold
```
Again, be careful about the order of operations.
Then, implement the method `combinedThreshold`, which returns a threshold
function that returns `true` when the amount of money multiplied with the number
of remaining coins is less than or equal to the starting money multiplied with
the initial number of coins divided by `2`:
```scala
def combinedThreshold(startingMoney: Int, allCoins: List[Int]): Threshold
```
Which of the three threshold heuristics gives the best speedup?
Can you think of a heuristic that improves performance even more?
## Parallel Parentheses Balancing
In this part of the assignment, we recall the Parenthesis Balancing assignment
that might be familiar to you from the Functional Programming in Scala course.
Here, the task is to, given an array of characters, decide if the parentheses in
the array are balanced.
Let us recall a few examples of strings in which parentheses are correctly
balanced:
```
(if (zero? x) max (/ 1 x))
I told him (that it's not (yet) done). (But he wasn't listening)
```
Similarly, the parentheses in the following strings are not balanced:
```
(o_()
:-)
())(
```
Implement a sequential function `balance`, which returns `true` iff the
parentheses in the array are balanced:
```scala
def balance(chars: Array[Char]): Boolean
```
Next, you will implement a parallel version of this method.
By now, you're already an expert at implementing the structure of a reduction
algorithm, so you should have no problem there.
The tricky part in parallel parentheses balancing is choosing the reduction
operator -- you probably implemented `balance` by keeping an integer
accumulator, incrementing it for left parentheses and decrementing it for the
right ones, taking care that this accumulator does not drop below zero.
Parallel parentheses balancing will require a bit more ingenuity on your part,
so we will give you a hint -- you will need two integer values for the
accumulator.
Implement the `parBalance` method, which checks if the parentheses in the input
array are balanced using two helper methods `reduce` and `traverse`.
These methods implement the parallel reduction and the sequential traversal
part, respectively:
```scala
def parBalance(chars: Array[Char], threshold: Int): Boolean = {
def traverse(idx: Int, until: Int, _???_: Int, _???_: Int): ???
def reduce(from: Int, until: Int): ??? = ???
reduce(0, chars.length) == ???
}
```
In this case, we again use the fixed threshold parameter, as we did in the
lectures. Sections with size smaller or equal to the threshold should be processed sequentially.
For maximum performance, use a `while` loop in the `traverse` method, or make
`traverse` tail-recursive -- do not use a `Range`.
Now, run the `ParallelParenthesesBalancing` application from sbt:
```
> runMain reductions.ParallelParenthesesBalancingRunner
```
How large was your speedup?
If you are looking for additional challenges, prove that your reduction operator
is associative!
## Line of Sight
In the last part of the exercise, you will be implementing an entirely new
parallel algorithm -- you will apply the prefix sum algorithm to computing the
line-of-sight in two-dimensional terrain.
Imagine that you are standing at the zero of a coordinate system.
The curve to your right describes the terrain that you are facing.
This is shown in the following figure:
![terrain](terrain.png)
The task of the line-of-sight algorithm is to compute the visibility of each
point of the terrain, as shown in the following figure, where the visible area
is above of the full line, and the obscured terrain is shown with a dotted
line.
![visibility](visibility.png)
What is the necessary and sufficient condition for a point on the terrain to be
visibile from the zero of the coordinate system, where you are standing?
Imagine that the terrain heights are represented with an array of numbers.
We can compute (the tangent of) the viewing angle of each point on the terrain by dividing the
height of the terrain `xs(i)` with the distance from the viewing point `i`,
as shown in the following figure:
![angle](angle.png)
It turns out that if the viewing angle of some point B is **lower** than the
viewing angle of an earlier point A, then the point B is not visible, as shown
in the following figure:
![angle](angle2.png)
This simple realization allows us to easily compute the line-of-sight on the
terrain -- if you were a sequential programmer, you would traverse the array of
height values from the beginning to the end, and write the maximum angle seen so
far into the output array.
Implement the sequential `lineOfSight` method, which, for each height entry in
the `input` array (except for input(0) which is the location of the observer and
is always zero), writes the maximum angle until that point into the `output`
array (output(0) should be 0):
```scala
def lineOfSight(input: Array[Float], output: Array[Float]): Unit
```
We keep things simple -- instead of outputting an array of booleans denoting the
visibilities, we only output the angles.
Note that what we call an angle in this assignment is actually the tangent
of the angle. Indeed, `xs(i)` is the opposing side of the angle and `i` the adjacent side.
The ratio `xs(i) / i` that you compute is in fact the tangent of the angle!
Since the tangent of an angle is strictly increasing between
0° and 90°, it is a perfectly good replacement for the actual angle in our use case.
Keep this in mind and make sure that you do not apply any trigonometic functions on the tangent!
When we see a sequential algorithm that produces a sequence of values by
traversing the input from left to right, this is an indication that the
algorithm might have a parallel prefix sum variant.
So let's try to implement one!
Recall what you learned in the lectures -- the first phase of the parallel
prefix sum algorithm is the *upsweep* phase.
Here, the algorithm constructs the reduction tree by traversing parts of the
input array in parallel.
Implement the method `upsweepSequential`, which returns the maximum angle in a
given part of the array, and the method `upsweep`, which returns the reduction
tree over parts of the input array. If the length of the given part of the input
array is less than or equal to `threshold`, then `upsweep` calls `upsweepSequential`.
Note that the part of the input array that needs to traversed is represented
using indices 'from' (inclusive) and 'until' (or 'end') (exclusive).
```scala
def upsweepSequential(input: Array[Float], from: Int, until: Int): Float
```
```scala
def upsweep(input: Array[Float], from: Int, end: Int, threshold: Int): Tree
```
The `Tree` data type is either a `Leaf` or an inner `Node`, and it contains the
maximum angle in the corresponding part of the array.
Note that when the number of elements in a part of the input array,
which is `(end - from)`, is smaller or equal to the threshold, the sequential `upsweepSequential`
has to be invoked, and you should return a `Leaf`.
Otherwise, you should process the part of the input array in parallel, and return
a `Node`. Make sure that the work is evenly distributed between the parallel computations.
The second phase is called *downsweep* -- here, the algorithm uses the tree to
push the maximum angle in the corresponding *prefix* of the array to the leaves
of the tree, and outputs the values.
Implement the methods `downsweep` which processes parts of the tree in parallel,
and the method `downsweepSequential`, which traverses the parts of the array
corresponding to leaves of the tree and writes the final angles into the
`output` array:
```scala
def downsweep(input: Array[Float], output: Array[Float],
startingAngle: Float, tree: Tree): Unit
def downsweepSequential(input: Array[Float], output: Array[Float],
startingAngle: Float, from: Int, until: Int): Unit
```
Finally, implement `parLineOfSight` using the `upsweep` and `downsweep` methods:
```scala
def parLineOfSight(input: Array[Float], output: Array[Float],
threshold: Int): Unit
```
Now, run the `LineOfSight` application in sbt and observe the relative speedups:
```
> runMain reductions.LineOfSightRunner
```
How large is the speedup compared to the number of cores in your processor?
Can you explain your results?