scala foreach of a 2-D List/Array in chisel with types issue - scala

Can "foreach" can be used for each element of the 2-D List/Array?
I tried the code:
val n_vec = (0 to 2).map(i=>
(0 to 2).map(j=>
Wire(UInt(3.W))
)
)
n_vec.foreach((i:Int)=>(
n_vec(i).foreach((j:Int)=>{
n_vec(i)(j) := i.U + j.U
})
))
the error message is
top.scala:24: error: type mismatch;
found : Int => Unit
required: chisel3.core.UInt => ?
n_vec(i).foreach((j:Int)=>{
^
Could you enlight me whether it can be used in such a way, even how?

It would be cleaner to write like this:
n_vec.foreach { i=>
i.foreach { j=>
j := x.U + y.U
y = y + 1
}
y = 0
x = x + 1
}
But you don't need to increment x and y manually, just iterate over indices instead:
n_vec.indices.foreach { x =>
n_vec(x).indices.foreach { y =>
n_vec(x)(y) := x.U + y.U
}
}
or better (and this translates exactly to the above)
for {
x <- n_vec.indices
y <- n_vec(x).indices
} {
n_vec(x)(y) := x.U + y.U
}

Yes it can be used this way.
solution:
var x = 0
var y = 0
n_vec.foreach(i=>{
i.foreach(j=>{
j := x.U + y.U
y = y + 1
})
y = 0
x = x + 1
})
x = 0
y = 0

Related

For loop with two variables in scala

I have the following java code:
for (int i = 0, j = 0; i < 10 && j < 10 0; i++, j++)
{
System.out.println("i = " + i + " :: " + "j = " + j);
}
The output is :
i = 0 :: j = 0
i = 1 :: j = 1
i = 2 :: j = 2
i = 3 :: j = 3
i = 4 :: j = 4
i = 5 :: j = 5
....
I would like to do the same thing in scala, I tried this but it does not work:
for (i<- 0 to 9; j <- 0 to 9)
{
println("i = " + i + " :: " + "j = " + j)
}
The output is:
i = 0 :: j = 0
i = 0 :: j = 1
i = 0 :: j = 2
i = 0 :: j = 3
i = 0 :: j = 4
i = 0 :: j = 5
i = 0 :: j = 6
i = 0 :: j = 7
i = 0 :: j = 8
i = 0 :: j = 9
i = 1 :: j = 0
i = 1 :: j = 1
i = 1 :: j = 2
i = 1 :: j = 3
....
I have not find a way to have two variables in the same level.
Thank you for your answer.
Scala's replacement would be
for {
(i, j) <- (0 to 9) zip (0 to 9)
} {
println("i = " + i + " :: " + "j = " + j)
}
To avoid the confusion I suggest reading what for is the syntactic sugar for (as opposed to Java it is not specialized while).
Since both variables always have the same value, you actually only need one of them. In Scala, you would generally not use a loop to solve this problem, but use higher-level collection operations instead. Something like:
(0 to 9) map { i => s"i = $i :: j = $i" } mkString "\n"
Note: this will only generate the string that you want to print, but not actually print it. It is generally considered a good thing to not mix generating data and printing data.
If you want to print this, you only need to pass it to println:
println((0 to 9) map { i => s"i = $i :: j = $i" } mkString "\n")
Or, in Scala 2.13+:
import scala.util.chaining._
(0 to 9) map { i => s"i = $i :: j = $i" } mkString "\n" pipe println
You could also write it like this:
(for (i <- 0 to 9) yield s"i = $i :: j = $i") mkString "\n"
Now, you might say, "Wait a minute, didn't you just say that we don't use loops in Scala?" Well, here's the thing: that's not a loop! That is a for comprehension. It is actually syntactic sugar for collection operations.
for (foo <- bar) yield baz(foo)
is actually just syntactic sugar for
bar map { foo => baz(foo) }
A for comprehension simply desugars into calls to map, flatMap, foreach, and withFilter. It is not a loop.
Note that Scala does have a while loop. It exists mainly for performance reasons. Unless you are writing low-level libraries that are going to be used in performance-intensive code by tens of thousands of developers, please just pretend that it doesn't exist.
Also note that if the while loop weren't built into Scala, you could easily write it yourself:
def whiley(cond: => Boolean)(body: => Unit): Unit =
if (cond) { body; whiley(cond)(body) }
you can do it as below
val start = 0; val size = 10;
for ((i, j) <- (start to size) zip (start to size))
{
println(s"i=$i j=$j")
}
j is just a copy of i so this is one solution:
for {
i <- 0 to 9
j = i
} {
println("i = " + i + " :: " + "j = " + j)
}
This pattern works in any situation where j is just a function of i

Acting on inner and outer loops for multidimensional array in idiomatic scala

I have this nested loop:
for ( y <- 0 to 5) {
for ( x <- 0 to 5) {
print(x, y)
}
println()
}
Is there a cleaner way of expressing this in scala -- bearing in mind I want to do something once for every outer loop iteration, as well as the internal?
The following is the closest I've got:
for {
y <- 0 to 5
x <- 0 to 5
} {
print (x, y) + " "
if(x == 5) println()
}
for {
y <- 0 to 5
x <- 0 to 5
_ = if (x ==5) println()
} print(x, y)
Seems like the most concise way to me.
I don't think for comprehensions are a good option here, why not just use foreach? like this:
(0 to 5).foreach{ y =>
(0 to 5).foreach{ x =>
print (x, y) + " "
}
println()
}

Scala Mismatch MonteCarlo

I try to implement a version of the Monte Carlo algorithm in Scala but i have a little problem.
In my first loop, i have a mismatch with Unit and Int, but I didn't know how to slove this.
Thank for your help !
import scala.math._
import scala.util.Random
import scala.collection.mutable.ListBuffer
object Main extends App{
def MonteCarlo(list: ListBuffer[Int]): List[Int] = {
for (i <- list) {
var c = 0.00
val X = new Random
val Y = new Random
for (j <- 0 until i) {
val x = X.nextDouble // in [0,1]
val y = Y.nextDouble // in [0,1]
if (x * x + y * y < 1) {
c = c + 1
}
}
c = c * 4
var p = c / i
var error = abs(Pi-p)
print("Approximative value of pi : $p \tError: $error")
}
}
var liste = ListBuffer (200, 2000, 4000)
MonteCarlo(liste)
}
A guy working usually with Python.
for loop does not return anything, so that's why your method returns Unit but expects List[Int] as return type is List[Int].
Second, you have not used scala interpolation correctly. It won't print the value of error. You forgot to use 's' before the string.
Third thing, if want to return list, you first need a list where you will accumulate all values of every iteration.
So i am assuming that you are trying to return error for all iterations. So i have created an errorList, which will store all values of error. If you want to return something else you can modify your code accordingly.
def MonteCarlo(list: ListBuffer[Int]) = {
val errorList = new ListBuffer[Double]()
for (i <- list) {
var c = 0.00
val X = new Random
val Y = new Random
for (j <- 0 until i) {
val x = X.nextDouble // in [0,1]
val y = Y.nextDouble // in [0,1]
if (x * x + y * y < 1) {
c = c + 1
}
}
c = c * 4
var p = c / i
var error = abs(Pi-p)
errorList += error
println(s"Approximative value of pi : $p \tError: $error")
}
errorList
}
scala> MonteCarlo(liste)
Approximative value of pi : 3.26 Error: 0.11840734641020667
Approximative value of pi : 3.12 Error: 0.02159265358979301
Approximative value of pi : 3.142 Error: 4.073464102067881E-4
res9: scala.collection.mutable.ListBuffer[Double] = ListBuffer(0.11840734641020667, 0.02159265358979301, 4.073464102067881E-4)

Scala Branch And Bound Motif Search

Below code searches for a motif (of length 8) in a sequence(String) and, as the result, it has to give back sequence with the best score. The problem is, although the code produces no errors, there is no output at all (probably infinite cycle, I observe blank console).
I am gonna give all my code online and if that is required. In order to reproduce the problem, just pass a number (between 0 and 3 - you can give 4 sequence, so you must choose 1 of them 0 is the first , 1 is the second etc) as args(0) (e.g. "0"), expected output should look something like "Motif = ctgatgta"
import scala.util.control._
object BranchAndBound {
var seq: Array[String] = new Array[String](20)
var startPos: Array[Int] = new Array[Int](20)
var pickup: Array[String] = new Array[String](20)
var bestMotif: Array[Int] = new Array[Int](20)
var ScoreMatrix = Array.ofDim[Int](5, 20)
var i: Int = _
var j: Int = _
var lmer: Int = _
var t: Int = _
def main(args: Array[String]) {
var t1: Long = 0
var t2: Long = 0
t1 = 0
t2 = 0
t1 = System.currentTimeMillis()
val seq0 = Array(
Array(
" >5 regulatory reagions with 69 bp",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaatttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"),
Array(
" 2 columns mutants",
" cctgatagacgctatctggctatccaggtacttaggtcctctgtgcgaatctatgcgtttccaaccat",
" agtactggtgtacatttgatccatacgtacaccggcaacctgaaacaaacgctcagaaccagaagtgc",
" aaacgttagtgcaccctctttcttcgtggctctggccaacgagggctgatgtataagacgaaaattttt",
" agcctccgatgtaagtcatagctgtaactattacctgccacccctattacatcttacgtccatataca",
" ctgttatacaacgcgtcatggcggggtatgcgttttggtcgtcgtacgctcgatcgttaccgtacggc"))
var k: Int = 0
var m: Int = 0
var n: Int = 0
var bestScore: Int = 0
var optScore: Int = 0
var get: Int = 0
var ok1: Boolean = false
var ok3: Boolean = false
ok1 = false
ok3 = false
j = 1
lmer = 8
m = 1
t = 5
n = 69
optScore = 0
bestScore = 0
k = java.lang.Integer.parseInt(args(0))
j = 1
while (j <= t) {
seq(j) = new String()
i = 0
while (i < n) {
seq(j) += seq0(k)(j).charAt(i)
i += 1
}
j += 1
}
j = 1
while (j <= t) {
newPickup(1, j)
j += 1
}
j = 0
bestScore = 0
i = 1
val whilebreaker = new Breaks
whilebreaker.breakable {
while (i > 0) {
if (i < t) {
if (startPos(1) == (n - lmer)) whilebreaker.break
val sc = Score()
optScore = sc + (t - i) * lmer
if (optScore < bestScore) {
ok1 = false
j = i
val whilebreak1 = new Breaks
whilebreak1.breakable {
while (j >= 1) {
if (startPos(j) < n - lmer) {
ok1 = true
newPickup(0, j)
whilebreak1.break
} else {
ok1 = true
newPickup(1, j)
val whilebreak2 = new Breaks
whilebreak2.breakable {
while (startPos(i - 1) == (n - lmer)) {
newPickup(1, i - 1)
i -= 1
if (i == 0) whilebreak2.break
}
}
if (i > 1) {
newPickup(0, i - 1)
i -= 1
}
whilebreak1.break
}
}
}
if (ok1 == false) i = 0
} else {
newPickup(1, i + 1)
i += 1
}
} else {
get = Score()
if (get > bestScore) {
bestScore = get
m = 1
while (m <= t) {
bestMotif(m) = startPos(m)
m += 1
}
}
ok3 = false
j = t
val whilebreak3 = new Breaks
whilebreak3.breakable {
while (j >= 1) {
if (startPos(j) < n - lmer) {
ok3 = true
newPickup(0, j)
whilebreak3.break
} else {
ok3 = true
newPickup(1, j)
val whilebreak4 = new Breaks
whilebreak4.breakable {
while (startPos(i - 1) == (n - lmer)) {
newPickup(1, i - 1)
i -= 1
if (i == 0) whilebreak4.break
}
}
if (i > 1) {
newPickup(0, i - 1)
i -= 1
}
whilebreak3.break
}
}
}
if (ok3 == false) i = 0
}
}
}
println("Motiv: " + Consensus())
// println()
j = 1
while (j <= t) {
t2 = System.currentTimeMillis()
j += 1
}
println("time= " + (t2 - t1) + " ms")
}
def Score(): Int = {
var j: Int = 0
var k: Int = 0
var m: Int = 0
var max: Int = 0
var sum: Int = 0
sum = 0
max = 0
m = 1
while (m <= lmer) {
k = 1
while (k <= 4) {
ScoreMatrix(k)(m) = 0
k += 1
}
m += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= i) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
m += 1
}
j = 1
while (j <= lmer) {
max = 0
m = 1
while (m <= 4) {
if (ScoreMatrix(m)(j) > max) {
max = ScoreMatrix(m)(j)
}
m += 1
}
sum += max
j += 1
}
sum
}
def Consensus(): String = {
var i: Int = 0
var j: Int = 0
var k: Int = 0
var m: Int = 0
var max: Int = 0
var imax: Int = 0
var str: String = null
i = 1
while (i <= t) {
pickup(i) = " " +
seq(i).substring(bestMotif(i), bestMotif(i) + lmer)
i += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= 4) {
ScoreMatrix(k)(m) = 0
k += 1
}
m += 1
}
m = 1
while (m <= lmer) {
k = 1
while (k <= t) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
m += 1
}
str = ""
imax = 0
j = 1
while (j <= lmer) {
max = 0
i = 1
while (i <= 4) {
if (ScoreMatrix(i)(j) > max) {
max = ScoreMatrix(i)(j)
imax = i
}
i += 1
}
imax match {
case 1 => str += 'a'
case 2 => str += 'c'
case 3 => str += 'g'
case 4 => str += 't'
}
j += 1
}
str
}
def newPickup(one: Int, h: Int) {
if (one == 1) startPos(h) = 1 else startPos(h) += 1
pickup(h) = " " + seq(h).substring(startPos(h), startPos(h) + lmer)
}
}
and thanks, i hope someone gonna find my failure.
Your current implementation 'hangs' on this loop:
while (k <= i) pickup(k).charAt(m) match {
case 'a' => ScoreMatrix(1)(m) += 1
case 'c' => ScoreMatrix(2)(m) += 1
case 'g' => ScoreMatrix(3)(m) += 1
case 't' => ScoreMatrix(4)(m) += 1
}
As it stands, the exit condition is never fulfilled because the relation between k and i never changes. Either increment k or decrement i.
It looks like programming is not the key aspect of this work, but increased modularity should help contain complexity.
Also, I wonder about the choice of using Scala. There're many areas in this algorithm that would benefit of a more functional approach. In this translation, using Scala in an imperative way gets cumbersome. If you have the opportunity, I'd recommend you to explore a more functional approach to solve this problem.
A tip: The intellij debugger didn't have issues with this code.

How to do X * diag(Y) in Scala Breeze?

How to do X * diag(Y) in Scala Breeze? X could be for example a CSCMatrix and Y could be a DenseVector?
In MATLAB syntax, this would be:
X * spdiags(0, Y, N, N )
Or:
X .* repmat( Y', K, 0 )
In SciPy syntax, this would be a 'broadcast multiply':
Y * X
How to do X * diag(Y) in Scala Breeze?
I wrote my own sparse diagonal method, and dense / sparse multiplication method in the end.
Use like this:
val N = 100000
val K = 100
val A = DenseMatrix.rand(N,K)
val b = DenseVector.rand(N)
val c = MatrixHelper.spdiag(b)
val d = MatrixHelper.mul( A.t, c )
Here are the implementations of spdiag and mul:
// Copyright Hugh Perkins 2012
// You can use this under the terms of the Apache Public License 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package root
import breeze.linalg._
object MatrixHelper {
// it's only efficient to put the sparse matrix on the right hand side, since
// it is a column-sparse matrix
def mul( A: DenseMatrix[Double], B: CSCMatrix[Double] ) : DenseMatrix[Double] = {
val resultRows = A.rows
val resultCols = B.cols
var row = 0
val result = DenseMatrix.zeros[Double](resultRows, resultCols )
while( row < resultRows ) {
var col = 0
while( col < resultCols ) {
val rightRowStartIndex = B.colPtrs(col)
val rightRowEndIndex = B.colPtrs(col + 1) - 1
val numRightRows = rightRowEndIndex - rightRowStartIndex + 1
var ri = 0
var sum = 0.
while( ri < numRightRows ) {
val inner = B.rowIndices(rightRowStartIndex + ri)
val rightValue = B.data(rightRowStartIndex + ri)
sum += A(row,inner) * rightValue
ri += 1
}
result(row,col) = sum
col += 1
}
row += 1
}
result
}
def spdiag( a: Tensor[Int,Double] ) : CSCMatrix[Double] = {
val size = a.size
val result = CSCMatrix.zeros[Double](size,size)
result.reserve(a.size)
var i = 0
while( i < size ) {
result.rowIndices(i) = i
result.colPtrs(i) = i
result.data(i) = i
//result(i,i) = a(i)
i += 1
}
//result.activeSize = size
result.colPtrs(i) = i
result
}
}