|
| 1 | +#!/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +## |
| 4 | +# __init__.py: Root module for Q# interoperability package. |
| 5 | +## |
| 6 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 7 | +# Licensed under the MIT License. |
| 8 | +## |
| 9 | + |
| 10 | +## IMPORTS ################################################################### |
| 11 | + |
| 12 | +# Standard Library Imports # |
| 13 | + |
| 14 | +from enum import IntEnum |
| 15 | +from functools import partial, singledispatch |
| 16 | +from abc import ABCMeta, abstractproperty |
| 17 | +from random import randrange |
| 18 | + |
| 19 | +# HACK: In order to make DLLs that we ship with visible to Python.NET |
| 20 | +# in the next step, we need to add the directory containing __file__ |
| 21 | +# to sys.path. |
| 22 | +import os.path |
| 23 | +import sys |
| 24 | +sys.path.append(os.path.split(__file__)[0]) |
| 25 | + |
| 26 | +# Version Information # |
| 27 | +# We try to import version.py, and if not, set our version to None. |
| 28 | +try: |
| 29 | + import qsharp.version |
| 30 | + __version__ = qsharp.version.version |
| 31 | +except ImportError: |
| 32 | + __version__ = "<unknown>" |
| 33 | + |
| 34 | +# CLR Imports # |
| 35 | + |
| 36 | +import clr |
| 37 | + |
| 38 | +import System.Threading.Tasks |
| 39 | +import Microsoft.Quantum.Simulation.Simulators as mqss |
| 40 | + |
| 41 | +# External Python Imports # |
| 42 | + |
| 43 | +try: |
| 44 | + import colorama as ca |
| 45 | + ca.init() |
| 46 | + |
| 47 | + SIMULATOR_COLOR = ca.Fore.BLUE + ca.Back.WHITE |
| 48 | + RESET_COLOR = ca.Style.RESET_ALL |
| 49 | +except: |
| 50 | + ca = None |
| 51 | + SIMULATOR_COLOR = "" |
| 52 | + RESET_COLOR = "" |
| 53 | + |
| 54 | +try: |
| 55 | + import qutip as qt |
| 56 | +except: |
| 57 | + qt = None |
| 58 | + |
| 59 | +try: |
| 60 | + from IPython.display import display |
| 61 | +except: |
| 62 | + def display(value): |
| 63 | + pass |
| 64 | + |
| 65 | +import qsharp.tomography |
| 66 | +from qsharp.clr_wrapper import * |
| 67 | + |
| 68 | + |
| 69 | +## ENUMERATIONS ############################################################## |
| 70 | + |
| 71 | +class SampleableEnum(IntEnum): |
| 72 | + """ |
| 73 | + Extends integer-valued enumerations to allow for uniformly sampling from |
| 74 | + enumeration members. |
| 75 | + """ |
| 76 | + @classmethod |
| 77 | + def random(cls): |
| 78 | + """ |
| 79 | + Returns a member of the enumeration uniformly at random. |
| 80 | + """ |
| 81 | + return cls(randrange(len(cls))) |
| 82 | + |
| 83 | +class Pauli(SampleableEnum): |
| 84 | + """ |
| 85 | + Represents the `Pauli` Q# type. |
| 86 | + """ |
| 87 | + I = 0 |
| 88 | + X = 1 |
| 89 | + Y = 2 |
| 90 | + Z = 3 |
| 91 | + |
| 92 | + def as_qobj(self): |
| 93 | + """ |
| 94 | + Returns a representation of the given Pauli operator as a QuTiP |
| 95 | + Qobj instance. |
| 96 | + """ |
| 97 | + if qt is None: |
| 98 | + raise RuntimeError("Requires QuTiP.") |
| 99 | + if self == Pauli.I: |
| 100 | + return qt.qeye(2) |
| 101 | + elif self == Pauli.X: |
| 102 | + return qt.sigmax() |
| 103 | + elif self == Pauli.Y: |
| 104 | + return qt.sigmay() |
| 105 | + else: |
| 106 | + return qt.sigmaz() |
| 107 | + |
| 108 | +class Result(SampleableEnum): |
| 109 | + """ |
| 110 | + Represents the `Result` Q# type. |
| 111 | + """ |
| 112 | + |
| 113 | + #: Represents a measurement corresponding to the $+1 = (-1)^0$ eigenvalue |
| 114 | + #: of a Pauli operator. |
| 115 | + Zero = 0 |
| 116 | + |
| 117 | + #: Represents a measurement corresponding to the $-1 = (-1)^1$ eigenvalue |
| 118 | + #: of a Pauli operator. |
| 119 | + One = 1 |
| 120 | + |
| 121 | +## FUNCTIONS ################################################################# |
| 122 | + |
| 123 | +@singledispatch |
| 124 | +def wrap_clr_object(clr_object): |
| 125 | + return WrappedCLRObject(clr_object) |
| 126 | + |
| 127 | +@wrap_clr_object.register(type(None)) |
| 128 | +def _(none): |
| 129 | + return None |
| 130 | + |
| 131 | +@wrap_clr_object.register(System.Threading.Tasks.Task) |
| 132 | +def _(clr_object): |
| 133 | + return Task(clr_object) |
| 134 | + |
| 135 | +## CLASSES ################################################################### |
| 136 | + |
| 137 | +class SimulatorOutput(object): |
| 138 | + """ |
| 139 | + Wraps a string for pretty-printing to Jupyter outputs. |
| 140 | + """ |
| 141 | + @classmethod |
| 142 | + def display_output(cls, data): |
| 143 | + display(cls(data)) |
| 144 | + |
| 145 | + def __init__(self, data): |
| 146 | + self.data = data |
| 147 | + |
| 148 | + def __repr__(self): |
| 149 | + return repr(self.data) |
| 150 | + def __str__(self): |
| 151 | + return "{}[Simulator]{} {}".format( |
| 152 | + SIMULATOR_COLOR, RESET_COLOR, self.data |
| 153 | + ) |
| 154 | + |
| 155 | + def _repr_html_(self): |
| 156 | + return """ |
| 157 | +<pre class="simulator-output">{}</pre> |
| 158 | +""".format(self.data) |
| 159 | + |
| 160 | +class Task(WrappedCLRObject): |
| 161 | + _detailed_repr = False |
| 162 | + |
| 163 | + @property |
| 164 | + def _friendly_name(self): |
| 165 | + return "Asynchronous {} Task".format( |
| 166 | + self.clr_type.GetGenericArguments()[0] |
| 167 | + ) |
| 168 | + |
| 169 | + def result(self): |
| 170 | + # Wait for the response first. This should be implied by self.Result, |
| 171 | + # but we've seen some bugs occur related to that. |
| 172 | + self.clr_object.Wait() |
| 173 | + return wrap_clr_object(self.clr_object.Result) |
| 174 | + |
| 175 | +class Simulator(WrappedCLRObject): |
| 176 | + _friendly_name = "Simulator" |
| 177 | + |
| 178 | + def __init__(self, clr_simulator): |
| 179 | + if isinstance(clr_simulator, CLR_METATYPE): |
| 180 | + clr_simulator = clr_simulator() |
| 181 | + super(Simulator, self).__init__(clr_simulator) |
| 182 | + |
| 183 | + # Register a delegate to handle Message calls. |
| 184 | + self.clr_object.OnLog += SimulatorOutput.display_output |
| 185 | + |
| 186 | + def get(self, clr_type): |
| 187 | + return Callable(self, self.clr_object.Get[clr_type, clr_type]()) |
| 188 | + |
| 189 | + def run(self, clr_type, *args): |
| 190 | + if isinstance(clr_type, Callable): |
| 191 | + # Check if the passed in type is already wrapped in a Callable Python |
| 192 | + # class. |
| 193 | + return clr_type(*args) |
| 194 | + else: |
| 195 | + # We need to get the callable ourselves, then. |
| 196 | + callable = self.get(clr_type) |
| 197 | + return callable(*args) |
| 198 | + |
| 199 | +class QuantumSimulator(Simulator): |
| 200 | + _friendly_name = "Quantum Simulator" |
| 201 | + def __init__(self): |
| 202 | + super(QuantumSimulator, self).__init__(mqss.QuantumSimulator) |
| 203 | + |
| 204 | +class Callable(WrappedCLRObject): |
| 205 | + _detailed_repr = False |
| 206 | + _parent = None |
| 207 | + _include_plain_repr = False |
| 208 | + |
| 209 | + @property |
| 210 | + def _friendly_name(self): |
| 211 | + # TODO: extract operation signature! |
| 212 | + return self.ToString() |
| 213 | + |
| 214 | + def __init__(self, parent, clr_callable): |
| 215 | + self._parent = parent |
| 216 | + super(Callable, self).__init__(clr_callable) |
| 217 | + |
| 218 | + def __call__(self, *args): |
| 219 | + output = self.clr_object.Run( |
| 220 | + unwrap_clr(self._parent), |
| 221 | + *map(unwrap_clr, args) |
| 222 | + ) |
| 223 | + |
| 224 | + if isinstance(type(output), CLR_METATYPE): |
| 225 | + # Try to wrap the output as best as we can. |
| 226 | + # We provide convienence wrappers for a few, so we call the |
| 227 | + # single-dispatched convienence function above. |
| 228 | + return wrap_clr_object(output) |
| 229 | + else: |
| 230 | + return output |
0 commit comments