{ "cells": [ { "cell_type": "raw", "metadata": { "raw_mimetype": "text/restructuredtext" }, "source": [ ".. _less-than-zero:\n", "\n", "Less Than Zero Comparison\n", "=========================\n", "\n", "Here we demonstrate testing a secret-shared array elementwise to see if the values are less than zero. The resulting secret shared array will be the same shape as the input, containing :math:`1` where the input is less than zero, and :math:`0` where it is not. Note that we use the :any:`Boolean` encoding when we reveal the output because the default :any:`FixedPoint` encoding would produce unexpected results.\n", "\n", "Note that this comparison is roughly three times faster than using :ref:`less-than` with :math:`0` as the second operand.\n", "\n", "In this example, we will compare the vector :math:`[2, -1.5, 0]` to zero, which should return :math:`[0, 1, 0]`:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO:root:Player 0 secret: [ 2. -1.5 0. ]\n", "INFO:root:Player 0 result: [False True False]\n", "INFO:root:Player 1 result: [False True False]\n", "INFO:root:Player 2 result: [False True False]\n" ] } ], "source": [ "import logging\n", "\n", "import numpy\n", "\n", "from cicada.additive import AdditiveProtocolSuite\n", "from cicada.communicator import SocketCommunicator\n", "from cicada.encoding import Boolean\n", "from cicada.logger import Logger\n", "\n", "logging.basicConfig(level=logging.INFO)\n", "\n", "def main(communicator):\n", " log = Logger(logging.getLogger(), communicator)\n", " protocol = AdditiveProtocolSuite(communicator)\n", " \n", " a = numpy.array([2, -1.5, 0]) if communicator.rank == 0 else None\n", " \n", " log.info(f\"Player {communicator.rank} secret: {a}\", src=0)\n", "\n", " a_share = protocol.share(src=0, secret=a, shape=(3,))\n", " less_zero_share = protocol.less_zero(a_share)\n", " less_zero = protocol.reveal(less_zero_share, encoding=Boolean())\n", " \n", " log.info(f\"Player {communicator.rank} result: {less_zero}\")\n", "\n", "SocketCommunicator.run(world_size=3, fn=main);" ] }, { "cell_type": "raw", "metadata": { "raw_mimetype": "text/restructuredtext" }, "source": [ ".. seealso:: :ref:`equality`, :ref:`less-than`" ] } ], "metadata": { "celltoolbar": "Raw Cell Format", "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.2" } }, "nbformat": 4, "nbformat_minor": 4 }