From 314a6c774380a9d2f5c77f24fd3589728c8704f4 Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Sat, 5 Jan 2013 14:18:36 +0100 Subject: [PATCH] corelogic: complex arithmetic support --- examples/basic/complex.py | 16 ++++++++++++ migen/corelogic/complex.py | 52 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 examples/basic/complex.py create mode 100644 migen/corelogic/complex.py diff --git a/examples/basic/complex.py b/examples/basic/complex.py new file mode 100644 index 00000000..d0e61e5e --- /dev/null +++ b/examples/basic/complex.py @@ -0,0 +1,16 @@ +from migen.corelogic.complex import * +from migen.fhdl import verilog + +w = Complex(32, 42) +A = SignalC(16) +B = SignalC(16) +Bw = SignalC(16, variable=True) +C = SignalC(16) +D = SignalC(16) +sync = [ + Bw.eq(B*w), + C.eq(A + Bw), + D.eq(A - Bw) +] + +print(verilog.convert(Fragment(sync=sync))) diff --git a/migen/corelogic/complex.py b/migen/corelogic/complex.py new file mode 100644 index 00000000..34c98224 --- /dev/null +++ b/migen/corelogic/complex.py @@ -0,0 +1,52 @@ +from migen.fhdl.structure import * + +class Complex: + def __init__(self, real, imag): + self.real = real + self.imag = imag + + def __neg__(self): + return Complex(-self.real, -self.imag) + + def __add__(self, other): + if isinstance(other, Complex): + return Complex(self.real + other.real, self.imag + other.imag) + else: + return Complex(self.real + other, self.imag) + __radd__ = __add__ + def __sub__(self, other): + if isinstance(other, Complex): + return Complex(self.real - other.real, self.imag - other.imag) + else: + return Complex(self.real - other, self.imag) + def __rsub__(self, other): + if isinstance(other, Complex): + return Complex(other.real - self.real, other.imag - self.imag) + else: + return Complex(other - self.real, -self.imag) + def __mul__(self, other): + if isinstance(other, Complex): + return Complex(self.real*other.real - self.imag*other.imag, + self.real*other.imag + self.imag*other.real) + else: + return Complex(self.real*other, self.imag*other) + __rmul__ = __mul__ + + def __lshift__(self, other): + return Complex(self.real << other, self.imag << other) + def __rshift__(self, other): + return Complex(self.real >> other, self.imag >> other) + + def __repr__(self): + return repr(self.real) + " + " + repr(self.imag) + "j" + + def eq(self, r): + if isinstance(r, Complex): + return self.real.eq(r.real), self.imag.eq(r.imag) + else: + return self.real.eq(r), self.imag.eq(0) + +def SignalC(*args, **kwargs): + real = Signal(*args, **kwargs) + imag = Signal(*args, **kwargs) + return Complex(real, imag) -- 2.30.2