smolarith


Namesmolarith JSON
Version 0.2.0 PyPI version JSON
download
home_pageNone
SummarySoft-core arithmetic components written in Amaranth HDL
upload_time2024-06-26 05:09:51
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseBSD 2-Clause License Copyright (c) 2023-2024, William D. Jones Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
keywords multiplication division hdl cpu
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # smolarith

[![Documentation Status](https://readthedocs.org/projects/smolarith/badge/?version=latest)](https://smolarith.readthedocs.io/en/latest/?badge=latest)
main: [![CI](https://github.com/cr1901/smolarith/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/cr1901/smolarith/actions/workflows/ci.yml)
next: [![CI](https://github.com/cr1901/smolarith/actions/workflows/ci.yml/badge.svg?branch=next)](https://github.com/cr1901/smolarith/actions/workflows/ci.yml)

Small arithmetic soft-cores for smol FPGAs. If your FPGA has hard IP
implementing functions in this repository, you should use those instead.

## Example

```python
from amaranth import signed, Module, C
from amaranth.lib.wiring import Component, Out, In
from amaranth.lib.stream import Signature
from amaranth.back.verilog import convert
from amaranth.sim import Simulator

import sys
from smolarith import mul
from smolarith.mul import MulticycleMul


class Celsius2Fahrenheit(Component):
    """Module to convert Celsius temperatures to Fahrenheit (F = 1.8*C + 32)."""

    def __init__(self, *, qc, qf, scale_const=5):
        self.qc = qc
        self.qf = qf
        self.scale_const = scale_const

        self.c_width = self.qc[0] + self.qc[1]
        self.f_width = self.qf[0] + self.qf[1]
        # 1.8 not representable. 1.78125 will have to be close enough.
        # Q1.{self.scale_const}
        self.mul_factor = C(9*2**self.scale_const // 5)
        # Q6.{self.qc[1] + self.scale_const}
        self.add_factor = C(32 << (self.qc[1] + self.scale_const))
        # Mul result will have self.qc[1] + self.scale_const fractional bits.
        # Adjust to desired Fahrenheit precision.
        self.extra_bits = self.qc[1] + self.scale_const - self.qf[1]

        # Output will be 2*max(len(self.mul_factor), self.c_width)...
        # more bits than we need.
        self.mul = MulticycleMul(width=max(len(self.mul_factor),
                                           self.c_width))

        super().__init__({
            "c": In(Signature(signed(self.c_width))),
            "f": Out(Signature(signed(self.f_width))),
        })

    def elaborate(self, plat):
        m = Module()
        m.submodules.mul = self.mul

        m.d.comb += [
            # res = 1.8*C
            self.c.ready.eq(self.mul.inp.ready),
            self.mul.inp.valid.eq(self.c.valid),
            self.mul.inp.payload.a.eq(self.c.payload),
            self.mul.inp.payload.b.eq(self.mul_factor),
            self.mul.inp.payload.sign.eq(mul.Sign.SIGNED_UNSIGNED),

            # F = res + 32, scaled to remove frac bits we don't need.
            self.f.payload.eq((self.mul.outp.payload.o + self.add_factor) >>
                              self.extra_bits),
            self.f.valid.eq(self.mul.outp.valid),
            self.mul.outp.ready.eq(self.f.ready)
        ]

        return m


def sim(*, c2f, start_c, end_c, gtkw=False):
    sim = Simulator(c2f)
    sim.add_clock(1e-6)

    async def tb(ctx):
        await ctx.tick()

        ctx.set(c2f.f.ready, 1)
        await ctx.tick()

        for i in range(start_c, end_c):
            ctx.set(c2f.c.payload, i)
            ctx.set(c2f.c.valid, 1)
            await ctx.tick()
            ctx.set(c2f.c.valid, 0)

            # Wait for module to calculate results.
            await ctx.tick().until(c2f.f.valid == 1)

            # This is a low-effort attempt to print fixed-point numbers
            # by converting them into floating point.
            print(ctx.get(c2f.c.payload) / 2**c2f.qc[1],
                  ctx.get(c2f.f.payload) / 2**c2f.qf[1])

    sim.add_testbench(tb)

    if gtkw:
        with sim.write_vcd("c2f.vcd", "c2f.gtkw"):
            sim.run()
    else:
        sim.run()


if __name__ == "__main__":
    # See: https://en.wikipedia.org/wiki/Q_(number_format)
    c2f = Celsius2Fahrenheit(qc=(8, 3), qf=(10, 3), scale_const=15)

    if len(sys.argv) > 1 and sys.argv[1] == "sim":
        if len(sys.argv) >= 2:
            start_c = int(float(sys.argv[2]) * 2**c2f.qc[1])
        else:
            start_c = -2**(c2f.qc[0] + c2f.qc[1] - 1)
        
        if len(sys.argv) >= 3:
            end_c = int(float(sys.argv[3]) * 2**c2f.qc[1])
        else:
            end_c = 2**(c2f.qc[0] + c2f.qc[1] - 1)

        sim(c2f=c2f, start_c=start_c, end_c=end_c, gtkw=False)
    else:
        print(convert(c2f))
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "smolarith",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "multiplication, division, HDL, cpu",
    "author": null,
    "author_email": "\"William D. Jones\" <thor0505@comcast.net>",
    "download_url": "https://files.pythonhosted.org/packages/3c/c3/3110b0b9ab8af9553336bb8257fb6b1c8a24f6107c28ae144f529441b005/smolarith-0.2.0.tar.gz",
    "platform": null,
    "description": "# smolarith\n\n[![Documentation Status](https://readthedocs.org/projects/smolarith/badge/?version=latest)](https://smolarith.readthedocs.io/en/latest/?badge=latest)\nmain: [![CI](https://github.com/cr1901/smolarith/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/cr1901/smolarith/actions/workflows/ci.yml)\nnext: [![CI](https://github.com/cr1901/smolarith/actions/workflows/ci.yml/badge.svg?branch=next)](https://github.com/cr1901/smolarith/actions/workflows/ci.yml)\n\nSmall arithmetic soft-cores for smol FPGAs. If your FPGA has hard IP\nimplementing functions in this repository, you should use those instead.\n\n## Example\n\n```python\nfrom amaranth import signed, Module, C\nfrom amaranth.lib.wiring import Component, Out, In\nfrom amaranth.lib.stream import Signature\nfrom amaranth.back.verilog import convert\nfrom amaranth.sim import Simulator\n\nimport sys\nfrom smolarith import mul\nfrom smolarith.mul import MulticycleMul\n\n\nclass Celsius2Fahrenheit(Component):\n    \"\"\"Module to convert Celsius temperatures to Fahrenheit (F = 1.8*C + 32).\"\"\"\n\n    def __init__(self, *, qc, qf, scale_const=5):\n        self.qc = qc\n        self.qf = qf\n        self.scale_const = scale_const\n\n        self.c_width = self.qc[0] + self.qc[1]\n        self.f_width = self.qf[0] + self.qf[1]\n        # 1.8 not representable. 1.78125 will have to be close enough.\n        # Q1.{self.scale_const}\n        self.mul_factor = C(9*2**self.scale_const // 5)\n        # Q6.{self.qc[1] + self.scale_const}\n        self.add_factor = C(32 << (self.qc[1] + self.scale_const))\n        # Mul result will have self.qc[1] + self.scale_const fractional bits.\n        # Adjust to desired Fahrenheit precision.\n        self.extra_bits = self.qc[1] + self.scale_const - self.qf[1]\n\n        # Output will be 2*max(len(self.mul_factor), self.c_width)...\n        # more bits than we need.\n        self.mul = MulticycleMul(width=max(len(self.mul_factor),\n                                           self.c_width))\n\n        super().__init__({\n            \"c\": In(Signature(signed(self.c_width))),\n            \"f\": Out(Signature(signed(self.f_width))),\n        })\n\n    def elaborate(self, plat):\n        m = Module()\n        m.submodules.mul = self.mul\n\n        m.d.comb += [\n            # res = 1.8*C\n            self.c.ready.eq(self.mul.inp.ready),\n            self.mul.inp.valid.eq(self.c.valid),\n            self.mul.inp.payload.a.eq(self.c.payload),\n            self.mul.inp.payload.b.eq(self.mul_factor),\n            self.mul.inp.payload.sign.eq(mul.Sign.SIGNED_UNSIGNED),\n\n            # F = res + 32, scaled to remove frac bits we don't need.\n            self.f.payload.eq((self.mul.outp.payload.o + self.add_factor) >>\n                              self.extra_bits),\n            self.f.valid.eq(self.mul.outp.valid),\n            self.mul.outp.ready.eq(self.f.ready)\n        ]\n\n        return m\n\n\ndef sim(*, c2f, start_c, end_c, gtkw=False):\n    sim = Simulator(c2f)\n    sim.add_clock(1e-6)\n\n    async def tb(ctx):\n        await ctx.tick()\n\n        ctx.set(c2f.f.ready, 1)\n        await ctx.tick()\n\n        for i in range(start_c, end_c):\n            ctx.set(c2f.c.payload, i)\n            ctx.set(c2f.c.valid, 1)\n            await ctx.tick()\n            ctx.set(c2f.c.valid, 0)\n\n            # Wait for module to calculate results.\n            await ctx.tick().until(c2f.f.valid == 1)\n\n            # This is a low-effort attempt to print fixed-point numbers\n            # by converting them into floating point.\n            print(ctx.get(c2f.c.payload) / 2**c2f.qc[1],\n                  ctx.get(c2f.f.payload) / 2**c2f.qf[1])\n\n    sim.add_testbench(tb)\n\n    if gtkw:\n        with sim.write_vcd(\"c2f.vcd\", \"c2f.gtkw\"):\n            sim.run()\n    else:\n        sim.run()\n\n\nif __name__ == \"__main__\":\n    # See: https://en.wikipedia.org/wiki/Q_(number_format)\n    c2f = Celsius2Fahrenheit(qc=(8, 3), qf=(10, 3), scale_const=15)\n\n    if len(sys.argv) > 1 and sys.argv[1] == \"sim\":\n        if len(sys.argv) >= 2:\n            start_c = int(float(sys.argv[2]) * 2**c2f.qc[1])\n        else:\n            start_c = -2**(c2f.qc[0] + c2f.qc[1] - 1)\n        \n        if len(sys.argv) >= 3:\n            end_c = int(float(sys.argv[3]) * 2**c2f.qc[1])\n        else:\n            end_c = 2**(c2f.qc[0] + c2f.qc[1] - 1)\n\n        sim(c2f=c2f, start_c=start_c, end_c=end_c, gtkw=False)\n    else:\n        print(convert(c2f))\n```\n",
    "bugtrack_url": null,
    "license": "BSD 2-Clause License  Copyright (c) 2023-2024, William D. Jones  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    "summary": "Soft-core arithmetic components written in Amaranth HDL",
    "version": "0.2.0",
    "project_urls": {
        "Documentation": "https://smolarith.readthedocs.io",
        "Repository": "https://github.com/cr1901/smolarith"
    },
    "split_keywords": [
        "multiplication",
        " division",
        " hdl",
        " cpu"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f47650dfdf7d78f1bb85181fcd40f1ff4f81a060c7bc8bee01c864164659d53f",
                "md5": "bb134f844723a65da5e2c44500a2a15d",
                "sha256": "2d86e11ce5479dea460ef73e2023acce6e16ca7eb0137778be5b3bb032f315ba"
            },
            "downloads": -1,
            "filename": "smolarith-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bb134f844723a65da5e2c44500a2a15d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 18156,
            "upload_time": "2024-06-26T05:09:49",
            "upload_time_iso_8601": "2024-06-26T05:09:49.499051Z",
            "url": "https://files.pythonhosted.org/packages/f4/76/50dfdf7d78f1bb85181fcd40f1ff4f81a060c7bc8bee01c864164659d53f/smolarith-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3cc33110b0b9ab8af9553336bb8257fb6b1c8a24f6107c28ae144f529441b005",
                "md5": "b5e17bfa59fc987023d61059f9b865de",
                "sha256": "ef7c8ec34e91ce12a6451c9e059227dd9ca653cbe20c32c379260ca15cc078c4"
            },
            "downloads": -1,
            "filename": "smolarith-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "b5e17bfa59fc987023d61059f9b865de",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 21732,
            "upload_time": "2024-06-26T05:09:51",
            "upload_time_iso_8601": "2024-06-26T05:09:51.181832Z",
            "url": "https://files.pythonhosted.org/packages/3c/c3/3110b0b9ab8af9553336bb8257fb6b1c8a24f6107c28ae144f529441b005/smolarith-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-26 05:09:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cr1901",
    "github_project": "smolarith",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "smolarith"
}
        
Elapsed time: 0.77209s