Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.

Commit 1789de8

Browse files
anpazcgranade
authored andcommitted
Release 0.2.1802.2202 - netcore & python preview (#32)
* Switching repository to MIT License * Release 0.2.1802.2202 - netcore & mit license * Added license headers to H2 simulation sample.
1 parent 18cabfe commit 1789de8

File tree

106 files changed

+4213
-3026
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

106 files changed

+4213
-3026
lines changed

.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# Set default behavior to automatically normalize line endings.
33
###############################################################################
44
* text=auto
5+
*.sh text eol=lf
56

67
###############################################################################
78
# Set default behavior for command prompt diff.

.gitignore

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# Python temporary files
2+
.ipynb_checkpoints
3+
14
# Git ignore file for the Solid project
25

36
# Build artifacts
@@ -11,12 +14,16 @@ packages/
1114
*.pdb
1215
*.exe
1316
*.chm
14-
*.html
1517

1618
# These files are generated by bootstrap from a .v.template (version template).
1719
# Any changes must be done to the corresponding the .v.template file directly
1820
Microsoft.Quantum.Canon/Microsoft.Quantum.Canon.nuspec
1921

22+
# Python interop build outputs:
23+
Interoperability/python/build
24+
Interoperability/python/dist
25+
Interoperability/python/qsharp.egg-info
26+
Interoperability/python/qsharp/version.py
2027

2128
# test outputs
2229
TestResults/

Docs/style-guide.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
- Avoid using people's names in operation and function names where reasonable.
1010
Consider using names that describe the implemented functionality;
11-
e.g. `CCNOT` versus `Toffoli` or `CSWAP` versus `Fredikin `.
11+
e.g. `CCNOT` versus `Toffoli` or `CSWAP` versus `Fredkin `.
1212
In sample code, consider using names that are familiar to the community reading each particular example, even if that would otherwise run counter to these suggestions.
1313
**NB:** names should still appear in documentation comments.
1414
- If an operation or function is not intended for direct use, but rather should be used by a matching callable which acts by partial application, consider using a name ending with `Impl` for the callable that is partially applied.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
##
2+
# environment.yml: Specification of a conda environment for use with
3+
# the Q# interoperability package.
4+
##
5+
# Copyright (c) Microsoft Corporation. All rights reserved.
6+
# Licensed under the MIT License.
7+
##
8+
9+
name: qsharp
10+
channels:
11+
- conda-forge
12+
- pythonnet
13+
dependencies:
14+
- numpy
15+
- pythonnet
16+
- qutip
17+
- matplotlib
18+
- pip:
19+
- qinfer
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<packages>
3+
<package id="Microsoft.Quantum.Development.Kit" version="0.2.1802.2202-preview" targetFramework="netstandard2.0" />
4+
<package id="Microsoft.Quantum.Canon" version="0.2.1802.2202-preview" targetFramework="netstandard2.0" />
5+
</packages>
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
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
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#!/bin/env python
2+
# -*- coding: utf-8 -*-
3+
##
4+
# __main__.py: Main script for the Q# interoperability package.
5+
##
6+
# Copyright (c) Microsoft Corporation. All rights reserved.
7+
# Licensed under the MIT License.
8+
##
9+
10+
import qsharp
11+
12+
from qsharp.tomography import single_qubit_process_tomography
13+
from Microsoft.Quantum.Primitive import I
14+
15+
qsim = qsharp.QuantumSimulator()
16+
noise_channel = qsim.get(I)
17+
estimation_results = single_qubit_process_tomography(qsim, noise_channel, n_measurements=2000)
18+
19+
print(estimation_results['est_channel'])

0 commit comments

Comments
 (0)