diff --git a/NOTICE.txt b/NOTICE.txt index 9227769ffc0..f100fcbb51d 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -2823,219 +2823,6 @@ See the License for the specific language governing permissions and limitations under the License. ---------------------------------------------------------- - ---------------------------------------------------------- - -NumSharp 0.20.5 - Apache-2.0 - - -(c) 2008 VeriSign, Inc. -(c) SciSharp STACK Team Numpy, NumSharp, MachineLearning, Math, Scientific, Numeric, Mathlab, SciSharp - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - --------------------------------------------------------- --------------------------------------------------------- diff --git a/Standard/src/Diagnostics/Emulation/DataStructures.cs b/Standard/src/Diagnostics/Emulation/DataStructures.cs index 391d539e441..3f67df590e6 100644 --- a/Standard/src/Diagnostics/Emulation/DataStructures.cs +++ b/Standard/src/Diagnostics/Emulation/DataStructures.cs @@ -5,13 +5,65 @@ using System.Collections.Generic; using System.Collections.Immutable; -using Microsoft.Quantum.Simulation.Common; using Microsoft.Quantum.Simulation.Core; -using Newtonsoft.Json; -using static NumSharp.Slice; namespace Microsoft.Quantum.Diagnostics.Emulation -{ +{ + /// + /// Represents a complex-vaued square matrix using a one-dimensional list of `double` values. + /// + public class ComplexSquareMatrix + { + public int Dimension { get; set; } = 0; + private double[] entries; + + public ComplexSquareMatrix(int dim) + { + Dimension = dim; + entries = new double[dim * dim * 2]; + } + + /// + /// Accesses an entry by providing row and column and part (0 = real, 1 = imag) of complex value. + /// + public double this[int row, int col, int part] + { + get + { + var index = row * (Dimension * 2) + col * 2 + part; + return entries[index]; + } + set + { + var index = row * (Dimension * 2) + col * 2 + part; + entries[index] = value; + } + } + + public override string ToString() + { + var realRows = new string[Dimension]; + var imagRows = new string[Dimension]; + var realEntries = new double[Dimension]; + var imagEntries = new double[Dimension]; + + var index = 0; + for (var row = 0; row < Dimension; ++row) + { + for (var col = 0; col < Dimension; ++col) + { + realEntries[col] = entries[index++]; + imagEntries[col] = entries[index++]; + } + + realRows[row] = $"[{string.Join(", ", realEntries)}]"; + imagRows[row] = $"[{string.Join(", ", imagEntries)}]"; + } + + return $"Real:\n[{string.Join(", \n", realRows)}]\nImag:\n[{string.Join(", \n", imagRows)}]"; + } + } + /// /// Represents a unitary operator intended for use as a diagnostic /// display. @@ -29,18 +81,15 @@ public class DisplayableUnitaryOperator /// An array of matrix elements for the given unitary operator. /// /// - /// For ease of use, this array has a dtype of double, and + /// For ease of use, this matrix has stores double values in a /// shape (dim, dim, 2), where dim is the dimension /// of the represented unitary operator (i.e.: 2^nQubits), and /// where the last axis represents the real (index 0) and /// imaginary parts, respectively. /// - public NumSharp.NDArray? Data { get; set; } + public ComplexSquareMatrix? Data { get; set; } - public override string ToString() => - Data == null - ? "" - : $"Real:\n{Data![Ellipsis, 0]}\nImag:\n{Data![Ellipsis, 1]}"; + public override string ToString() => Data == null ? "" : Data!.ToString(); } /// diff --git a/Standard/src/Diagnostics/Emulation/Internal.cs b/Standard/src/Diagnostics/Emulation/Internal.cs index cb8ff06c480..f76bc93e335 100644 --- a/Standard/src/Diagnostics/Emulation/Internal.cs +++ b/Standard/src/Diagnostics/Emulation/Internal.cs @@ -4,23 +4,19 @@ #nullable enable using System; -using System.Numerics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.Quantum.Diagnostics.Emulation; using Microsoft.Quantum.Simulation.Common; using Microsoft.Quantum.Simulation.Core; using Microsoft.Quantum.Simulation.Simulators; -using NumSharp; -using static NumSharp.Slice; namespace Microsoft.Quantum.Diagnostics { internal class ArrayDumper : QuantumSimulator.StateDumper { - // NB: NumSharp does not yet support complex numbers, so we store data - // as an array with a trailing index of length 2. - internal NumSharp.NDArray? Data = null; + internal ComplexSquareMatrix? Data = null; + private double scaleFactor = 1.0; public ArrayDumper(QuantumSimulator sim) : base(sim) { } @@ -28,8 +24,12 @@ public ArrayDumper(QuantumSimulator sim) : base(sim) public override bool Callback([MarshalAs(UnmanagedType.LPStr)] string idx, double real, double img) { if (Data == null) throw new Exception("Expected data buffer to be initialized before callback, but it was null."); - Data![(int)(CommonNativeSimulator.DisplayableState.BasisStateLabelToBigInt(idx)), 0] = real; - Data![(int)(CommonNativeSimulator.DisplayableState.BasisStateLabelToBigInt(idx)), 1] = img; + var index = (int)(CommonNativeSimulator.DisplayableState.BasisStateLabelToBigInt(idx)); + var row = index / Data.Dimension; + var col = index % Data.Dimension; + + Data[row, col, 0] = scaleFactor * real; + Data[row, col, 1] = scaleFactor * img; return true; } @@ -38,16 +38,9 @@ public override bool Dump(IQArray? qubits = null) { var count = qubits?.Length ?? Simulator.QubitManager!.AllocatedQubitsCount; var nQubitsPerRegister = ((int)count / 2); - Data = np.empty(new Shape(1 << ((int)count), 2)); - var result = base.Dump(qubits); - - // At this point, _data should be filled with the full state - // vector, so let's display it, counting on the right display - // encoder to be there to pack it into a table. - var scaleFactor = System.Math.Sqrt(1 << nQubitsPerRegister); - Data = scaleFactor * Data.reshape(1 << nQubitsPerRegister, 1 << nQubitsPerRegister, 2); - - return result; + Data = new ComplexSquareMatrix(1 << nQubitsPerRegister); + scaleFactor = System.Math.Sqrt(1 << nQubitsPerRegister); + return base.Dump(qubits); } } diff --git a/Standard/src/Standard.csproj b/Standard/src/Standard.csproj index ad11b8a7dee..4e3587d3e9f 100644 --- a/Standard/src/Standard.csproj +++ b/Standard/src/Standard.csproj @@ -41,7 +41,6 @@ - diff --git a/Standard/tests/Diagnostics/DumpTests.cs b/Standard/tests/Diagnostics/DumpTests.cs index e692c7b2799..7df007bfcf9 100644 --- a/Standard/tests/Diagnostics/DumpTests.cs +++ b/Standard/tests/Diagnostics/DumpTests.cs @@ -41,10 +41,7 @@ public void DumpSReturnsCorrectMatrix() Assert.NotNull(unitary); Assert.Equal(1, unitary.Qubits?.Count); Assert.NotNull(unitary.Data); - Assert.Equal(3, unitary.Data.ndim); - Assert.Equal(2, unitary.Data.shape[0]); - Assert.Equal(2, unitary.Data.shape[1]); - Assert.Equal(2, unitary.Data.shape[2]); + Assert.Equal(2, unitary.Data.Dimension); // Check that the matrix is [1 0; 0 𝑖]. Assert.Equal(1.0, (double)unitary.Data[0, 0, 0], precision: 6); Assert.Equal(0.0, (double)unitary.Data[0, 1, 0], precision: 6); @@ -54,6 +51,8 @@ public void DumpSReturnsCorrectMatrix() Assert.Equal(0.0, (double)unitary.Data[0, 1, 1], precision: 6); Assert.Equal(0.0, (double)unitary.Data[1, 0, 1], precision: 6); Assert.Equal(1.0, (double)unitary.Data[1, 1, 1], precision: 6); + + Assert.Equal("Real:\n[[1.0000000000000002, 0], \n[0, 0]]\nImag:\n[[0, 0], \n[0, 1.0000000000000002]]", unitary.ToString()); } @@ -79,10 +78,7 @@ public void DumpCnotReturnsCorrectMatrix() Assert.NotNull(unitary); Assert.Equal(2, unitary.Qubits?.Count); Assert.NotNull(unitary.Data); - Assert.Equal(3, unitary.Data.ndim); - Assert.Equal(4, unitary.Data.shape[0]); - Assert.Equal(4, unitary.Data.shape[1]); - Assert.Equal(2, unitary.Data.shape[2]); + Assert.Equal(4, unitary.Data.Dimension); // Check that the matrix is [1 0 0 0; 0 0 0 1; 0 0 1 0; 0 1 0 0]. // real Assert.Equal(1.0, (double)unitary.Data[0, 0, 0], precision: 6); @@ -119,6 +115,8 @@ public void DumpCnotReturnsCorrectMatrix() Assert.Equal(0.0, (double)unitary.Data[3, 1, 1], precision: 6); Assert.Equal(0.0, (double)unitary.Data[3, 2, 1], precision: 6); Assert.Equal(0.0, (double)unitary.Data[3, 3, 1], precision: 6); + + Assert.Equal("Real:\n[[1, 0, 0, 0], \n[0, 0, 0, 1], \n[0, 0, 1, 0], \n[0, 1, 0, 0]]\nImag:\n[[0, 0, 0, 0], \n[0, 0, 0, 0], \n[0, 0, 0, 0], \n[0, 0, 0, 0]]", unitary.ToString()); } } } diff --git a/Visualization/src/CallSiteEncoders.cs b/Visualization/src/CallSiteEncoders.cs index 35b3f246e36..5b0b4650cc4 100644 --- a/Visualization/src/CallSiteEncoders.cs +++ b/Visualization/src/CallSiteEncoders.cs @@ -3,11 +3,8 @@ #nullable enable -using System.Text; using Microsoft.Jupyter.Core; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using static NumSharp.Slice; using Microsoft.Quantum.IQSharp.Jupyter; using System.Linq; using System; diff --git a/Visualization/src/DisplayableUnitaryEncoders.cs b/Visualization/src/DisplayableUnitaryEncoders.cs index a9652bc6b82..d3635564709 100644 --- a/Visualization/src/DisplayableUnitaryEncoders.cs +++ b/Visualization/src/DisplayableUnitaryEncoders.cs @@ -3,11 +3,8 @@ #nullable enable -using System.Text; using Microsoft.Jupyter.Core; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using static NumSharp.Slice; using Microsoft.Quantum.IQSharp.Jupyter; using System.Linq; using System; @@ -33,7 +30,7 @@ public DisplayableUnitaryOperatorToTextEncoder(ILogger 3 ); - var outputMatrix = String.Join( - " \\\\\n", - op.Data.EnumerateOverAxis().Cast().Select( - row => - String.Join(" & ", - row.EnumerateOverAxis() - .Cast() - .Select(element => - { - var format = $"{{0:G{precision}}}"; - var re = (double)element[0]; - var im = (double)element[1]; - var reFmt = String.Format(format, re); - var imFmt = String.Format(format, System.Math.Abs(im)) + "i"; - if (IsNearZero(re) && IsNearZero(im)) - { - return "0"; - } - else if (IsNearZero(im)) - { - return reFmt; - } - else if (IsNearZero(re)) - { - return im < 0.0 ? $"-{imFmt}" : imFmt; - } - else - { - return $"{reFmt} {(im < 0.0 ? "-" : "+")} {imFmt}"; - } - }) - ) - ) - ); + var rows = new string[op.Data.Dimension]; + var entries = new string[op.Data.Dimension]; + + for (var row = 0; row < op.Data.Dimension; ++row) + { + for (var col = 0; col < op.Data.Dimension; ++col) + { + var format = $"{{0:G{precision}}}"; + var re = op.Data[row, col, 0]; + var im = op.Data[row, col, 1]; + var reFmt = String.Format(format, re); + var imFmt = String.Format(format, System.Math.Abs(im)) + "i"; + if (IsNearZero(re) && IsNearZero(im)) + { + entries[col] = "0"; + } + else if (IsNearZero(im)) + { + entries[col] = reFmt; + } + else if (IsNearZero(re)) + { + entries[col] = im < 0.0 ? $"-{imFmt}" : imFmt; + } + else + { + entries[col] = $"{reFmt} {(im < 0.0 ? "-" : "+")} {imFmt}"; + } + } + + rows[row] = String.Join(" & ", entries); + } + + var outputMatrix = String.Join(" \\\\\n", rows); return $@" diff --git a/Visualization/src/Extensions.cs b/Visualization/src/Extensions.cs deleted file mode 100644 index 5bacbdd3c3a..00000000000 --- a/Visualization/src/Extensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#nullable enable - -using System.Text; -using Microsoft.Jupyter.Core; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using NumSharp; -using static NumSharp.Slice; -using Microsoft.Quantum.IQSharp.Jupyter; -using System.Linq; -using System; -using System.Collections.Generic; - -namespace Microsoft.Quantum.Diagnostics.Emulation -{ - - internal static class Extensions - { - internal static IEnumerable EnumerateOverAxis(this NumSharp.NDArray array, int axis = 0) - { - var prefix = Enumerable.Repeat(All, axis).ToArray(); - foreach (var idx in Enumerable.Range(0, array.Shape[axis])) - { - Slice[] slice = prefix.Concat(new Slice[] { idx, Ellipsis }).ToArray(); - yield return array[slice]; - } - } - } - -} diff --git a/Visualization/src/Visualization.csproj b/Visualization/src/Visualization.csproj index fdfdee4f7cf..add707fc29c 100644 --- a/Visualization/src/Visualization.csproj +++ b/Visualization/src/Visualization.csproj @@ -35,7 +35,6 @@ -