How to writing a accumulator by using ScalaBlackBox? - chisel

I want to create some new number types that like DspReal for dsptools, such as DspPosit and DspQuire. DspPosit bases on posit which I have some Java code, and DspQuire bases on quire which is a kind of accumulator for posit. Because I just want to simulation now, so I have write many ScalaBlackBox for their operation like DspReal. However, I found that ScalaBlackBox can't construct sequential logic. For example, current output of the quire accumulator depends on it's input and last output. But ScalaBlackBox can't get the value of the output. In addition, step(n) also influences the output. Because accumulator will read its input per clock cycle.
I found some system problems of treadle. First, the function of ScalaBlackBox, twoOp and oneOp and so on, will be called many times. I don't know why. Second, step(n) is the function of PeekPokeTester, which can't be access by ScalaBlackBox. Third, I try to read current output but system gives errors.
trait DspBlackBlackBoxImpl extends BlackBoxImplementation with ScalaBlackBox
abstract class DspQuireAccumulator extends DspBlackBlackBoxImpl {
lazy val accValue = Quire32() // initial value
/**
* sub-classes must implement this two argument function
*
* #param posit accumulate element
* #return quire operation result
*/
def accOp(posit: Posit32): Unit
def outputDependencies(outputName: String): Seq[(String)] = {
outputName match {
case "out" => Seq("in") // Seq("out", "in") gives errors
case _ => Seq.empty
}
}
def cycle(): Unit = {}
def execute(inputValues: Seq[Concrete], tpe: Type, outputName: String): Concrete = {
val arg1 :: _ = inputValues
val positArg = Posit32(arg1.value)
accOp(positArg)
val result = quire32ToBigInt(accValue)
ConcreteSInt(result, DspQuire.underlyingWidth, arg1.poisoned).asUInt
}
def getOutput(inputValues: Seq[BigInt], tpe: Type, outputName: String): BigInt = {
val arg1 :: _ = inputValues
val positArg = Posit32(arg1)
accOp(positArg)
quire32ToBigInt(accValue)
}
}
class DspQuireAddAcc(val name: String) extends DspQuireAccumulator {
def accOp(posit: Posit32): Unit = accValue += posit
}
class QuireBlackboxAccOperand extends BlackBox {
val io = IO(new Bundle() {
val in = Input(UInt(DspPosit.underlyingWidth.W))
val out = Output(UInt(DspQuire.underlyingWidth.W))
})
}
class BBQAddAcc extends QuireBlackboxAccOperand
class TreadleDspQuireFactory extends ScalaBlackBoxFactory {
def createInstance(instanceName: String, blackBoxName: String): Option[ScalaBlackBox] = {
blackBoxName match {
case "BBQAddAcc" => Some(add(new DspQuireAddAcc(instanceName)))
...
accOp will be called many times. So, if I want to accumulate List(1, 2, 3), the result maybe 0 + 1 + 1 + 2 + 2 + ...
And peek function will call accOp one time again, this makes me confused also.

I believe most of your problems at this point are caused by mixing two different approaches. I think you should not be using BlackBoxImplmentation because it is an older scheme used in with the firrtl-interpreter. Just use the ScalaBlackBox and implement the methods as described in the wiki page Black Boxes and Treadle and shown in the TreadleTest BlackBoxWithState.
Don't use outputDependencies, and instead specify any dependencies between inputs and outputs with with getDependencies. inputChanged will be called whenever an input IO is changed. So in that method you want to record or update the internal state of your black box. clockChange will be called whenever a clock is changed and will provide the transition information so you can decide what happens then. Treadle will call getOutput whenever it needs that output of your black box, since you will not have used outputDependencies you can ignore the inputs and just provide the output value depending on your internal state.
I am still trying to reproduce a running version of your code here but it will be a little time for me to put it together, if you can try my suggestions above and let me know how it goes that would be helpful. I am interested in making this feature of Treadle better and easier to use so all feedback is appreciated.

Related

Is there an accepted way to get a Gray Code counter in Chisel?

I'm looking to write counters in Chisel3 that will be used to address subunits. If the counter matches some register in a subunit then the subunit fires, otherwise it doesn't.
I would much rather have the addresses cycle in Gray code than in binary. It's easy enough to write a binary counter in Chisel, but I see no provision for a Gray code counter.
I can write a new type akin to Uint and Sint, but I'm reluctant to reinvent it if it's already out there. Yet I don't see anything in the cookbook or other docs about Gray code. Github just turns up a Minecraft-oriented repo (because it matches "chisel") There is existing stuff for VHDL but I want to express this in Chisel.
So have I missed a resource that would provide a Gray counter in Chisel? Failing that, is building a new type akin to Uint a reasonable way to proceed?
I did a quick look around and didn't find anything quite like what you're looking for. The closest thing I could find was a simple Gray counter in rocket-chip (https://github.com/chipsalliance/rocket-chip/blob/29ce00180f2a69947546d6385a1da86cbc584376/src/main/scala/util/AsyncQueue.scala#L49) but it uses regular binary counting and then just returns a UInt in Gray code. It also doesn't take advantage of any Scala type safety.
I think this would be a reasonable thing to build, and if you want you could contribute it to https://github.com/freechipsproject/ip-contributions for increased visibility.
I think if you wanted a proper GrayCode type, it would be reasonable to create a custom type. Unfortunately, there is no way to extend Data for a Bits-like type (all of the types in that hierarchy are sealed), but you could create a custom Bundle that wraps a UInt and then implement your own set of operations, eg.
class GrayCode(private val w: Int) extends Bundle {
val value = UInt(w.W)
def +(that: GrayCode): GrayCode = ???
}
object GrayCode {
// Lets you write GrayCode(4.W)
// Width is defined in chisel3.internal.firrtl though which is awkward...
def apply(width: Width): GrayCode = ???
}
This is just a quick sketch. The DSP Tools library has examples of custom types for DSP: https://github.com/ucb-bar/dsptools
They tend to use Scala Typeclasses a lot which is a more advanced Scala feature. Just mentioning in case some of the syntax in their looks alien.
You might take a look at this link programmersought gray code fifo it seems like it may be relevant but I am not familiar with it otherwise.
As with Jack I'm not familiar with the math needed to actually increment values in Gray code, but something like the following code would convert Gray code to binary, add, then convert it back to Gray code. I'm not sure if the Vec() code below would work correctly but should make the idea clear.
import chisel3._
import chisel3.util._
class GrayCode(private val w: Int) extends Bundle {
val value = UInt(w.W)
def bin2grey(x : UInt) : UInt = {
x ^ (x >> 1.U)
}
def grey2bin(x : UInt, n : Int) : UInt = {
val tmp = Wire(Vec(n, Bool()))
tmp(n-1) := x(n-1)
for (i <- 0 to (n-2)) {
tmp(i) := x(i) ^ tmp(i+1)
}
Cat(tmp.reverse)
}
def +(that: GrayCode): GrayCode = {
val sum = new GrayCode(w)
sum.value := grey2bin(bin2grey(this.value) + bin2grey(that.value), w)
sum
}
}
It seems like all implementations here use binary-to-Gray conversion. For asynchronous FIFOs, this only works if the Gray code is latched just before crossing clock domains. What if you want a counter that actually counts Gray codes instead of converting binary values to Gray codes?
One option is to convert Gray to binary, add, then convert back to Gray and store the result. The other is to use custom arithmetic to calculate the next Gray value in the sequence. The typical sequence is a reflected-binary Gray code, but others exist.
The code below implements a Gray code counter using a reflected-binary Gray code. It was adapted from this blog post. It only counts up. It works like the Chisel Counter object, except it adds support for a synchronous reset and custom register name. It returns the counter and wrap status.
import chisel3._
import chisel3.util._
// a Gray counter counts in Gray code
object GrayCounter {
// Gray unit cell
// b is the current state of this bit
// returns (t, z_o) where t is the next state of this bit
def grayCell(b: Bool, q_i: Bool, z_i: Bool, enable: Bool, parity: Bool): (Bool, Bool) = {
(b ^ (enable && q_i && z_i && parity), (!q_i) && z_i)
}
// cond = counts when true
// n = count value, must be a power of 2
// synchronousReset = resets counter to 0
// name = name for this counter
def apply(cond: Bool, n: Int, synchronousReset: Bool = false.B, name: String = null) = {
require(isPow2(n), s"Gray counter must have power-of-2 length (you asked for $n)")
require(n > 2, s"Gray counter minimum count is 4 (you asked for $n)")
val counter = RegInit(0.U(log2Ceil(n).W))
if (name != null) {
counter.suggestName(name)
}
val counterNext = Wire(Vec(log2Ceil(n), Bool()))
counter := counterNext.asUInt
val z_wires = Wire(Vec(log2Ceil(n), Bool()))
val parity = counter.xorR
for (i <- 0 until log2Ceil(n)) {
if (i == 0) {
val grayCellOut = grayCell(counter(i), true.B, true.B, cond, !parity)
counterNext(i) := grayCellOut._1
z_wires(i) := grayCellOut._2
} else {
val grayCellOut = grayCell(counter(i), counter(i-1) || (i == log2Ceil(n)-1).B,
z_wires(i-1) || (i == 1).B, cond, parity)
counterNext(i) := grayCellOut._1
z_wires(i) := grayCellOut._2
}
}
when (synchronousReset) {
counter := 0.U
}
val wrap = counter === (n/2).U && cond
(counter, wrap)
}
}

Could not find implicit value for parameter c: anorm.Column[Float]

I got this similar question but it doesn't help me. (Anorm parse float values). And I can honestly say I didn't understand the solution of that question.
I am getting this complie time error:
could not find implicit value for parameter c: anorm.Column[Float]
at
def getInformation(id: Long): List[(Float, Float, Float)] = {
DB.withConnection { implicit con =>
val query = SQL("select principal,interest,value from myTable where userId={id} and status=true").on("id"->id)
val result = query().map { row =>
Tuple3(row[Float]("principal"), row[Float]("inetrest"), row[Float]("value"))
// ^
}.toList
return result
}
}
Maybe a short review of implicits help you. Let's construct a very basic example:
// some class which will be used as implicit (can be anything)
case class SomeImplicitInformation(maybe: Int, with: Int, data: Int)
// lets assume we have a function that requires an implicit
def functionRequiringImplicit(regularParameters: Int)(implicit imp: SomeImplicitInformation) {
// ...
}
// now if you try to call the function without having an implicit in scope
// you would have to pass it explicitly as second parameter list:
functionRequiringImplicit(0)(SomeImplicitInformation(0,0,0))
// instead you can declare an implicit somewhere in your scope:
implicit val imp = SomeImplicitInformation(0,0,0)
// and now you can call:
functionRequiringImplicit(0)
The error you get simply says that anorm.Column[Float] in not in the scope as implicit. You can solve it by adding it implicitly to your scope or pass it explicitly.
More detailed instructions for you: Since the Column companion object only provides an implicit for rowToDouble you simply have to use the code that is linked in your question. To get it to work put it before your result computation. Later you might want to place it in a val in some enclosing scope.
try this...
def getInformation(id: Long): List[(Float, Float, Float)] = {
DB.withConnection { implicit con =>
val query = SQL("select principal,interest,value from myTable where userId={id} and status=true").on("id"->id)
val result = query().map { row =>
Tuple3(row[Float]("principal").asInstanceOf[Float], row[Float]("inetrest").asInstanceOf[Float], row[Float]("value").asInstanceOf[Float])
}.toList
return result
}
}
implicit def rowToFloat: Column[Float] = Column.nonNull { (value, meta) =>
val MetaDataItem(qualified, nullable, clazz) = meta
value match {
case d: Float => Right(d)
case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass + " to Float for column " + qualified))
}
}
Some functions can accept what we call implicit parameters. Such parameters can, under certain conditions, be derived from the context. If these parameters can't be found, then you have to specify them by hand. If you expect a parameter to be used as an implicit one, it must have been declared implicit, for instance this way :
implicit val myVal = ...
It can be done in the current block or in an enclosing one (in the class body, for instance, or even sometimes in the imports)
The error you get seems to be related to this feature. You're using a function that needs a parameter of type anorm.Column[Float]. The argument is defined to be implicit so that an implicit value can be used and your code may be more concise. Unfortunately, you don't seem to have such an implicit value in your code, so it fails.
Latest Anorm (included in Play 2.3) provides more numeric conversion (see details at http://applicius-en.tumblr.com/post/87829484643/anorm-whats-new-play-2-3 & in Play migration notes).
If you have missing converter, you can add an issue on Play github project.
Best

Scala Saving Sort Function Parameters

I'm trying to save the parameters used to sort a sequence in Scala for deferred execution at a later time.
For example, instead of "list.sortBy (.value)", I want to save the (".value") sort function, and retrieve this sort function ("_.value") at a later time for the actual sorting.
How do I save and retrieve the sort function arguments for deferred execution? Here is some sample test code:
class SortTest {
def testSort () = {
val myClass = new MyClass(0)
val list = List (myClass, new MyClass(1), new MyClass(2), new MyClass(3), new MyClass(4))
// Want to sort by value attribute, but don't want to sort right away. Rather
// how do I save the sort function, and retrieve it at a later time for execution?
list.sortBy(_.value)
// save the sort function (i.e. sort by the value attribute of myClass)
// something similar to the following syntax
myClass.setSortFunction (_.value)
// retrieve the sort function and sort the list
list.sortBy(myClass.getSortFunction())
}
class MyClass (d:Int){
val value = d
val sortFunc = null
// what should be the signature of this function ?
def setSortFunction (sortFunc: ()) = {
this.sortFunc = sortFunc
}
// what should be the return type of this function?
def getSortFunction () = {
return sortFunc
}
}
}
You could do something like this:
val sortFunction = (x : { def value: Int } ) => x.value
At this point, you might not be happy with the hardcoding of Int. Unfortunately, a function must have well defined types, so I cannot make this generic on the return type.
One could instead make it a definition:
def sortFunction[T] = (x : { def value: T } ) => x.value
However, you cannot pass definitions around, only values, and values cannot be parameterized.
On the other hand, you are approaching this the wrong way -- there's an assumption there that sortBy takes a function as a parameter, and only that. Not true: sortBy takes two parameters: a function, and an Ordering. If you don't save the ordering, you cannot sort it.
And here we get to the other problem... the function must have a type MyClass => T, and the ordering must be of type Ordering[T]. Without knowing in advance what T is, you cannot save that.
Fortunately, and the reason why Ordering is a good idea, you can simply create an Ordering[MyClass], and use that!
Here's how:
class MyClass(d: Int) {
val value = d
private var sortFunction: Ordering[MyClass] = _
def setSortFunction[T : Ordering](f: MyClass => T) {
sortFunction = Ordering by f
}
def getSortFunction = sortFunction
}
And you use it like this:
list.sorted(myClass.getSortFunction)
Notice that instead of sortBy it uses sorted. The method sortBy is implemented by creating an Ordering and calling sorted with it, so you are not losing any performance.

What are the implications of using def vs. val for constant values

What are the implications of using def vs. val in Scala to define a constant, immutable value? I obviously can write the following:
val x = 3;
def y = 4;
var a = x + y; // 7
What's the difference between those two statements? Which one performs better / is the recommended way / more idiomatic? When would I use one over the other?
Assuming these are class-level declarations:
The compiler will make a val final, which can lead to better-optimised code by the VM.
A def won't store the value in the object instance, so will save memory, but requires the method to be evaluated each time.
For the best of both worlds, make a companion object and declare constants as vals there.
i.e. instead of
class Foo {
val MyConstant = 42
}
this:
class Foo {}
object Foo {
val MyConstant = 42
}
The val is evaluated once and stored in a field. The def is implemented as a method and is reevaluated each time, but does not use memory space to store the resulting value.

Passing functions and operating on their results within Scala's Actors

I'm implementing an actor-based app in scala and I'm trying to be able to pass functions between the actors for them to be processed only when some message is received by the actor.
import actors.Actor
import java.util.Random
import scala.Numeric._
import Implicits._
class Constant(val n:Number) extends Actor{
def act(){
loop{
receive{
case "value" => reply( {n} )
}
}
}
}
class Arithmetic[T: Numeric](A: ()=>T, B: ()=>T) extends Actor{
def act(){
receive{
case "sum" => reply ( A() + B() )
/* case "mul" => reply ( A * B )
*/
}
}
}
object Main extends App{
val c5 = new Constant(5)
c5.start
val a = new Arithmetic({c5 !! "value"}, {c5!!"value"} )
a.start
println(a!?"sum")
println(a!?"mul")
}
In the example code above I would expect the output to be both 5+5 and 5*5. The issue is that reply is not a typed function and as such I'm unable to have the operator (+,*) to operate over the result from A and B.
Can you provide any help on how to better design/implement such system?
Edit: Code updated to better reflect the problem. Error in:
error: could not find implicit value for evidence parameter of type Numeric[Any]
val a = new Arithmetic({c5 !! "value"}, {c5!!"value"} )
I need to be able to pass the function to be evaluated in the actor whenever I call it. This example uses static values but I'll bu using dynamic values in the future, so, passing the value won't solve the problem. Also, I would like to receive different var types (Int/Long/Double) and still be able to use the same code.
The error: Error in: error: could not find implicit value for evidence parameter of type Numeric[Any]. The definition of !!:
def !! (msg: Any): Future[Any]
So the T that Arithmetic is getting is Any. There truly isn't a Numeric[Any].
I'm pretty sure that is not your problem. First, A and B are functions, and functions don't have + or *. If you called A() and B(), then you might stand a chance... except for the fact that they are java.lang.Number, which also does not have + or * (or any other method you'd expect it to have).
Basically, there's no "Number" type that is a superclass or interface of all numbers for the simple reason that Java doesn't have it. There's a lot of questions touching this subject on Stack Overflow, including some of my own very first questions about Scala -- investigate scala.math.Numeric, which is the best approximation for the moment.
Method vs Function and lack of parenthesis
Methods and functions are different things -- see tons of related questions here, and the rule regarding dropping parenthesis is different as well. I'll let REPL speak for me:
scala> def f: () => Int = () => 5
f: () => Int
scala> def g(): Int = 5
g: ()Int
scala> f
res2: () => Int = <function0>
scala> f()
res3: Int = 5
scala> g
res4: Int = 5
scala> g()
res5: Int = 5