PyGears How to make AND gate - pygears

Let's say I have two modules M1 and M2 and both of them are outputting 32 bits data. I would like to do logic AND for each bit. How to do it?
I have been looking into Library on GitHub but couldn't find module for AND operation.
I would like to do next:
X[0] = M1[0] && M2[0]
X[1] = M1[1] && M2[1]
etc.

Code example of add_gate:
#gear
async def and_gate(arg1, arg2) -> (Uint[32]):
async with arg1 as a1:
async with arg2 as a2:
res = a1 & a2
yield res
#alternative(and_gate)
#gear
async def and_gate_one_arg(args) -> (Uint[32]):
async with args as (a1, a2):
res = a1 & a2
yield res
res_two = []
res_one = []
#gear
def consumer():
arg1 = once(val=31, tout=Uint[32])
arg2 = once(val=15, tout=Uint[32])
args = once(val=(15, 31), tout=Tuple[Uint[32], Uint[32]])
bits_and_two_args = and_gate(arg1, arg2)
bits_and_one_arg = and_gate(args)
collect(bits_and_two_args, result=res_two)
collect(bits_and_one_arg, result=res_one)
consumer()
sim()
print(res_one)
print(res_two)
How it represents in GearBox:

Related

Scala filter and multiple predicates reporting

I have a 4 predicates
private def pred1(ep:MyClass):Boolean = ep.attr1.contains(true) && func1(ep)
private def pred2(ep:MyClass):Boolean = ep.attr1.contains(true) && !func1(ep)
private def pred3(ep:MyClass):Boolean = ep.attr1.contains(false) && func2(ep)
private def pred4(ep:MyClass):Boolean = ep.attr1.contains(false) && !func2(ep)
I then have a list that I want to filter by each of the predicates like so.
val ep: Seq[MyClass] = ???
val v1 = es.filter(pred1)
val v2 = es.filter(pred2)
val v3 = es.filter(pred3)
val v4 = es.filter(pred4)
How do I get values of v1, v2, v3, v4 with the correct predicates in a single filter and report it as a 4 tuple (v1,v2,v3,v4)? Or something similar. I do not want to do this 4 times. I have a huge sequence and this is not optimized
You can use a fold like this ..
ep.foldLeft[(Seq[MyClass], Seq[MyClass], Seq[MyClass], Seq[MyClass])]
((Nil,Nil,Nil,Nil)) { case ((a,b,c,d), i) =>
(
if (pred1(i)) a :+ i else a,
if (pred2(i)) b :+ i else b,
if (pred3(i)) c :+ i else c,
if (pred4(i)) d :+ i else d
)
}

.zip three futures in Scala [duplicate]

This question already has answers here:
Return Future[(Int,Int)] instead of (Future[Int],Future[Int])
(2 answers)
Closed 5 years ago.
I need the result variable below to contain Future[(String,String,String)] with the result of futures f1, f2 and f3, but instead I'm getting Future[((String, String), String)]. I need the three futures to run in parallel. How to make this work?
def futureA = Future { "A" }
def futureB = Future { "B" }
def futureC = Future { "C" }
def futureFunc = {
val cond1 = 1
val cond2 = 0
val f1 = if (cond1 > 0)
futureA
else
Future {""}
val f2 = if (cond2 > 0)
futureB
else
Future {""}
val f3 = futureC
val fx = f1.zip(f2)
val result = fx.zip(f3)
}
If you create your futures beforehand, you can combine them in a for comprehension and they will run in parallel:
for {
a <- f1
b <- f2
c <- f3
} yield (a, b, c)
res0: scala.concurrent.Future[(String, String, String)]
I tried to create more solutions and here is result:
def futureFunc = {
val cond1 = 1
val cond2 = 0
val f1 = if (cond1 > 0)
futureA
else
Future {""}
val f2 = if (cond2 > 0)
futureB
else
Future {""}
val f3 = futureC
//#1
Future.sequence(List(f1, f2, f3)).map {
case List(a, b, c) => (a, b, c)
}
//#2
for{
f11 <- f1
f22 <- f2
f33 <- f3
} yield (f11, f22, f33)
//#3
f1.zip(f2).zip(f3).map{
case ((f11,f22),f33) => (f11,f22,f33)
}
}
First one uses Future sequence, for creating Future[List[]] and then mapping this list for tuple (because of type safety we don't have method for tupling list).
Second is usage of for comprehension as described by Sascha, as you may know it is syntactic sugar for maps and flatmaps which is preferred to work with futures.
Last one is using zips, as you wanted, but you still need to map last future to obtain tuple which you want.
All operations are non blocking, but for all operations you need to know exactly futures which you will be using. You can use additional libraries for tupling lists, and then use first solution for not well known amount for futures. For readability i think for comprehension is best.

Running futures sequentially

The objective of the code below is to execute Future f3 or f4 depending on a condition. Note that the condition depends on the result of Future f1 or f2, so it has to wait. This seems to work, however since f1 and f2 are futures this code shouldn't run sequentially. Is this code correct?
object TestFutures extends App {
val f1 = Future { 1 }
val f2 = Future { 2 }
val f3 = Future { 3 }
val f4 = Future { 4 }
val y = 1
for {
condition <- if (y>0) f1 else f2
_ <- if (condition==1) f3.map {a => println("333")} else f4.map {b => println("444")}
} yield ()
Thread.sleep(5000)
}
No it is not correct. When you create a Future like you do it, it starts the computations immediately. Before reaching for comprehension, all of your 4 futures are running already. You need to create them later, depending on the conditions.
val y = 1
for {
condition <- if (y > 0) Future { 1 } else Future { 2 }
_ <- if (condition == 1)
Future { 3 }.map(a => println("333"))
else
Future { 4 }.map(b => println("444"))
} yield ()
It is probably good to extract creating each of those to a method, that you will just call, for sake of readability.
It should be obvious they start running when they are created because you can just say
Future(1).map(x => println(x))
and it works without any sort of triggering. Anyway try to run the following code
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def printWhenCompleted[A](f: Future[A]): Future[A] = f.map { x =>
println(x)
x
}
val f1 = printWhenCompleted(Future { 1 })
val f2 = printWhenCompleted(Future { 2 })
val f3 = printWhenCompleted(Future { 3 })
for {
r3 <- f3
r2 <- f2
r1 <- f1
} yield r1 + r2 + r3
it should give you those numbers in random order, instead of sequential 3, 2, 1
Edit
Here is implementation of the first code (without println) using flatMap
val futureCondition = if (y > 0) Future(1) else Future(2)
futureCondition.flatMap(condition => if (condition == 1) Future(3) else Future(4))

Combinatorics in Scala: How to iterate/enumerate all possibilities to merge multiple sequences/lists (riffle shuffle permutations)

Updated question:
In my original question I did not know how to refer to the following problem. To clarify my question, I added the following illustration from Wikipedia:
It turns out that the problem is also named after this analogy: Riffle shuffle permutations. Based on this terminology my question simply becomes: How can I iterate/enumerate all riffle shuffle permutations in the general case of multiple decks?
Original question:
Let's assume we are given multiple sequences and we want to merge these sequences into one single sequence. The resulting sequence should preserve the order of the original sequences. Think of merging multiple stacks of cards (say Seq[Seq[T]]) into one single stack (Seq[T]) by randomly drawing a card from any (random) stack. All input stacks should be fully merged into the resulting stack. How can I iterate or enumerate all possible compositions of such a resulting sequence?
To clarify: If I have three stacks A, B, C (of say 5 elements each) then I do not only want the six possible arrangements of these stacks like "all of A, all of B, all of C" and "all of A, all of C, all of B" etc. I rather want all possible compositions like "1. of A, 1. of B, 2. of A, 1. of C, 3. of A, 2. of B, ...".
Since I'm a bit under the weather today, my first approach is terribly ugly and also produces duplicates:
def enumerateCompositions[T](stacks: Seq[Seq[T]], prefix: Seq[T]): Seq[Seq[T]] = {
if (stacks.length == 0) return {
Seq(prefix)
}
stacks.zipWithIndex.flatMap{ case (stack, stackInd) =>
if (stack.length > 0) {
val stacksWithHeadRemoved = stacks.indices.map{ i =>
if (i != stackInd) stacks(i) else stacks(i).drop(1)
}
enumerateCompositions(stacksWithHeadRemoved, prefix :+ stack.head)
} else {
val remainingStacks = stacks.indices.filterNot(_ == stackInd).map(i => stacks(i))
enumerateCompositions(remainingStacks, prefix)
}
}
}
Any idea how to make this more elegant and get rid of the duplicates?
Let's call this operation "to riffle". Here is a clean idomatic solution:
def allRiffles[T](stack1: List[T], stack2: List[T]): List[List[T]] =
(stack1, stack2) match {
case (x :: xs, y :: ys) => {
allRiffles(xs, stack2).map(x :: _) ++
allRiffles(stack1, ys).map(y :: _)
}
case _ => List(stack1 ++ stack2) // at least one is empty
}
def allRifflesSeq[T](stacks: Seq[List[T]]): List[List[T]] =
stacks.foldLeft(List(List[T]())) { (z, x) =>
z.flatMap(y => allRiffles(y, x))
}
allRiffles will produce all the possible rifflings of two stacks. allRifflesSeq will take a sequence of stacks and produce all the possible rifflings using a fold. For example, if allRifflesSeq is given stacks A, B, and C, it first produces all possible rifflings of A and B and then riffles C into each of those rifflings.
Note that allRiffles consumes stacks space proportional to the length of the shortest stack and allRifflesSeq consumes stacks space bounded by the length of the longest stack. Also, the returned list could be huge (combinatoric explosion) and consume a lot of heap space. An Iterator based solution is safer, but much less pretty:
def allRiffles[T](stacks: List[List[T]]): Iterator[List[T]] = new Iterator[List[T]] {
type Frame = (List[List[T]], List[List[T]], List[T])
var stack = List[Frame]((Nil, stacks, Nil))
var ready = false
var cachedHasNext: Boolean = _
var cachedNext: List[T] = _
def computeNext: Unit = {
while (stack.nonEmpty) {
val (doneStacks, stacks, prefix) :: stackTail = stack
stack = stackTail
stacks match {
case Nil => {
cachedNext = prefix.reverse
cachedHasNext = true
return
}
case Nil :: rest =>
stack ::= (doneStacks, rest, prefix)
case (xs#(x :: xtail)) :: rest =>
if (rest.nonEmpty)
stack ::= (xs :: doneStacks, rest, prefix)
val newStacks = doneStacks.reverse ++ (if (xtail.isEmpty) rest
else xtail :: rest)
stack ::= (Nil, newStacks, x :: prefix)
}
}
cachedHasNext = false
}
def ensureReady = {
if (!ready) {
computeNext
ready = true
}
}
def next = {
ensureReady
if (cachedHasNext) {
val next = cachedNext
ready = false
next
} else Iterator.empty.next
}
def hasNext = {
ensureReady
cachedHasNext
}
}
I have written this in Java. The code is following.
import java.util.*;
import java.io.*;
public class RiffleShufflePermutation {
protected static ArrayList<String> a1 = null;
protected static ArrayList<String> a2 = null;
protected static ArrayList<ArrayList<String>> a = new <ArrayList<ArrayList<String>>();
private static int getStartingPosition(ArrayList<String> inA, String inS) {
for(String s : inA)
if (s.equals(inS))
return inA.indexOf(s)+1;
return 0;
}
private static void shootRiffle(int previous, int current) {
ArrayList<ArrayList<String>> newAA = new ArrayList<ArrayList<String>>();
ArrayList<String> newA;
int start;
for(ArrayList<String> al : a) {
start = (previous < 0)?0:getStartingPosition(al,a2.get(previous));
for(int i=start; i<=al.size(); i++) {
newA = new ArrayList<String>();
newA.addAll(al);
newA.add(i,a2.get(current));
newAA.add(newA);
}
}
a.clear();
a.addAll(newAA);
}
public static void main(String[] args) {
a1 = new ArrayList(Arrays.asList("a1","a2","a3"));
a2 = new ArrayList(Arrays.asList("b1","b2"));
a.add(a1);
for (int i=0; i<a2.size(); i++)
shootRiffle(i-1,i);
int i = 0;
for (ArrayList<String> s : a)
System.out.println(String.format("%2d",++i)+":"+s);
}
}
Here is the Output:
1:[b1, b2, a1, a2, a3]
2:[b1, a1, b2, a2, a3]
3:[b1, a1, a2, b2, a3]
4:[b1, a1, a2, a3, b2]
5:[a1, b1, b2, a2, a3]
6:[a1, b1, a2, b2, a3]
7:[a1, b1, a2, a3, b2]
8:[a1, a2, b1, b2, a3]
9:[a1, a2, b1, a3, b2]
10:[a1, a2, a3, b1, b2]
Hopefully this is useful.

Returning code block in Scala

I was trying to implement the closure example in Scala, from Neal Ford's Functional Thinking presentation which is in Groovy. Refer slide # 43 & 44 https://sea.ucar.edu/sites/default/files/Functional_Thinking.pdf
def makeCounter : Unit = {
var localVar = 0
return { localVar += 1 }
}
This code returns an anonymous function. Now I want to increment the localVar by invoking this anonymous function.
I have two questions:
1. How do I invoke the anonymous function?
2. After invoking it how do I check if the value of localVar is incremented or not?
First I tried this -
val c1 = makeCounter(). It threw below error:
error: makeCounter of type Unit does not take parameters
Then I tried this.
val c1 = makeCounter
This didn't give any error. Only printed c1: Unit = ().
Then,
print(c1) printed (), whereas c1() gave the same error.
First of all. Don't use return, its semantics is completely different in Scala than in Java or Groovy.
The Unit type isn't a synonym for anonymous function. It's more like a indication of side-effects.
The type for an anonymous function is () => A. In your case you want a function that doesn't return any thing, but causes a side-effect. So its type should be () => Unit.
Let's see some code:
def makeCounter : () => Unit = {
var x = 0
{ () => x = x + 1 }
}
val counter = makeCounter
counter(); counter(); counter()
Great! We made makeCounter give us a fresh counter!
There is only one problem. x is a local variable in the method makeCounter and since it's never returned we can't see its value! Ever! We could, for example, remove x from the method, making it public in the outer scope. But it's not very functional. Instead let's make the function return it:
def makeCounter : () => Int = { // Notice now, instead of Unit we use Int
var x = 0
{ () => x = x + 1; x }
}
val counter = makeCounter
println(counter(), counter(), counter())
val counter2 = makeCounter
println(counter2(), counter2(), counter2())
You will see "1,2,3" twice. Once for each counter.
I didn't look at the presentation, so I don't know if this is functional thinking or just one of the slides on the road to functional thinking, but:
scala> def f: () => Int = {
| var v = 0
| () => v += 1 ; v }
f: () => Int
scala> val g = f
g: () => Int = <function0>
scala> g()
res0: Int = 1
scala> g()
res1: Int = 2
scala> g()
res2: Int = 3
The function literal returned by f is, of course, everything after the parens.