def popcount(w): """ Create a population count circuit. Parameters ---------- w: the width of the adder. Returns ------- a `CircuitGraph` addder. """ c = Circuit(name="popcount") ps = [[c.add(f"in_{i}", "input")] for i in range(w)] i = 0 while len(ps) > 1: # get values ns = ps.pop(0) ms = ps.pop(0) # pad aw = max(len(ns), len(ms)) while len(ms) < aw: ms += ["null"] while len(ns) < aw: ns += ["null"] # instantiate and connect adder a = adder(aw).strip_io() c.extend(a.relabel({n: f"add_{i}_{n}" for n in a.nodes()})) for j, (n, m) in enumerate(zip(ns, ms)): c.connect(n, f"add_{i}_a_{j}") c.connect(m, f"add_{i}_b_{j}") # add adder outputs ps.append([f"add_{i}_out_{j}" for j in range(aw + 1)]) i += 1 # connect outputs for i, o in enumerate(ps[0]): c.add(f"out_{i}", "buf", fanin=o, output=True) if "null" in c: c.set_type("null", "0") c.set_output("null", False) return c
def comb_ff(): lm = Circuit(name="ff") # mux m = mux(2).strip_io() lm.extend(m.relabel({n: f"mux_{n}" for n in m.nodes()})) # inputs lm.add("si", "input", fanout="mux_in_0") lm.add("d", "input", fanout="mux_in_1") lm.add("clk", "input", fanout="mux_sel_0") lm.add("r", "input") lm.add("s", "input") # logic lm.add("r_b", "not", fanin="r") lm.add("qr", "and", fanin=["mux_out", "r_b"]) lm.add("q", "or", fanin=["qr", "s"], output=True) lm.add("so", "buf", fanin="q", output=True) return lm