├── .gitattributes
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── devskim.yml
│ ├── docker-build.yml
│ ├── gh-sync.yml
│ ├── push-selfcontained.yml
│ └── qdk-sync.yml
├── .gitignore
├── .ionide
└── symbolCache.db
├── .sscignore
├── .vscode
├── launch.json
├── settings.json
└── tasks.json
├── CONTRIBUTING.md
├── LICENSE
├── NOTICE.txt
├── NuGet.Config
├── PRIVACY.md
├── README.md
├── SECURITY.md
├── acr
└── purge-old-images.yml
├── bootstrap.ps1
├── build
├── .gitignore
├── DelaySign.cs
├── assets
│ └── qdk-nuget-icon.png
├── build.ps1
├── ci.yml
├── docs
│ ├── README.md
│ └── build_docs.py
├── e2e.yml
├── manifest-selfcontained.ps1
├── manifest.ps1
├── pack-conda.ps1
├── pack-docs.ps1
├── pack-selfcontained.ps1
├── pack.ps1
├── set-env.ps1
├── steps-conda.yml
├── steps-frameworks.yml
├── steps-selenium.yml
├── steps-selfcontained.yml
├── steps.yml
├── test-conda.ps1
├── test-selenium.py
└── test.ps1
├── conda-recipes
├── iqsharp
│ ├── build.ps1
│ ├── meta.yaml
│ ├── test.ps1
│ └── test.py
└── qsharp
│ ├── build.ps1
│ ├── meta.yaml
│ ├── test.ps1
│ └── tests.py
├── global.json
├── images
├── iqsharp-base
│ └── Dockerfile
└── test-environments
│ ├── README.md
│ ├── linux
│ └── Dockerfile
│ ├── macos
│ └── Dockerfile
│ └── windows
│ └── Dockerfile
├── iqsharp.sln
├── src
├── AzureClient
│ ├── AzureClient.cs
│ ├── AzureClient.csproj
│ ├── AzureClientError.cs
│ ├── AzureExecutionTarget.cs
│ ├── AzureFactory.cs
│ ├── AzureSubmissionContext.cs
│ ├── EntryPoint
│ │ ├── EntryPoint.cs
│ │ ├── EntryPointGenerator.cs
│ │ ├── EntryPointOperationResolver.cs
│ │ ├── IEntryPoint.cs
│ │ └── IEntryPointGenerator.cs
│ ├── Extensions.cs
│ ├── IAzureClient.cs
│ ├── IAzureFactory.cs
│ ├── Magic
│ │ ├── AzureClientMagicBase.cs
│ │ ├── CapabilityMagic.cs
│ │ ├── ConnectMagic.cs
│ │ ├── ExecuteMagic.cs
│ │ ├── JobsMagic.cs
│ │ ├── OutputMagic.cs
│ │ ├── QuotaMagic.cs
│ │ ├── StatusMagic.cs
│ │ ├── SubmitMagic.cs
│ │ └── TargetMagic.cs
│ ├── Mocks
│ │ ├── MockAzureExecutionTarget.cs
│ │ ├── MockAzureWorkspace.cs
│ │ ├── MockCloudJob.cs
│ │ ├── MockHelper.cs
│ │ ├── MockProviderStatus.cs
│ │ ├── MockQIRSubmitter.cs
│ │ ├── MockQuantumMachine.cs
│ │ ├── MockTargetStatus.cs
│ │ └── MocksAzureFactory.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ └── GlobalUsings.cs
│ ├── Resources.cs
│ └── Visualization
│ │ ├── AzureClientErrorEncoders.cs
│ │ ├── CloudJobEncoders.cs
│ │ ├── DeviceCodeResultEncoders.cs
│ │ ├── HistogramEncoders.cs
│ │ ├── JsonConverters.cs
│ │ ├── ResourceEstimationEncoder.cs
│ │ ├── TargetCapabilityEncoders.cs
│ │ └── TargetStatusEncoders.cs
├── Common
│ └── GlobalUsings.cs
├── Core
│ ├── AssemblyInfo.cs
│ ├── CommonMessages.cs
│ ├── Compat.cs
│ ├── Compiler
│ │ ├── CompilerMetadata.cs
│ │ ├── CompilerService.cs
│ │ ├── ICompilerService.cs
│ │ └── MSBuild.cs
│ ├── Core.csproj
│ ├── Events
│ │ ├── EventService.cs
│ │ ├── IEventService.cs
│ │ └── ServiceInitializedEvent.cs
│ ├── Exceptions
│ │ ├── CompilationErrorsException.cs
│ │ └── InvalidWorkspaceException.cs
│ ├── Extensions
│ │ ├── Async.cs
│ │ ├── FSharp.cs
│ │ ├── IO.cs
│ │ ├── NuGet.cs
│ │ ├── Qsharp.cs
│ │ ├── ServiceCollection.cs
│ │ ├── String.cs
│ │ └── Type.cs
│ ├── IPerformanceMonitor.cs
│ ├── Loggers
│ │ ├── NugetLogger.cs
│ │ └── QsharpLogger.cs
│ ├── Metadata
│ │ ├── ClientInformation.cs
│ │ └── MetadataController.cs
│ ├── OperationInfo.cs
│ ├── PerformanceMonitor.cs
│ ├── Platform
│ │ └── Utils.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── GlobalSuppressions.cs
│ │ └── KnownUris.cs
│ ├── References
│ │ ├── INugetPackages.cs
│ │ ├── IReferences.cs
│ │ ├── NugetPackages.cs
│ │ └── References.cs
│ ├── Resolver
│ │ ├── IOperationResolver.cs
│ │ └── OperationResolver.cs
│ ├── Snippets
│ │ ├── ISnippets.cs
│ │ ├── Snippet.cs
│ │ └── Snippets.cs
│ ├── Telemetry
│ │ ├── ITelemetryService.cs
│ │ └── NullTelemetryService.cs
│ ├── TupleConversion.cs
│ └── Workspace
│ │ ├── IWorkspace.cs
│ │ ├── Project.cs
│ │ └── Workspace.cs
├── ExecutionPathTracer
│ ├── ExecutionPath.cs
│ ├── ExecutionPathTracer.cs
│ ├── ExecutionPathTracer.csproj
│ ├── Extensions.cs
│ └── Register.cs
├── Jupyter
│ ├── ChannelWriter.cs
│ ├── Compat.cs
│ ├── CompilationErrorStyle.cs
│ ├── ConfigurationSource
│ │ ├── ConfigurationSource.cs
│ │ └── IConfigurationSource.cs
│ ├── Extensions.cs
│ ├── Jupyter.csproj
│ ├── Magic
│ │ ├── AbstractMagic.cs
│ │ ├── AbstractNativeSimulateMagic.cs
│ │ ├── ConfigMagic.cs
│ │ ├── ExperimentalBuildInfo.cs
│ │ ├── LsMagicMagic.cs
│ │ ├── LsOpenMagic.cs
│ │ ├── NoiseModel.cs
│ │ ├── PackageMagic.cs
│ │ ├── PerformanceMagic.cs
│ │ ├── ProjectMagic.cs
│ │ ├── Resolution
│ │ │ ├── IMagicResolver.cs
│ │ │ └── MagicResolver.cs
│ │ ├── Simulate.cs
│ │ ├── SimulateNoise.cs
│ │ ├── SimulateSparse.cs
│ │ ├── ToffoliMagic.cs
│ │ ├── WhoMagic.cs
│ │ └── WorkspaceMagic.cs
│ ├── NoiseModelSource
│ │ ├── INoiseModelSource.cs
│ │ └── NoiseModelSource.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ └── GlobalUsings.cs
│ ├── SymbolResolver.cs
│ └── Visualization
│ │ ├── DataTableEncoders.cs
│ │ ├── DebugContent.cs
│ │ ├── DisplayableExceptionEncoders.cs
│ │ ├── DisplayableHtmlElementEncoder.cs
│ │ ├── FancyError.cs
│ │ ├── IDisplayable.cs
│ │ ├── LsMagicEncoders.cs
│ │ ├── MeasurementHistogramContent.cs
│ │ ├── OpenSystemsEncoders.cs
│ │ ├── PerformanceReportEncoders.cs
│ │ ├── StateDisplayEncoders.cs
│ │ ├── TaskStatusEncoders.cs
│ │ └── TraceVisualization.cs
├── Kernel
│ ├── ClientInfoListener.cs
│ ├── Compat.cs
│ ├── CustomShell
│ │ └── MessageExtensions.cs
│ ├── ExperimentalFeatures.cs
│ ├── Extensions.cs
│ ├── IQSharpEngine.cs
│ ├── Kernel.csproj
│ ├── KernelApp
│ │ └── IQSharpKernelApp.cs
│ ├── KernelProperties.cs
│ ├── Magic
│ │ ├── AttachMagic.cs
│ │ ├── DebugMagic.cs
│ │ ├── QirMagic.cs
│ │ └── TraceMagic.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ └── GlobalUsings.cs
│ ├── SymbolEncoders.cs
│ ├── client
│ │ ├── ipython.d.ts
│ │ ├── kernel.ts
│ │ ├── plotting.ts
│ │ ├── syntax.ts
│ │ └── telemetry.ts
│ ├── package-lock.json
│ ├── package.json
│ ├── res
│ │ ├── .gitignore
│ │ ├── kernel.js
│ │ └── logo-64x64.png
│ └── tsconfig.json
├── MockLibraries
│ ├── Mock.Chemistry
│ │ ├── Library.qs
│ │ └── Mock.Chemistry.csproj
│ └── Mock.Standard
│ │ ├── Arrays.cs
│ │ ├── Arrays.qs
│ │ ├── Canon.cs
│ │ ├── Canon.qs
│ │ └── Mock.Standard.csproj
├── Python
│ ├── qsharp-core
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── qsharp
│ │ │ ├── __init__.py
│ │ │ ├── azure.py
│ │ │ ├── clients
│ │ │ │ ├── __init__.py
│ │ │ │ ├── iqsharp.py
│ │ │ │ └── mock.py
│ │ │ ├── config.py
│ │ │ ├── experimental.py
│ │ │ ├── ipython_magic.py
│ │ │ ├── loader.py
│ │ │ ├── noise_model.py
│ │ │ ├── packages.py
│ │ │ ├── projects.py
│ │ │ ├── qobj.py
│ │ │ ├── results
│ │ │ │ ├── __init__.py
│ │ │ │ └── resource_estimator.py
│ │ │ ├── serialization.py
│ │ │ ├── tests
│ │ │ │ ├── Operations.qs
│ │ │ │ ├── __init__.py
│ │ │ │ ├── test_azure.py
│ │ │ │ ├── test_iqsharp.py
│ │ │ │ ├── test_loader.py
│ │ │ │ ├── test_qir.py
│ │ │ │ ├── test_serialization.py
│ │ │ │ └── utils.py
│ │ │ ├── tomography.py
│ │ │ ├── types.py
│ │ │ └── utils.py
│ │ └── setup.py
│ └── requirements.txt
├── Tests
│ ├── AzureClientEntryPointTests.cs
│ ├── AzureClientMagicTests.cs
│ ├── AzureClientTests.cs
│ ├── ConfigurationSourceTests.cs
│ ├── DisplayConverterTests.cs
│ ├── ExecutionPathTracerTests.cs
│ ├── GlobalSuppressions.cs
│ ├── HttpServerIntegrationTests.cs
│ ├── IQsharpEngineTests.cs
│ ├── Logging.cs
│ ├── Mocks.cs
│ ├── NugetPackagesTests.cs
│ ├── PackagesControllerTest.cs
│ ├── SNIPPETS.cs
│ ├── SerializationTests.cs
│ ├── SnippetsControllerTests.cs
│ ├── Startup.cs
│ ├── TelemetryTests.cs
│ ├── TestExtensions.cs
│ ├── Tests.IQsharp.csproj
│ ├── Workspace.Broken
│ │ ├── BasicOps.qs
│ │ └── NoOp.qs
│ ├── Workspace.Chemistry
│ │ └── Operation.qs
│ ├── Workspace.ExecutionPathTracer
│ │ ├── Canon.qs
│ │ ├── Circuits.qs
│ │ ├── Intrinsic.qs
│ │ └── Measurement.qs
│ ├── Workspace.HardwareTarget
│ │ └── Operation.qs
│ ├── Workspace.ProjectReferences.ProjectA
│ │ ├── ProjectA.csproj
│ │ └── ProjectA.qs
│ ├── Workspace.ProjectReferences.ProjectB
│ │ ├── ProjectB.csproj
│ │ └── ProjectB.qs
│ ├── Workspace.ProjectReferences
│ │ ├── Operation.qs
│ │ └── Workspace.ProjectReferences.csproj
│ ├── Workspace.QPRGen1
│ │ └── Operations.qs
│ ├── Workspace
│ │ ├── BasicOps.qs
│ │ └── NoOp.qs
│ ├── WorkspaceControllerTest.cs
│ └── WorkspaceTests.cs
├── Tool
│ ├── EnvironmentProvider.cs
│ ├── Program.cs
│ ├── Startup.cs
│ ├── Telemetry.cs
│ ├── Tool.csproj
│ ├── Tool.csproj.orig
│ ├── Untitled.ipynb
│ └── appsettings.json
└── Web
│ ├── AbstractOperationsController.cs
│ ├── Models
│ └── CompileSnippetModel.cs
│ ├── PackagesController.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── Response.cs
│ ├── SnippetsController.cs
│ ├── Web.csproj
│ └── WorkspaceController.cs
├── test-containers
└── miniconda
│ ├── .devcontainer
│ └── devcontainer.json
│ ├── Untitled.ipynb
│ └── environment.yml
└── tests.live
├── All.Tests.ps1
├── Install-Artifacts.ps1
├── Notebooks
├── IonQ.ipynb
└── ResourceEstimator.ipynb
├── Python
├── qsharp
│ ├── estimator
│ │ ├── Estimator.csproj
│ │ └── Operation.qs
│ ├── ionq
│ │ ├── IonQ.csproj
│ │ └── Operations.qs
│ └── quantinuum
│ │ ├── Operations.qs
│ │ └── Quantinuum.csproj
└── test_live.py
├── README.md
└── Run.ps1
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Prevent GitHub from excluding the build/ directory from the file finder.
2 | # See: https://docs.github.com/en/search-github/searching-on-github/finding-files-on-github
3 | build/** linguist-generated=false
4 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **System information**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Additional context**
32 | Add any other context about the problem here.
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/devskim.yml:
--------------------------------------------------------------------------------
1 | name: DevSkim
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 | workflow_dispatch:
9 | schedule:
10 | # set schedule to run at 2AM PT on Saturdays
11 | - cron: '0 9 * * Sat'
12 |
13 | jobs:
14 | lint:
15 | name: DevSkim
16 | runs-on: ubuntu-latest
17 | permissions:
18 | actions: read
19 | contents: read
20 | security-events: write
21 | steps:
22 | - name: Checkout code
23 | uses: actions/checkout@v3
24 |
25 | - name: Run DevSkim scanner
26 | uses: microsoft/DevSkim-Action@v1
27 |
28 | - name: Upload DevSkim scan results to GitHub Security tab
29 | uses: github/codeql-action/upload-sarif@v2
30 | with:
31 | sarif_file: devskim-results.sarif
32 |
--------------------------------------------------------------------------------
/.github/workflows/gh-sync.yml:
--------------------------------------------------------------------------------
1 | name: Sync GitHub with ADO
2 |
3 | on:
4 | issues:
5 | types: [closed, edited, deleted, reopened, assigned, unassigned, labeled, unlabeled]
6 | issue_comment:
7 |
8 | concurrency:
9 | group: ${{ github.event.issue.number }}
10 | cancel-in-progress: true
11 |
12 | jobs:
13 | sync-issues:
14 | name: Run gh-sync from GitHub action
15 | if: ${{ github.event.label.name == 'tracking' || contains(github.event.issue.labels.*.name, 'tracking') }}
16 | runs-on: ubuntu-latest
17 | steps:
18 | - name: Login to Azure
19 | uses: Azure/login@v1
20 | with:
21 | creds: ${{ secrets.AZURE_CREDENTIALS }}
22 |
23 | - id: AzureKeyVault
24 | uses: Azure/get-keyvault-secrets@v1
25 | with:
26 | keyvault: 'kv-qdk-build'
27 | secrets: 'ghSyncBuildPAT'
28 |
29 | - name: 'Trigger gh-sync'
30 | uses: microsoft/gh-sync@main
31 | with:
32 | ado-organization-url: ${{ secrets.ADO_URL }}
33 | ado-project: ${{ secrets.ADO_PROJECT }}
34 | ado-area-path: ${{ secrets.ADO_AREA_PATH }}
35 | github-repo: 'microsoft/iqsharp'
36 | issue-number: ${{ github.event.issue.number }}
37 | ado-token: ${{ steps.AzureKeyVault.outputs.ghSyncBuildPAT }}
38 | github-token: ${{ secrets.GITHUB_TOKEN }}
39 |
--------------------------------------------------------------------------------
/.github/workflows/push-selfcontained.yml:
--------------------------------------------------------------------------------
1 | # Leverages the callable workflow defined in docker-build.yml
2 | # to build the images used in conda tests. This is necessary
3 | # as the Windows and Linux images need to be built on agents
4 | # of those operating systems, respectively. Using a callable
5 | # workflow allows the agent's OS to be parameterized.
6 |
7 | name: Push Docker test images
8 |
9 | on:
10 | push:
11 | branches:
12 | - main
13 | paths:
14 | - 'images/test-environments/**/Dockerfile'
15 | workflow_dispatch:
16 | schedule:
17 | # set schedule to run at 2AM PT on Saturdays
18 | - cron: '0 9 * * SAT'
19 |
20 | jobs:
21 | windows:
22 | name: "Build windows image"
23 | uses: ./.github/workflows/docker-build.yml
24 | secrets: inherit
25 | with:
26 | os: "windows-latest"
27 | path: "images/test-environments/windows"
28 | repoName: "windows-selfcontained"
29 | tagSuffix: "windows"
30 |
31 | linux:
32 | name: "Build linux image"
33 | uses: ./.github/workflows/docker-build.yml
34 | secrets: inherit
35 | with:
36 | os: "ubuntu-latest"
37 | path: "images/test-environments/linux"
38 | repoName: "linux-selfcontained"
39 | tagSuffix: "linux"
40 |
--------------------------------------------------------------------------------
/.github/workflows/qdk-sync.yml:
--------------------------------------------------------------------------------
1 | name: Sync QDK repos
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 |
8 | jobs:
9 | sync-repos:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Login to Azure
13 | uses: Azure/login@v1
14 | with:
15 | creds: ${{ secrets.AZURE_CREDENTIALS }}
16 |
17 | - id: AzureKeyVault
18 | uses: Azure/get-keyvault-secrets@v1
19 | with:
20 | keyvault: 'kv-qdk-build'
21 | secrets: 'qdkBuildPAT'
22 |
23 | - name: 'Trigger QDK sync build'
24 | uses: Azure/pipelines@releases/v1
25 | with:
26 | azure-devops-project-url: 'https://dev.azure.com/ms-quantum-public/Microsoft Quantum (public)'
27 | azure-pipeline-name: 'microsoft.qdk.sync'
28 | azure-devops-token: ${{ steps.AzureKeyVault.outputs.qdkBuildPAT }}
29 |
--------------------------------------------------------------------------------
/.ionide/symbolCache.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/.ionide/symbolCache.db
--------------------------------------------------------------------------------
/.sscignore:
--------------------------------------------------------------------------------
1 | {
2 | "cfs": ["CFS0012", "CFS0013"]
3 | }
4 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to find out which attributes exist for C# debugging
3 | // Use hover for the description of the existing attributes
4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": ".NET Core Launch (console)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/src/Tool/bin/Debug/net6.0/Microsoft.Quantum.IQSharp.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}/src/Tool",
16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
17 | "console": "internalConsole",
18 | "stopAtEntry": false
19 | },
20 | {
21 | "name": ".NET Core Attach",
22 | "type": "coreclr",
23 | "request": "attach",
24 | "processId": "${command:pickProcess}"
25 | }
26 | ]
27 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "files.associations": {
3 | "**/build/*.yml": "azure-pipelines"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/src/Tool/Tool.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/src/Tool/Tool.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/src/Tool/Tool.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation. All rights reserved.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE
22 |
--------------------------------------------------------------------------------
/NuGet.Config:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/PRIVACY.md:
--------------------------------------------------------------------------------
1 | # Data Collection #
2 |
3 | The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.
4 |
--------------------------------------------------------------------------------
/acr/purge-old-images.yml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/acr/purge-old-images.yml
--------------------------------------------------------------------------------
/bootstrap.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 |
5 | # Fetch TypeScript definitions
6 | Push-Location (Join-Path $PSScriptRoot src/Kernel)
7 | if (Get-Command npm -ErrorAction SilentlyContinue) {
8 | "##[info]Installing npm dependencies" | Write-Host
9 | npm install | Write-Host
10 | "==> npm install complete <==" | Write-Host
11 | } else {
12 | "##[info]npm not installed. Will skip npm install" | Write-Host
13 | }
14 | Pop-Location
15 |
16 |
17 | # If the compiler constants include TELEMETRY, explicitly add the Aria telemetry package to the iqsharp tool:
18 | if (($Env:ASSEMBLY_CONSTANTS -ne $null) -and ($Env:ASSEMBLY_CONSTANTS.Contains("TELEMETRY"))) {
19 | $project = (Join-Path $PSScriptRoot 'src\Tool\Tool.csproj')
20 | $pkg = "Microsoft.Applications.Events.Server.Core2"
21 | Write-Host "##[info]Adding $pkg to $project"
22 | dotnet add $project `
23 | package $pkg `
24 | --no-restore `
25 | --version "$Env:BUILD_ARIA_VERSION"
26 | }
27 |
28 | # Install Python requirements for building/testing
29 | if ($Env:ENABLE_PYTHON -ne "false") {
30 | $pythonVersion = python --version
31 | $requirements = Join-Path $PSScriptRoot 'src\Python\requirements.txt'
32 | "##[info]Installing requirements from '$requirements' using version: '{$pythonVersion}'" | Write-Host
33 | pip install -r $requirements | Write-Host
34 | "==> pip install complete <==" | Write-Host
35 | }
--------------------------------------------------------------------------------
/build/.gitignore:
--------------------------------------------------------------------------------
1 | *.snk
--------------------------------------------------------------------------------
/build/DelaySign.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System.Reflection;
5 |
6 | // Attributes for delay-signing
7 | #if SIGNED
8 | [assembly:AssemblyKeyFile("../../build/267DevDivSNKey2048.snk")]
9 | [assembly:AssemblyDelaySign(true)]
10 | #endif
11 |
12 | internal static class SigningConstants
13 | {
14 | #if SIGNED
15 | public const string PUBLIC_KEY = ", PublicKey=" +
16 | "002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1" +
17 | "a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a2" +
18 | "35e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b" +
19 | "5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c" +
20 | "8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f" +
21 | "9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f3" +
22 | "02d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd9" +
23 | "11f0571aaf3d54da12b11ddec375b3";
24 | #else
25 | public const string PUBLIC_KEY = "";
26 | #endif
27 | }
28 |
--------------------------------------------------------------------------------
/build/assets/qdk-nuget-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/build/assets/qdk-nuget-icon.png
--------------------------------------------------------------------------------
/build/build.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | & "$PSScriptRoot/set-env.ps1"
5 |
6 | $all_ok = $True
7 |
8 | function Build-One {
9 | param(
10 | [string]$action,
11 | [string]$project
12 | );
13 |
14 | Write-Host "##[info]Building $project"
15 | dotnet $action (Join-Path $PSScriptRoot $project) `
16 | -c $Env:BUILD_CONFIGURATION `
17 | -v $Env:BUILD_VERBOSITY `
18 | /property:DefineConstants=$Env:ASSEMBLY_CONSTANTS `
19 | /property:Version=$Env:ASSEMBLY_VERSION `
20 | /property:InformationalVersion=$Env:SEMVER_VERSION `
21 | /property:QsharpDocsOutDir=$Env:DOCS_OUTDIR
22 |
23 | if ($LastExitCode -ne 0) {
24 | Write-Host "##vso[task.logissue type=error;]Failed to build $project"
25 | $script:all_ok = $False
26 | }
27 | }
28 |
29 | # Fetch TypeScript definitions
30 | Push-Location (Join-Path $PSScriptRoot ../src/Kernel)
31 | Try {
32 | # npm install writes some output to stderr, which causes PowerShell to throw
33 | # unless $ErrorActionPreference is set to 'Continue'.
34 | # We also redirect stderr output to stdout to prevent an exception being incorrectly thrown.
35 | $OldPreference = $ErrorActionPreference;
36 | $ErrorActionPreference = 'Continue'
37 | npm install 2>&1 | ForEach-Object { "$_" }
38 | } Catch {
39 | Write-Host $Error[0]
40 | Write-Host "##vso[task.logissue type=error;]Failed to install npm dependencies."
41 | $script:all_ok = $False
42 | } Finally {
43 | $ErrorActionPreference = $OldPreference
44 | }
45 |
46 | if ($LastExitCode -ne 0) {
47 | Write-Host "##vso[task.logissue type=error;]Failed to install npm dependencies."
48 | $script:all_ok = $False
49 | }
50 | Pop-Location
51 |
52 | Build-One build '../iqsharp.sln'
53 |
54 | if (-not $all_ok)
55 | {
56 | throw "At least one project failed to compile. Check the logs."
57 | }
58 |
--------------------------------------------------------------------------------
/build/ci.yml:
--------------------------------------------------------------------------------
1 | name: $(Build.Major).$(Build.Minor).$(DayOfMonth)$(rev:rr)
2 |
3 | trigger: none
4 |
5 | pr:
6 | - main
7 | - feature/*
8 | - features/*
9 | - release/*
10 |
11 | schedules:
12 | - cron: "0 9 * * Sat"
13 | displayName: 'Build for Component Governance'
14 | branches:
15 | include:
16 | - main
17 | always: true
18 |
19 | variables:
20 | Build.Major: 0
21 | Build.Minor: 18
22 | Drops.Dir: $(Build.ArtifactStagingDirectory)/drops
23 | IQSharp.Hosting.Env: 'build-agent-iqsharp'
24 | agent.preferPowerShellOnContainers: false
25 |
26 | jobs:
27 | - job: "iqsharp"
28 | pool:
29 | vmImage: 'ubuntu-latest'
30 | steps:
31 | - template: steps.yml
32 | - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
33 | displayName: 'Component Detection'
34 | inputs:
35 | failOnAlert: true
36 |
37 | - job: "test_selenium"
38 | pool:
39 | vmImage: 'windows-2019'
40 | steps:
41 | - template: steps-selenium.yml
42 | condition: ne(variables['Skip.Tests'], 'true')
43 |
44 | - job: "pack_selfcontained"
45 | dependsOn: "iqsharp"
46 | pool:
47 | vmImage: 'ubuntu-latest'
48 | steps:
49 | - template: steps-selfcontained.yml
50 | condition: and(succeeded(), ne(variables['Enable.Conda'], 'false'))
51 |
52 | - job: "pack_conda_macos"
53 | dependsOn: "pack_selfcontained"
54 | condition: and(succeeded(), ne(variables['Enable.Conda'], 'false'))
55 | pool:
56 | vmImage: 'macOS-latest'
57 | variables:
58 | CondaPath: '/usr/local/bin/'
59 | steps:
60 | - template: steps-conda.yml
61 |
62 | - job: "pack_conda_linux"
63 | dependsOn: "pack_selfcontained"
64 | condition: and(succeeded(), ne(variables['Enable.Conda'], 'false'))
65 | pool:
66 | vmImage: 'ubuntu-latest'
67 | container: 'mcr.microsoft.com/quantum/linux-selfcontained:latest'
68 | variables:
69 | CondaPath: '/miniconda/bin/'
70 | steps:
71 | - template: steps-conda.yml
72 |
73 | - job: "pack_conda_windows"
74 | dependsOn: "pack_selfcontained"
75 | condition: and(succeeded(), ne(variables['Enable.Conda'], 'false'))
76 | pool:
77 | vmImage: 'windows-latest'
78 | container: 'mcr.microsoft.com/quantum/windows-selfcontained:latest'
79 | variables:
80 | CondaPath: 'C:\Miniconda3\Scripts'
81 | steps:
82 | - template: steps-conda.yml
83 |
--------------------------------------------------------------------------------
/build/docs/README.md:
--------------------------------------------------------------------------------
1 | # Building IQ# Reference Documentation
2 |
3 | The contents of this folder automatically builds documentation for each
4 | available magic command.
5 |
--------------------------------------------------------------------------------
/build/e2e.yml:
--------------------------------------------------------------------------------
1 | name: $(Build.Major).$(Build.Minor).$(BuildId)
2 |
3 | parameters:
4 | - name: validation_level
5 | displayName: Validation Level
6 | type: string
7 | default: normal
8 | values:
9 | - minimal
10 | - normal
11 | - full
12 |
13 | trigger: none
14 |
15 | pr:
16 | - main
17 | - feature/*
18 | - features/*
19 | - release/*
20 |
21 | resources:
22 | repositories:
23 | - repository: qdk
24 | type: github
25 | endpoint: github
26 | name: microsoft/qdk
27 | ref: refs/heads/main
28 |
29 | extends:
30 | template: build/qdk-module-e2e.yml@qdk
31 | parameters:
32 | module: iqsharp
33 | validation_level: ${{ parameters.validation_level }}
34 |
--------------------------------------------------------------------------------
/build/manifest-selfcontained.ps1:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env pwsh
2 | #Requires -PSEdition Core
3 |
4 | & "$PSScriptRoot/set-env.ps1"
5 |
6 | @{
7 | Assemblies = @(
8 | "linux-x64/Microsoft.Quantum.IQSharp.dll",
9 | "linux-x64/Microsoft.Quantum.IQSharp.Core.dll",
10 | "linux-x64/Microsoft.Quantum.IQSharp.ExecutionPathTracer.dll",
11 | "linux-x64/Microsoft.Quantum.IQSharp.Jupyter.dll",
12 | "linux-x64/Microsoft.Quantum.IQSharp.Kernel.dll",
13 | "linux-x64/Microsoft.Quantum.IQSharp.Web.dll",
14 | "osx-x64/Microsoft.Quantum.IQSharp.dll",
15 | "osx-x64/Microsoft.Quantum.IQSharp.Core.dll",
16 | "osx-x64/Microsoft.Quantum.IQSharp.ExecutionPathTracer.dll",
17 | "osx-x64/Microsoft.Quantum.IQSharp.Jupyter.dll",
18 | "osx-x64/Microsoft.Quantum.IQSharp.Kernel.dll",
19 | "osx-x64/Microsoft.Quantum.IQSharp.Web.dll",
20 | "win10-x64/Microsoft.Quantum.IQSharp.dll",
21 | "win10-x64/Microsoft.Quantum.IQSharp.Core.dll",
22 | "win10-x64/Microsoft.Quantum.IQSharp.ExecutionPathTracer.dll",
23 | "win10-x64/Microsoft.Quantum.IQSharp.Jupyter.dll",
24 | "win10-x64/Microsoft.Quantum.IQSharp.Kernel.dll",
25 | "win10-x64/Microsoft.Quantum.IQSharp.Web.dll"
26 | ) | ForEach-Object { Get-Item (Join-Path $Env:SELFCONTAINED_OUTDIR $_) };
27 | } | Write-Output;
28 |
--------------------------------------------------------------------------------
/build/manifest.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | <#
5 | .SYNOPSIS
6 | Provides the list of artifacts (Packages and Assemblies) generated by this repository.
7 |
8 | .PARAMETER OutputFormat
9 | Specifies if the output of this script should be a hashtable with the artifacts
10 | as strings with the absolute path (AbsolutePath) or FileInfo structures.
11 | #>
12 | param(
13 | [ValidateSet('FileInfo','AbsolutePath')]
14 | [string] $OutputFormat = 'FileInfo'
15 | );
16 |
17 |
18 | & "$PSScriptRoot/set-env.ps1" | Out-Null
19 |
20 | $artifacts = @{
21 | Packages = @(
22 | "Microsoft.Quantum.IQSharp.Core",
23 | "Microsoft.Quantum.IQSharp.ExecutionPathTracer",
24 | "Microsoft.Quantum.IQSharp.Jupyter",
25 | "Microsoft.Quantum.IQSharp"
26 | ) | ForEach-Object { Join-Path $Env:NUGET_OUTDIR "$_.$Env:NUGET_VERSION.nupkg" };
27 |
28 | Assemblies = @(
29 | "./src/AzureClient/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.AzureClient.dll",
30 | "./src/Core/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.Core.dll",
31 | "./src/ExecutionPathTracer/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.ExecutionPathTracer.dll",
32 | "./src/Jupyter/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.Jupyter.dll",
33 | "./src/Kernel/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.Kernel.dll",
34 | "./src/Tool/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.dll",
35 | "./src/Web/bin/$Env:BUILD_CONFIGURATION/net6.0/Microsoft.Quantum.IQSharp.Web.dll"
36 | ) | ForEach-Object { Join-Path $PSScriptRoot (Join-Path ".." $_) };
37 | }
38 |
39 | if ($OutputFormat -eq 'FileInfo') {
40 | $artifacts.Packages = $artifacts.Packages | ForEach-Object { Get-Item $_ };
41 | $artifacts.Assemblies = $artifacts.Assemblies | ForEach-Object { Get-Item $_ };
42 | }
43 |
44 | $artifacts | Write-Output;
45 |
--------------------------------------------------------------------------------
/build/pack-docs.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 | <#
5 | .SYNOPSIS
6 | Packs documentation for IQ# using a newly built Dockerfile and the
7 | build_docs.py script. See build/docs/README.md.
8 | #>
9 |
10 | param(
11 | [string] $DockerImageTag
12 | );
13 |
14 | $ErrorActionPreference = 'Stop';
15 | & "$PSScriptRoot/set-env.ps1";
16 |
17 | # If we can, pack docs using the documentation build container.
18 | # We use the trick at https://blog.ropnop.com/plundering-docker-images/#extracting-files
19 | # to build a new image containing all the docs we care about, then `docker cp`
20 | # them out.
21 | $tempTag = New-Guid | Select-Object -ExpandProperty Guid;
22 | # When building in release mode, we also want to document additional
23 | # packages that contribute IQ# magic commands.
24 | if ("$Env:BUILD_RELEASETYPE" -eq "release") {
25 | $extraPackages = "--package Microsoft.Quantum.Katas --package Microsoft.Quantum.Chemistry.Jupyter";
26 | } else {
27 | $extraPackages = "";
28 | }
29 | # Note that we want to use a Dockerfile read from stdin so that we can more
30 | # easily inject the right base image into the FROM line. In doing so,
31 | # the build context should include the build_docs.py script that we need.
32 | $dockerfile = @"
33 | FROM ${Env:DOCKER_PREFIX}iqsharp-base:$DockerImageTag
34 |
35 | USER root
36 | RUN pip install click ruamel.yaml
37 | WORKDIR /workdir
38 | RUN chown -R `${USER} /workdir
39 |
40 | USER `${USER}
41 | COPY build_docs.py /workdir
42 | RUN python build_docs.py \
43 | /workdir/drops/docs/iqsharp-magic \
44 | microsoft.quantum.iqsharp.magic-ref \
45 | $extraPackages
46 | "@;
47 | $dockerfile | docker build -t $tempTag -f - (Join-Path $PSScriptRoot "docs");
48 | $tempContainer = docker create $tempTag;
49 | docker cp "${tempContainer}:/workdir/drops/docs/iqsharp-magic" (Join-Path $Env:DOCS_OUTDIR "iqsharp-magic")
50 |
--------------------------------------------------------------------------------
/build/pack-selfcontained.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 | $ErrorActionPreference = 'Stop'
4 |
5 | & (Join-Path $PSScriptRoot "set-env.ps1")
6 | $all_ok = $True
7 |
8 | function Pack-Exe() {
9 | param(
10 | [string] $Project,
11 | [string] $Runtime,
12 | [string] $Configuration = $Env:BUILD_CONFIGURATION
13 | );
14 |
15 | $OutputPath = Join-Path $Env:SELFCONTAINED_OUTDIR $Runtime;
16 |
17 | Write-Host "##[info]Publishing self-contained $Runtime executable to $OutputPath"
18 |
19 | # Suppress generating pdb files.
20 | # See https://github.com/dotnet/cli/issues/2246#issuecomment-320633639.
21 | dotnet publish $Project `
22 | -c $Configuration `
23 | -r $Runtime `
24 | --self-contained true `
25 | -o $OutputPath `
26 | -v $Env:BUILD_VERBOSITY `
27 | /property:DefineConstants=$Env:ASSEMBLY_CONSTANTS `
28 | /property:Version=$Env:ASSEMBLY_VERSION `
29 | /property:InformationalVersion=$Env:SEMVER_VERSION `
30 | /property:PackAsTool=false `
31 | /property:CopyOutputSymbolsToPublishDirectory=false
32 |
33 | # Fix the output when using project references:
34 | # If a project includes native libraries under the "runtimes/$runtime/native" path
35 | # dotnet publish doesn't copy them automatically to the output folder
36 | # and therefore they are not recognized at runtime:
37 | $nativeFolder = (Join-Path $OutputPath "runtimes/$Runtime/native")
38 | if (Test-Path $nativeFolder) {
39 | Copy-Item -Path (Join-Path $nativeFolder "*") -Destination $OutputPath -Recurse
40 | }
41 | }
42 |
43 | & (Join-Path $PSScriptRoot ".." "bootstrap.ps1")
44 |
45 | Write-Host "##[info]Packing IQ# as self-contained executables..."
46 | Push-Location (Join-Path $PSScriptRoot ../src/Tool)
47 | Pack-Exe "./Tool.csproj" -Runtime win10-x64
48 | Pack-Exe "./Tool.csproj" -Runtime osx-x64
49 | Pack-Exe "./Tool.csproj" -Runtime linux-x64
50 | Pop-Location
51 |
52 | Write-Host "##[info]Verifying manifest..."
53 | & (Join-Path $PSScriptRoot "manifest-selfcontained.ps1")
54 |
--------------------------------------------------------------------------------
/build/set-env.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | $ErrorActionPreference = 'Stop'
5 |
6 | Write-Host "Setting up build environment variables"
7 |
8 | If ($Env:BUILD_BUILDNUMBER -eq $null) { $Env:BUILD_BUILDNUMBER = "0.0.1.0" }
9 | If ($Env:BUILD_CONFIGURATION -eq $null) { $Env:BUILD_CONFIGURATION = "Debug"}
10 | If ($Env:BUILD_VERBOSITY -eq $null) { $Env:BUILD_VERBOSITY = "m"}
11 | If ($Env:ASSEMBLY_VERSION -eq $null) { $Env:ASSEMBLY_VERSION = "$Env:BUILD_BUILDNUMBER"}
12 | If ($Env:NUGET_VERSION -eq $null) { $Env:NUGET_VERSION = "$Env:ASSEMBLY_VERSION-alpha"}
13 | If ($Env:PYTHON_VERSION -eq $null) { $Env:PYTHON_VERSION = "${Env:ASSEMBLY_VERSION}a1" }
14 | if ($Env:DOCKER_PREFIX -eq $null) { $Env:DOCKER_PREFIX = "" }
15 |
16 | If ($Env:DROPS_DIR -eq $null) { $Env:DROPS_DIR = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\drops")) }
17 |
18 | If ($Env:NUGET_OUTDIR -eq $null) { $Env:NUGET_OUTDIR = (Join-Path $Env:DROPS_DIR "nugets") }
19 | If (-not (Test-Path -Path $Env:NUGET_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:NUGET_OUTDIR) }
20 |
21 | If ($Env:PYTHON_OUTDIR -eq $null) { $Env:PYTHON_OUTDIR = (Join-Path $Env:DROPS_DIR "wheels") }
22 | If (-not (Test-Path -Path $Env:PYTHON_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:PYTHON_OUTDIR) }
23 |
24 | If ($Env:SELFCONTAINED_OUTDIR -eq $null) { $Env:SELFCONTAINED_OUTDIR = (Join-Path $Env:DROPS_DIR "selfcontained") }
25 | If (-not (Test-Path -Path $Env:SELFCONTAINED_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:SELFCONTAINED_OUTDIR) }
26 |
27 | If ($Env:CONDA_BLD_PATH -eq $null) { $Env:CONDA_BLD_PATH = (Join-Path (Resolve-Path ~) "conda-bld") }
28 | If (-not (Test-Path -Path $Env:CONDA_BLD_PATH)) { [IO.Directory]::CreateDirectory($Env:CONDA_BLD_PATH) }
29 |
30 | If ($Env:CONDA_PKGS_DIRS -eq $null) { $Env:CONDA_PKGS_DIRS = (Join-Path (Resolve-Path ~) "conda-pkgs") }
31 | If (-not (Test-Path -Path $Env:CONDA_PKGS_DIRS)) { [IO.Directory]::CreateDirectory($Env:CONDA_PKGS_DIRS) }
32 |
33 | If ($Env:CONDA_OUTDIR -eq $null) { $Env:CONDA_OUTDIR = (Join-Path $Env:DROPS_DIR "conda") }
34 | If (-not (Test-Path -Path $Env:CONDA_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:CONDA_OUTDIR) }
35 |
36 | If ($Env:DOCS_OUTDIR -eq $null) { $Env:DOCS_OUTDIR = (Join-Path $Env:DROPS_DIR "docs") }
37 | If (-not (Test-Path -Path $Env:DOCS_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:DOCS_OUTDIR) }
38 |
39 |
--------------------------------------------------------------------------------
/build/steps-frameworks.yml:
--------------------------------------------------------------------------------
1 | ##
2 | # Sets the version of .NET and Python to use.
3 | ##
4 |
5 | steps:
6 | - task: UseDotNet@2
7 | displayName: 'Use .NET Core SDK'
8 | inputs:
9 | packageType: sdk
10 | useGlobalJson: true
11 |
12 | - task: UsePythonVersion@0
13 | inputs:
14 | versionSpec: 3.9
15 | displayName: 'Use Python 3.9'
--------------------------------------------------------------------------------
/build/steps-selenium.yml:
--------------------------------------------------------------------------------
1 | ##
2 | # Test IQ# with Selenium.
3 | # Windows build agents have ChromeWebDriver and GeckoWebDriver pre-installed.
4 | ##
5 |
6 | steps:
7 |
8 | ##
9 | # Pre-reqs
10 | ##
11 | - template: steps-frameworks.yml
12 |
13 | - pwsh: ./bootstrap.ps1
14 | displayName: "Bootstrap"
15 | workingDirectory: '$(System.DefaultWorkingDirectory)'
16 |
17 | - task: NuGetAuthenticate@1
18 |
19 | ##
20 | # Install IQ# kernel
21 | ##
22 | - script: dotnet run -c %BUILD_CONFIGURATION% -- install --user
23 | displayName: "Installing IQ#"
24 | workingDirectory: '$(System.DefaultWorkingDirectory)/src/Tool'
25 |
26 | ##
27 | # Test
28 | ##
29 | - script: |
30 | start jupyter notebook --no-browser --NotebookApp.base_url=test/path
31 | pytest -v ./test-selenium.py
32 | displayName: "Running Selenium tests"
33 | workingDirectory: '$(System.DefaultWorkingDirectory)/build'
34 |
--------------------------------------------------------------------------------
/build/steps-selfcontained.yml:
--------------------------------------------------------------------------------
1 | ##
2 | # Pack IQ# self-contained executable.
3 | ##
4 |
5 | steps:
6 |
7 | ##
8 | # Pre-reqs
9 | ##
10 | - template: steps-frameworks.yml
11 |
12 | - task: DownloadBuildArtifacts@0
13 | inputs:
14 | artifactName: iqsharp
15 | downloadPath: '$(System.DefaultWorkingDirectory)/artifact'
16 |
17 | - pwsh: |
18 | Move-Item "$Env:SYSTEM_DEFAULTWORKINGDIRECTORY/artifact/iqsharp/drops" "$Env:SYSTEM_DEFAULTWORKINGDIRECTORY/drops"
19 | displayName: "Copy build artifacts to IQ# working directory"
20 |
21 | - task: NuGetAuthenticate@1
22 |
23 | ##
24 | # Pack
25 | ##
26 | - pwsh: ./pack-selfcontained.ps1
27 | displayName: "Packing IQ# self-contained executable"
28 | workingDirectory: '$(System.DefaultWorkingDirectory)/build'
29 |
30 | ##
31 | # Publish tests results and build artifacts.
32 | ##
33 | - task: PublishBuildArtifacts@1
34 | displayName: 'Publish Artifact: iqsharp'
35 | condition: succeededOrFailed()
36 | inputs:
37 | PathtoPublish: '$(Build.ArtifactStagingDirectory)'
38 | artifactName: iqsharp
39 |
--------------------------------------------------------------------------------
/build/steps.yml:
--------------------------------------------------------------------------------
1 | ##
2 | # Build and test IQ#.
3 | ##
4 |
5 | steps:
6 |
7 | ##
8 | # Pre-reqs
9 | ##
10 | - template: steps-frameworks.yml
11 |
12 | - pwsh: .\bootstrap.ps1
13 | displayName: "Bootstrap"
14 | workingDirectory: '$(System.DefaultWorkingDirectory)'
15 |
16 | - task: NuGetAuthenticate@1
17 |
18 | ##
19 | # Build, test & pack
20 | ##
21 | - pwsh: .\build.ps1
22 | displayName: "Building IQ#"
23 | workingDirectory: '$(System.DefaultWorkingDirectory)/build'
24 |
25 | - pwsh: .\test.ps1
26 | displayName: "Testing IQ#"
27 | workingDirectory: '$(System.DefaultWorkingDirectory)/build'
28 | condition: and(succeeded(), ne(variables['Skip.Tests'], 'true'))
29 |
30 | - pwsh: .\pack.ps1
31 | displayName: "Packing IQ#"
32 | workingDirectory: '$(System.DefaultWorkingDirectory)/build'
33 |
34 | - pwsh: .\manifest.ps1
35 | displayName: "List built packages & assemblies"
36 | workingDirectory: '$(System.DefaultWorkingDirectory)/build'
37 | condition: succeededOrFailed()
38 |
39 | ##
40 | # Publish tests results and build artifacts.
41 | ##
42 | - task: PublishTestResults@2
43 | displayName: 'Publish IQ# tests results'
44 | condition: succeededOrFailed()
45 | inputs:
46 | testResultsFormat: VSTest
47 | testResultsFiles: '$(System.DefaultWorkingDirectory)/**/*.trx'
48 | testRunTitle: 'IQ# tests'
49 |
50 | - task: PublishBuildArtifacts@1
51 | displayName: 'Publish Artifact: iqsharp'
52 | condition: succeededOrFailed()
53 | inputs:
54 | PathtoPublish: '$(Build.ArtifactStagingDirectory)'
55 | artifactName: iqsharp
56 |
--------------------------------------------------------------------------------
/build/test-conda.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 | $ErrorActionPreference = 'Stop'
4 |
5 | & "$PSScriptRoot/set-env.ps1"
6 | $script:AllOk = $True
7 |
8 | function Get-ErrorMessage {
9 | [CmdletBinding()]
10 | param(
11 | [Parameter(ValueFromPipeline=$true)]
12 | $Value
13 | );
14 |
15 | process {
16 | if ($Value -is [System.Management.Automation.ErrorRecord]) {
17 | $Value.Exception.Message | Write-Output
18 | } else {
19 | $Value.ToString() | Write-Output
20 | }
21 | }
22 | }
23 |
24 | function Test-CondaPackage {
25 | [CmdletBinding()]
26 | param (
27 | [Parameter(ValueFromPipeline=$true)]
28 | [string]
29 | $Path
30 | );
31 |
32 | begin {
33 | if (-not (Get-Command conda-build -ErrorAction SilentlyContinue)) {
34 | Write-Host "##vso[task.logissue type=warning;] conda-build not installed. " + `
35 | "Will skip testing conda packages.";
36 | return;
37 | }
38 | $OldPreference = $ErrorActionPreference;
39 | $ErrorActionPreference = "Continue";
40 | }
41 |
42 | process {
43 | Write-Host "##[info]Testing conda package $Path..."
44 | conda-build (Resolve-Path $Path) --test 2>&1 | Get-ErrorMessage;
45 | if ($LASTEXITCODE -ne 0) {
46 | Write-Host "##vso[task.logissue type=error;]conda-build --test failed for $Path.";
47 | $script:AllOk = $false;
48 | }
49 | }
50 |
51 | end {
52 | $ErrorActionPreference = $OldPreference;
53 | }
54 |
55 | }
56 |
57 | Get-ChildItem $Env:CONDA_OUTDIR -Filter "*.tar.bz2" -Recurse | Select-Object -ExpandProperty FullName | Test-CondaPackage
58 |
59 |
60 | if (-not $script:AllOk) {
61 | throw "At least one package failed to build. Check the logs."
62 | }
63 |
--------------------------------------------------------------------------------
/conda-recipes/iqsharp/meta.yaml:
--------------------------------------------------------------------------------
1 | {% set version = environ.get('PYTHON_VERSION', '0.0.0.1') %}
2 |
3 | package:
4 | name: iqsharp
5 | version: "{{ version }}"
6 |
7 | source:
8 | - path: ../../
9 | folder: src
10 |
11 | build:
12 | binary_relocation: False
13 | detect_binary_files_with_prefix: False
14 | has_prefix_files:
15 | - share/jupyter/kernels/iqsharp/kernel.json
16 | script: |
17 | powershell -NoProfile src/conda-recipes/iqsharp/build.ps1 # [win]
18 | pwsh src/conda-recipes/iqsharp/build.ps1 # [not win]
19 |
20 | requirements:
21 | build:
22 | - python
23 | - jupyter
24 |
25 | run:
26 | - python
27 | - jupyter_client
28 |
29 | test:
30 | requires:
31 | - notebook
32 | - python
33 | - pip
34 |
35 | source_files:
36 | - src/conda-recipes/iqsharp/test.ps1
37 | - src/conda-recipes/iqsharp/test.py
38 |
39 | commands:
40 | - pip install jupyter_kernel_test==0.5.0
41 | - powershell -NoProfile src/conda-recipes/iqsharp/test.ps1 # [win]
42 | - pwsh src/conda-recipes/iqsharp/test.ps1 # [not win]
43 |
44 | about:
45 | home: https://docs.microsoft.com/azure/quantum
46 | license: MIT
47 | summary: Microsoft's IQ# kernel providing Q# support for the Jupyter platform.
48 | description: |
49 | For details on how to get started with Jupyter and Q#, please see the guide at https://docs.microsoft.com/azure/quantum/install-jupyter-qkd.
50 | You can also try our Quantum Computing Fundamentals learning path (https://aka.ms/learnqc) to get familiar with the basic concepts
51 | of quantum computing, build quantum programs, and identify the kind of problems that can be solved.
52 | dev_url: https://github.com/microsoft/iqsharp
53 | doc_url: https://docs.microsoft.com/azure/quantum/install-jupyter-qkd
54 |
--------------------------------------------------------------------------------
/conda-recipes/iqsharp/test.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | $failed = $false;
5 |
6 | $Env:IQSHARP_PACKAGE_SOURCE = "$Env:NUGET_OUTDIR"
7 |
8 | # Add the prerelease NuGet feed if this isn't a release build.
9 | if ("$Env:BUILD_RELEASETYPE" -ne "release") {
10 | $NuGetDirectory = Resolve-Path ~
11 | Write-Host "## Writing prerelease NuGet config to $NuGetDirectory ##"
12 | "
13 |
14 |
15 |
16 |
17 | " | Out-File -FilePath $NuGetDirectory/NuGet.Config -Encoding utf8
18 | }
19 |
20 | # Check that iqsharp is installed as a Jupyter kernel.
21 | $kernels = jupyter kernelspec list --json | ConvertFrom-Json;
22 | if ($null -eq $kernels.kernelspecs.iqsharp) {
23 | $failed = $true;
24 | Write-Error "##vso[task.logissue type=error;]Failed: IQ# not found in list of kernelspecs, see kernelspec list below."
25 | jupyter kernelspec list
26 | }
27 |
28 | # Run the kernel unit tests.
29 | Push-Location $PSScriptRoot
30 | python test.py
31 | if ($LastExitCode -ne 0) {
32 | $failed = $true;
33 | Write-Host "##vso[task.logissue type=error;]Failed: IQ# kernel unittests failed"
34 | }
35 | Pop-Location
36 |
37 | # If any tests failed, raise an error code.
38 | if ($failed) {
39 | exit -1;
40 | } else {
41 | Write-Host "## ALL TESTS PASSED ##";
42 | }
43 |
--------------------------------------------------------------------------------
/conda-recipes/iqsharp/test.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 | import unittest
5 | import jupyter_kernel_test
6 |
7 | import sys
8 |
9 | class MyKernelTests(jupyter_kernel_test.KernelTests):
10 | # Required --------------------------------------
11 |
12 | # The name identifying an installed kernel to run the tests against
13 | kernel_name = "iqsharp"
14 |
15 | # language_info.name in a kernel_info_reply should match this
16 | language_name = "qsharp"
17 |
18 | def test_iqsharp_metadata_is_correct(self):
19 | """
20 | Some clients, e.g. nteract, require that metadata on displayable data
21 | is convertable to dict[str, dict[str, Any]]; we test that this is the
22 | case here.
23 | """
24 |
25 | # NB: There is a race condition in jupyter_kernel_test itself on 3.10
26 | # that can cause this test to false positive. Since these tests are
27 | # not intended to test Python integration, but Jupyter adherence
28 | # itself, the Python version is insignificant to this test and can
29 | # be safely locked down to 3.9. See tests on the qsharp-core package
30 | # for unit and integration testing of Q# + Python interop.
31 | if sys.version_info.minor >= 10:
32 | print("This test is not yet supported on Python 3.10.")
33 | raise unittest.SkipTest
34 |
35 | self.flush_channels()
36 | reply, output_msgs = self.execute_helper("%version", timeout=30)
37 | self.assertEqual(output_msgs[0]['header']['msg_type'], 'display_data')
38 | self.assert_(isinstance(output_msgs[0]['content']['metadata'], dict))
39 | for mime_type, contents in output_msgs[0]['content']['metadata'].items():
40 | self.assert_(isinstance(mime_type, str))
41 | self.assert_(isinstance(contents, dict))
42 | self.assertEqual(contents, {})
43 |
44 | if __name__ == '__main__':
45 | unittest.main()
46 |
--------------------------------------------------------------------------------
/conda-recipes/qsharp/build.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 | param(
4 | [string]
5 | $Version
6 | )
7 |
8 | $versionPyContents = @"
9 | # Auto-generated file, do not edit.
10 | ##
11 | # version.py: Specifies the version of the qsharp package.
12 | ##
13 | # Copyright (c) Microsoft Corporation.
14 | # Licensed under the MIT License.
15 | ##
16 | __version__ = "$Version"
17 | is_conda = True
18 | _user_agent_extra = "[$Version](qsharp:conda)"
19 | "@;
20 |
21 | Push-Location src/drops/wheels
22 | # Patch the qsharp-core wheel to add version info.
23 | Get-ChildItem qsharp_core-*.whl `
24 | | ForEach-Object {
25 | Write-Host "##[debug]Patching wheel at $_.";
26 | wheel unpack $_ --dest unpacked
27 | $versionPyPath = Get-Item (Join-Path "." "unpacked" "qsharp_core-$Version" "qsharp" "version.py");
28 | Write-Host "Setting contents of ${versionPyPath}:`n$versionPyContents";
29 | Set-Content -Path $versionPyPath -Value $versionPyContents -Encoding utf8NoBOM;
30 | wheel pack (Join-Path "." "unpacked" "qsharp_core-$Version");
31 | }
32 |
33 | # Install all the wheels, including the wheel we patched above.
34 | Get-ChildItem *.whl `
35 | | ForEach-Object {
36 | pip install --verbose --verbose --no-index --find-links . --prefix $Env:PREFIX $_.Name
37 | }
38 | Pop-Location
39 |
--------------------------------------------------------------------------------
/conda-recipes/qsharp/meta.yaml:
--------------------------------------------------------------------------------
1 | {% set version = environ.get('PYTHON_VERSION', '0.0.0.1') %}
2 |
3 | package:
4 | name: qsharp
5 | version: "{{ version }}"
6 |
7 | source:
8 | - path: ../../
9 | folder: src
10 |
11 | requirements:
12 | build:
13 | - python
14 | - jupyter
15 | - iqsharp={{ version }}
16 |
17 | run:
18 | - python
19 | - iqsharp={{ version }}
20 |
21 | build:
22 | script: |
23 | pwsh -NoProfile src/conda-recipes/qsharp/build.ps1 -Version {{ version }}
24 |
25 | test:
26 | requires:
27 | - python
28 | - iqsharp={{ version }}
29 | - pytest
30 |
31 | source_files:
32 | - src/conda-recipes/qsharp/test.ps1
33 | - src/conda-recipes/qsharp/tests.py
34 |
35 | commands:
36 | # NB: We install QuTiP this way to avoid turning on conda-forge when building
37 | # the test environment, as that introduces a lot of potential
38 | # conflicts. In particular, we want defaults to take priority over
39 | # conda-forge.
40 | - conda install --yes -c conda-forge qutip
41 | - conda install --yes attrs
42 | - powershell -NoProfile src/conda-recipes/qsharp/test.ps1 # [win]
43 | - pwsh src/conda-recipes/qsharp/test.ps1 # [not win]
44 |
45 | about:
46 | home: https://docs.microsoft.com/azure/quantum
47 | license: MIT
48 | summary: Python client for Q#, a domain-specific quantum programming language.
49 | description: |
50 | For details on how to get started with Python and Q#, please see the guide at https://docs.microsoft.com/azure/quantum/install-python-qdk.
51 | You can also try our Quantum Computing Fundamentals learning path (https://aka.ms/learnqc) to get familiar with the basic concepts
52 | of quantum computing, build quantum programs, and identify the kind of problems that can be solved.
53 | dev_url: https://github.com/microsoft/iqsharp
54 | doc_url: https://docs.microsoft.com/azure/quantum/install-python-qdk
55 |
--------------------------------------------------------------------------------
/conda-recipes/qsharp/test.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 | $failed = $false;
5 |
6 | $Env:IQSHARP_PACKAGE_SOURCE = "$Env:NUGET_OUTDIR"
7 | $Env:IQSHARP_LOG_LEVEL = "Debug"
8 |
9 | Push-Location (Resolve-Path $PSScriptRoot)
10 | pytest -v --log-level=Debug tests.py
11 |
12 | # Check for success.
13 | if ($LastExitCode -ne 0) {
14 | $failed = $true;
15 | Write-Host "##vso[task.logissue type=error;]Failed: Invoking qsharp from python."
16 | }
17 | Pop-Location
18 |
19 | # If any tests failed, raise an error code.
20 | if ($failed) {
21 | exit -1;
22 | } else {
23 | Write-Host "## ALL TESTS PASSED ##";
24 | }
25 |
--------------------------------------------------------------------------------
/conda-recipes/qsharp/tests.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 | import logging
5 | logging.basicConfig(level=logging.DEBUG)
6 |
7 | import os
8 |
9 | import pytest
10 | os.environ["QSHARP_PY_ISCONDA"] = "True"
11 |
12 | from importlib import import_module
13 | from attr import attr
14 | import qsharp
15 |
16 | # We also want to make sure that QuTiP is enabled for tests when running via
17 | # conda, even though these tests are optional for the qsharp wheel.
18 | # We use try_import_qutip to force a successful import to populate the same
19 | # cache of the import call used later by tests.
20 | from qsharp.utils import try_import_qutip
21 | try_import_qutip(optional=False)
22 |
23 | def test_simple_compile():
24 | """
25 | Verifies that compile works
26 | """
27 | op = qsharp.compile( """
28 | operation HelloQ() : Result
29 | {
30 | Message($"Hello from quantum world!");
31 | return One;
32 | }
33 | """)
34 | r = op.simulate()
35 | assert r == qsharp.Result.One
36 |
37 | def test_user_agent_extra():
38 | """
39 | Verifies that the extra information sent with the user agent for this
40 | package correctly marks that the package was installed with conda.
41 | """
42 | import qsharp.version
43 | assert getattr(qsharp.version, "is_conda", False)
44 | assert qsharp.version._user_agent_extra == f"[{qsharp.__version__}](qsharp:conda)"
45 |
46 | # Forward tests from the unit testing modules.
47 | def _forward_tests(module_name) -> None:
48 | logging.debug(f"Importing module {module_name} to forward tests...")
49 | module = import_module(module_name)
50 |
51 | for attr_name in dir(module):
52 | if attr_name.startswith("test_") or attr_name.startswith("Test"):
53 | logging.debug(f"Forwarding {attr_name} from {module_name}.")
54 | globals()[attr_name] = getattr(module, attr_name)
55 |
56 | _forward_tests("qsharp.tests.test_iqsharp")
57 | _forward_tests("qsharp.tests.test_serialization")
58 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "6.0.100",
4 | "rollForward": "latestMinor"
5 | },
6 | "msbuild-sdks": {
7 | "Microsoft.Quantum.Sdk": "0.28.302812"
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/images/test-environments/README.md:
--------------------------------------------------------------------------------
1 | # Self-contained environments for conda testing and packing
2 |
3 | Testing CI runs conda testing and packing on the build agent host. This can make it difficult to find and diagnose issues caused by missing dependencies. For example the build agent host can inadvertently provide dependencies that should be provided by conda packages themselves. Conda testing and packing should be executed from within a brand-new Docker container, in order to emulate a minimal environment as may be installed by users.
4 |
5 | Each Dockerfile in this directory represents the contained environments to be used from the build agent for conda testing and packing. Whenever any of these files are changed the new images will be built and pushed to the internal MCR `msint.azure.io`. MacOS is not supported as a pipeline Container job and requires further investigation.
6 |
7 | Each Dockerfile includes instructions to download the following tools:
8 |
9 | * PowerShell 7
10 | * Miniconda3
11 | * Python 3.9
12 | * Git
13 |
--------------------------------------------------------------------------------
/images/test-environments/linux/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG CONDA_VER=latest
2 | ARG UBUNTU_VER=20.04
3 | ARG OS_TYPE=x86_64
4 | ARG PY_VER=3.9
5 |
6 | FROM mcr.microsoft.com/mirror/docker/library/ubuntu:${UBUNTU_VER}
7 |
8 | RUN apt-get update && apt-get install -yq curl wget jq
9 |
10 | ARG CONDA_VER
11 | ARG OS_TYPE
12 | # Install miniconda to /miniconda
13 | RUN curl -LO "http://repo.continuum.io/miniconda/Miniconda3-${CONDA_VER}-Linux-${OS_TYPE}.sh" && \
14 | bash Miniconda3-${CONDA_VER}-Linux-${OS_TYPE}.sh -p /miniconda -b && \
15 | rm Miniconda3-${CONDA_VER}-Linux-${OS_TYPE}.sh
16 |
17 | ARG UBUNTU_VER
18 | # Download the Microsoft repository GPG keys
19 | RUN wget -q "https://packages.microsoft.com/config/ubuntu/${UBUNTU_VER}/packages-microsoft-prod.deb"
20 | # Register the Microsoft repository GPG keys
21 | RUN dpkg -i packages-microsoft-prod.deb
22 |
23 | ARG DEBIAN_FRONTEND=noninteractive
24 | # Update the list of packages after we added packages.microsoft.com
25 | RUN apt-get update && \
26 | apt-get -y install \
27 | git \
28 | powershell \
29 | # install the below packages to pick up the latest security patch
30 | logsave \
31 | libext2fs2 \
32 | libss2 \
33 | libcom-err2 \
34 | e2fsprogs \
35 | libssl1.1 \
36 | openssl && \
37 | # We clean the apt cache at the end of each apt command so that the caches
38 | # don't get stored in each layer.
39 | apt-get clean && rm -rf /var/lib/apt/lists/
40 |
41 | RUN ./miniconda/bin/conda update -y certifi
42 | RUN ./miniconda/bin/conda update -y cryptography
43 |
--------------------------------------------------------------------------------
/images/test-environments/macos/Dockerfile:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/images/test-environments/macos/Dockerfile
--------------------------------------------------------------------------------
/images/test-environments/windows/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/windows/servercore:ltsc2022 AS buildbase
2 |
3 | RUN powershell (New-Object System.Net.WebClient).DownloadFile('https://repo.anaconda.com/miniconda/Miniconda3-py39_4.12.0-Windows-x86_64.exe', 'Miniconda3.exe') && \
4 | powershell (Get-FileHash .\Miniconda3.exe).Hash -eq '1ACBC2E8277DDD54A5F724896C7EDEE112D068529588D944702966C867E7E9CC' && \
5 | powershell Unblock-File Miniconda3.exe && \
6 | Miniconda3.exe /InstallationType=JustMe /RegisterPython=1 /S /D=C:\Miniconda3
7 |
8 | FROM mcr.microsoft.com/powershell:lts-windowsservercore-ltsc2022
9 |
10 | COPY --from=buildbase C:/Miniconda3 C:/Miniconda3
11 |
12 | USER ContainerAdministrator
13 |
14 | RUN C:\Miniconda3\Library\bin\conda init && \
15 | C:\Miniconda3\Library\bin\conda clean -afy
16 |
17 | CMD ["cmd"]
18 |
--------------------------------------------------------------------------------
/src/AzureClient/AzureClient.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | x64
6 | Microsoft.Quantum.IQSharp.AzureClient
7 | Microsoft.Quantum.IQSharp.AzureClient
8 | true
9 | 10.0
10 | enable
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/src/AzureClient/AzureFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Azure.Core;
7 |
8 | using Azure.Quantum;
9 | using Microsoft.Azure.Quantum;
10 | using Microsoft.Quantum.Runtime;
11 |
12 | namespace Microsoft.Quantum.IQSharp.AzureClient
13 | {
14 | ///
15 | public class AzureFactory : IAzureFactory
16 | {
17 | ///
18 | public Azure.Quantum.IWorkspace CreateWorkspace(string subscriptionId,
19 | string resourceGroup,
20 | string workspaceName,
21 | string location,
22 | TokenCredential credential,
23 | QuantumJobClientOptions options) =>
24 | new Azure.Quantum.Workspace(
25 | subscriptionId: subscriptionId,
26 | resourceGroupName: resourceGroup,
27 | workspaceName: workspaceName,
28 | location: location,
29 | credential: credential,
30 | options: options);
31 |
32 | ///
33 | public IQuantumMachine? CreateMachine(Azure.Quantum.IWorkspace workspace, string targetName, string storageConnectionString) =>
34 | QuantumMachineFactory.CreateMachine(workspace, targetName, storageConnectionString);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/AzureClient/EntryPoint/EntryPointOperationResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Text;
9 |
10 | namespace Microsoft.Quantum.IQSharp.AzureClient
11 | {
12 | internal class EntryPointOperationResolver : IOperationResolver
13 | {
14 | private IEntryPointGenerator EntryPointGenerator { get; }
15 |
16 | public EntryPointOperationResolver(IEntryPointGenerator entryPointGenerator) =>
17 | EntryPointGenerator = entryPointGenerator;
18 |
19 | public OperationInfo Resolve(string name) => OperationResolver.ResolveFromAssemblies(name, RelevantAssemblies());
20 |
21 | private IEnumerable RelevantAssemblies()
22 | {
23 | if (EntryPointGenerator.SnippetsAssemblyInfo is not null) yield return EntryPointGenerator.SnippetsAssemblyInfo;
24 | foreach (var asm in EntryPointGenerator.WorkspaceAssemblies) yield return asm;
25 | foreach (var asm in EntryPointGenerator.References.Assemblies) yield return asm;
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/AzureClient/EntryPoint/IEntryPoint.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.IO;
7 | using System.Threading;
8 | using Microsoft.Quantum.QsCompiler;
9 | using Microsoft.Quantum.Runtime;
10 | using Microsoft.Quantum.Runtime.Submitters;
11 |
12 | namespace Microsoft.Quantum.IQSharp.AzureClient
13 | {
14 | ///
15 | /// Represents a Q# entry point that can be submitted
16 | /// for execution to Azure Quantum.
17 | ///
18 | public interface IEntryPoint
19 | {
20 | ///
21 | /// Submits the entry point for execution to Azure Quantum.
22 | ///
23 | /// The object representing the job submission target.
24 | /// The object representing the submission context for the job.
25 | /// Cancellation token used to interrupt this submission.
26 | /// The details of the submitted job.
27 | public Task SubmitAsync(IQuantumMachine machine, AzureSubmissionContext submissionContext, CancellationToken cancellationToken = default);
28 |
29 | ///
30 | /// Submits the entry point for execution to Azure Quantum.
31 | ///
32 | /// The object representing the job submission target.
33 | /// The object representing the submission context for the job.
34 | /// Cancellation token used to interrupt this submission.
35 | /// The details of the submitted job.
36 | public Task SubmitAsync(IQirSubmitter submitter, AzureSubmissionContext submissionContext, CancellationToken cancellationToken = default);
37 |
38 | ///
39 | /// The stream from which QIR bitcode for the entry point can be read.
40 | ///
41 | public Stream? QirStream { get; }
42 |
43 | ///
44 | /// The target capability which the QIR was generated for.
45 | ///
46 | public TargetCapability? TargetCapability { get; }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/AzureClient/EntryPoint/IEntryPointGenerator.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.Threading.Tasks;
7 | using Microsoft.Quantum.QsCompiler;
8 |
9 | namespace Microsoft.Quantum.IQSharp.AzureClient
10 | {
11 | ///
12 | /// This service is capable of generating entry points for
13 | /// job submission to Azure Quantum.
14 | ///
15 | public interface IEntryPointGenerator
16 | {
17 | ///
18 | /// Gets the compiled workspace assemblies for the most recently-generated entry point.
19 | ///
20 | public AssemblyInfo[] WorkspaceAssemblies { get; }
21 |
22 | ///
23 | /// Gets the compiled snippets assembly for the most recently-generated entry point.
24 | ///
25 | public AssemblyInfo? SnippetsAssemblyInfo { get; }
26 |
27 | ///
28 | /// Gets the compiled entry point assembly for the most recently-generated entry point.
29 | ///
30 | public AssemblyInfo? EntryPointAssemblyInfo { get; }
31 |
32 | ///
33 | /// Gets the references used for compilation of the entry point assembly.
34 | ///
35 | public IReferences References { get; }
36 |
37 | ///
38 | /// Compiles an assembly and returns the object
39 | /// representing an entry point that wraps the specified operation.
40 | ///
41 | /// The name of the operation to wrap in an entry point.
42 | /// The intended execution target for the compiled entry point.
43 | /// The capability of the intended execution target.
44 | /// When true, uses QIR to generate the entry point.
45 | /// The generated entry point.
46 | public Task Generate(string operationName, string? executionTarget,
47 | TargetCapability? capability = null, bool generateQir = false);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/AzureClient/IAzureFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Azure.Core;
7 | using Azure.Quantum;
8 |
9 | namespace Microsoft.Quantum.IQSharp.AzureClient
10 | {
11 | ///
12 | /// This service is used to create instances of classes from the AzureQuantum packages.
13 | /// Mostly used to support Mock instances.
14 | ///
15 | public interface IAzureFactory
16 | {
17 | ///
18 | /// Creates an instance of an Azure Quantum Workspace client
19 | ///
20 | Azure.Quantum.IWorkspace CreateWorkspace(string subscriptionId, string resourceGroup, string workspaceName, string location, TokenCredential credential, QuantumJobClientOptions options);
21 |
22 | ///
23 | /// Creates an instance of an Azure Quantum Machine
24 | ///
25 | Runtime.IQuantumMachine? CreateMachine(Azure.Quantum.IWorkspace workspace, string targetName, string storageConnectionString);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/AzureClient/Mocks/MockAzureExecutionTarget.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.Collections.Generic;
7 | using System.Diagnostics.CodeAnalysis;
8 | using Microsoft.Azure.Quantum;
9 | using Microsoft.Quantum.QsCompiler;
10 | using Microsoft.Quantum.Runtime;
11 | using Microsoft.Quantum.Runtime.Submitters;
12 |
13 | namespace Microsoft.Quantum.IQSharp.AzureClient
14 | {
15 | internal record MockAzureExecutionTarget : AzureExecutionTarget
16 | {
17 | MockAzureExecutionTarget(TargetStatusInfo target)
18 | : this(target?.TargetId)
19 | { }
20 |
21 | MockAzureExecutionTarget(string? targetId)
22 | : base(targetId)
23 | { }
24 |
25 | // We test using a non-QDK package name to avoid possible version conflicts.
26 | public override string PackageName => "Microsoft.Extensions.DependencyInjection";
27 |
28 | public static MockAzureExecutionTarget? CreateMock(TargetStatusInfo target) =>
29 | CreateMock(target?.TargetId);
30 |
31 | public static MockAzureExecutionTarget? CreateMock(string? targetId) =>
32 | IsValid(targetId)
33 | ? new MockAzureExecutionTarget(targetId)
34 | : null;
35 |
36 |
37 | public override bool TryGetQirSubmitter(Azure.Quantum.IWorkspace workspace, string storageConnectionString, TargetCapability? targetCapability, [NotNullWhen(true)] out IQirSubmitter? submitter)
38 | {
39 | if (this.TargetId?.EndsWith("mock-qir") ?? false)
40 | {
41 | submitter = new MockQirSubmitter(new List());
42 | return true;
43 | }
44 | else
45 | {
46 | submitter = null;
47 | return false;
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/AzureClient/Mocks/MockProviderStatus.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.Collections.Generic;
7 |
8 | using Microsoft.Azure.Quantum;
9 |
10 | namespace Microsoft.Quantum.IQSharp.AzureClient
11 | {
12 | internal class MockProviderStatus : ProviderStatusInfo
13 | {
14 | private string _id;
15 |
16 | public MockProviderStatus(global::Microsoft.Azure.Quantum.IWorkspace ws, string? id = null)
17 | : base()
18 | {
19 | _id = id ?? string.Empty;
20 | }
21 |
22 | public override string ProviderId => _id;
23 |
24 | public override IEnumerable Targets =>
25 | new[]
26 | {
27 | new MockTargetStatus(_id.ToLower() + "." + "simulator"),
28 | new MockTargetStatus(_id.ToLower() + "." + "mock"),
29 | new MockTargetStatus(_id.ToLower() + "." + "mock-qir")
30 | };
31 | }
32 | }
--------------------------------------------------------------------------------
/src/AzureClient/Mocks/MockTargetStatus.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Microsoft.Azure.Quantum;
7 |
8 | namespace Microsoft.Quantum.IQSharp.AzureClient
9 | {
10 | internal class MockTargetStatus : TargetStatusInfo
11 | {
12 | public MockTargetStatus(string id) : base()
13 | {
14 | this.TargetId = id;
15 | }
16 |
17 | public override string TargetId { get; }
18 |
19 | public override string ToString() => $"MockTargetStatus {{ TargetId = \"{TargetId}\" }}";
20 | }
21 | }
--------------------------------------------------------------------------------
/src/AzureClient/Mocks/MocksAzureFactory.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using Azure.Core;
5 | using Azure.Quantum;
6 | using Microsoft.Quantum.Runtime;
7 |
8 | namespace Microsoft.Quantum.IQSharp.AzureClient
9 | {
10 | ///
11 | /// This service is used to create instances of classes from the AzureQuantum packages.
12 | /// Mostly used to support Mock instances.
13 | ///
14 | public class MocksAzureFactory : IAzureFactory
15 | {
16 | ///
17 | public Azure.Quantum.IWorkspace CreateWorkspace(string subscriptionId, string resourceGroup, string workspaceName, string location, TokenCredential credential, QuantumJobClientOptions options) =>
18 | new MockAzureWorkspace(
19 | subscriptionId: subscriptionId,
20 | resourceGroup: resourceGroup,
21 | workspaceName: workspaceName,
22 | location: location,
23 | options: options);
24 |
25 | ///
26 | public IQuantumMachine CreateMachine(Azure.Quantum.IWorkspace workspace, string targetName, string storageConnectionString) =>
27 | new MockQuantumMachine(workspace as MockAzureWorkspace);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/AzureClient/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | [assembly: InternalsVisibleTo("Tests.IQsharp" + SigningConstants.PUBLIC_KEY)]
4 |
--------------------------------------------------------------------------------
/src/AzureClient/Properties/GlobalUsings.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | global using Microsoft.Jupyter.Core;
5 | global using Microsoft.Quantum.IQSharp.Jupyter;
6 |
--------------------------------------------------------------------------------
/src/AzureClient/Visualization/DeviceCodeResultEncoders.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Globalization;
9 | using System.Linq;
10 | using System.Text;
11 | using Microsoft.Azure.Quantum;
12 | using Microsoft.Identity.Client;
13 | using Microsoft.Jupyter.Core;
14 | using Newtonsoft.Json;
15 | using Newtonsoft.Json.Linq;
16 |
17 | namespace Microsoft.Quantum.IQSharp.AzureClient
18 | {
19 | ///
20 | /// Encodes a object as HTML.
21 | ///
22 | public class DeviceCodeResultToHtmlEncoder : IResultEncoder
23 | {
24 | private static readonly IResultEncoder tableEncoder = new TableToHtmlDisplayEncoder();
25 |
26 | ///
27 | public string MimeType => MimeTypes.Html;
28 |
29 | ///
30 | public EncodedData? Encode(object displayable)
31 | {
32 | if (displayable is DeviceCodeResult deviceCode)
33 | {
34 | var guid = Guid.NewGuid();
35 | var htmlMessage = deviceCode.Message
36 | .Replace(deviceCode.VerificationUrl, $"{deviceCode.VerificationUrl}
")
37 | .Replace(
38 | deviceCode.UserCode,
39 | $@"
40 |
41 | {deviceCode.UserCode.Trim()}"
42 | );
43 | var attach = $@"";
46 | return (htmlMessage + "\n" + attach).ToEncodedData();
47 | } else return null;
48 | }
49 | }
50 |
51 | ///
52 | /// Encodes a object as plain text.
53 | ///
54 | public class DeviceCodeResultToTextEncoder : IResultEncoder
55 | {
56 | private static readonly IResultEncoder tableEncoder = new TableToHtmlDisplayEncoder();
57 |
58 | ///
59 | public string MimeType => MimeTypes.PlainText;
60 |
61 | ///
62 | public EncodedData? Encode(object displayable) =>
63 | displayable is DeviceCodeResult deviceCode
64 | ? deviceCode.Message.ToEncodedData()
65 | : null as EncodedData?;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/AzureClient/Visualization/JsonConverters.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Newtonsoft.Json;
7 |
8 | namespace Microsoft.Quantum.IQSharp.AzureClient;
9 | ///
10 | /// Declares classes derived from defined in this assembly.
11 | ///
12 | public static class JsonConverters
13 | {
14 | private static readonly ImmutableList allConverters = ImmutableList.Create(
15 | new CloudJobJsonConverter(),
16 | new CloudJobListJsonConverter(),
17 | new TargetStatusJsonConverter(),
18 | new TargetStatusListJsonConverter(),
19 | new AzureClientErrorJsonConverter(),
20 | new TargetCapabilityConverter(),
21 | new ResourceEstimationResultConverter()
22 | );
23 |
24 | ///
25 | /// Gets an array of instances of each class derived from defined in this assembly.
26 | ///
27 | public static JsonConverter[] AllConverters => allConverters.ToArray();
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/src/AzureClient/Visualization/ResourceEstimationEncoder.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.Extensions.Logging;
5 | using Newtonsoft.Json.Linq;
6 | using Newtonsoft.Json;
7 | using System.IO;
8 | using System.Text;
9 | using Markdig;
10 |
11 | namespace Microsoft.Quantum.IQSharp.AzureClient;
12 |
13 | ///
14 | /// The results of a resource estimation job.
15 | ///
16 | public record class ResourceEstimationResult(JToken RawJson)
17 | {
18 | internal JToken GetValueFromPath(string path)
19 | {
20 | var value = RawJson;
21 | foreach (var p in path.Split("/"))
22 | {
23 | value = value.Value(p) is {} newValue
24 | ? newValue
25 | : throw new JsonException($"Malformed JSON. Failed at '{p}' to retrieve value for '{path}'");
26 | }
27 | return value;
28 | }
29 | }
30 |
31 | internal static class ResourceEstimationResultExtensions
32 | {
33 | internal static ResourceEstimationResult ToResourceEstimationResults(this Stream stream) =>
34 | new ResourceEstimationResult(JToken.Parse(new StreamReader(stream).ReadToEnd()));
35 |
36 | internal static T GetValue(this JToken token, object key) =>
37 | token.Value(key) is {} newValue
38 | ? newValue
39 | : throw new Exception($"Malformed JSON. Failed to retrieve value for '{key}' from '{token.Path}'");
40 | }
41 |
42 | ///
43 | /// Encodes a object as JSON.
44 | ///
45 | public class ResourceEstimationResultConverter : JsonConverter
46 | {
47 | ///
48 | public override ResourceEstimationResult ReadJson(JsonReader reader, Type objectType, ResourceEstimationResult? existingValue, bool hasExistingValue, JsonSerializer serializer)
49 | => throw new NotImplementedException();
50 |
51 | ///
52 | public override void WriteJson(JsonWriter writer, ResourceEstimationResult? value, JsonSerializer serializer)
53 | {
54 | if (value != null) JToken.FromObject(value.RawJson).WriteTo(writer);
55 | }
56 | }
--------------------------------------------------------------------------------
/src/Common/GlobalUsings.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | global using System;
5 | global using System.Linq;
6 | global using System.Threading.Tasks;
7 | global using System.Collections.Generic;
8 | global using System.Collections.Immutable;
9 |
--------------------------------------------------------------------------------
/src/Core/CommonMessages.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp.Common;
5 |
6 | ///
7 | /// Abstracts error and warning messages for conditions that may commonly
8 | /// occur during IQ# sessions.
9 | ///
10 | public static class CommonMessages
11 | {
12 | public record UserMessage(
13 | string Text,
14 | string? Hint = null
15 | );
16 |
17 | public record NoSuchOperation(string OperationName) : UserMessage(
18 | Text: $"No Q# operation with name `{OperationName}` has been defined.",
19 | Hint: $"You may have misspelled the name `{OperationName}`, or you may have forgotten to run a cell above."
20 | );
21 | }
22 |
--------------------------------------------------------------------------------
/src/Core/Compat.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace System.Runtime.CompilerServices;
5 | /// Allows using init-only properties in netstandard2.1 project. Note that
6 | /// init-only is only enforced for net5.0 and later callers.
7 | public class IsExternalInit {}
8 |
--------------------------------------------------------------------------------
/src/Core/Events/IEventService.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp
5 | {
6 | ///
7 | /// A DependencyInjection service for the Event Publisher-Subscriber
8 | ///
9 | public interface IEventService
10 | {
11 | ///
12 | /// Gets the corresponding typed EventPubSub for the given event type
13 | ///
14 | /// The type of the event
15 | /// The type of the arguments of the event
16 | /// The typed EventPubSub for the given event type
17 | EventPubSub Events()
18 | where TEvent : Event;
19 |
20 | ///
21 | /// Instantiate and trigger the event, invoking all subscriber Actions
22 | ///
23 | /// The type of the event
24 | /// The type of the arguments of the event
25 | /// The arguments of the event
26 | void Trigger(TArgs args)
27 | where TEvent : Event, new();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/Core/Events/ServiceInitializedEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp
5 | {
6 | ///
7 | /// A event to track when services get initialized.
8 | /// This is useful for scenarios where we want to do something immediately
9 | /// after a specific service is initialized, for example subscribing to the
10 | /// service events for telemetry purposes.
11 | ///
12 | /// The type (usually the interface) of the service
13 | public record ServiceInitializedEvent : Event;
14 |
15 | ///
16 | /// Extension methods to make it easy to consume and trigger ServiceInitialized events
17 | ///
18 | public static class ServiceInitializedEventExtensions
19 | {
20 | ///
21 | /// Instantiate and trigger the ServiceInitialized event, invoking all subscriber Actions
22 | ///
23 | /// The type (usually the interface) of the service
24 | /// The event service where the EventSubPub lives
25 | /// The service that got initialized
26 | public static void TriggerServiceInitialized(this IEventService eventService, TService service)
27 | {
28 | eventService?.Trigger, TService>(service);
29 | }
30 |
31 | ///
32 | /// Gets the typed EventPubSub for the ServiceInitialized event
33 | ///
34 | /// The type (usually the interface) of the service
35 | /// The event service where the EventSubPub lives
36 | /// The typed EventPubSub for the ServiceInitialized event
37 | public static EventPubSub, TService> OnServiceInitialized(this IEventService eventService)
38 | {
39 | return eventService?.Events, TService>();
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/src/Core/Exceptions/CompilationErrorsException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Collections.Immutable;
7 | using System.Linq;
8 | using System.Text;
9 | using Microsoft.VisualStudio.LanguageServer.Protocol;
10 |
11 | namespace Microsoft.Quantum.IQSharp.Common
12 | {
13 | public class CompilationErrorsException : InvalidOperationException
14 | {
15 | public CompilationErrorsException(QSharpLogger logger) : this(
16 | logger.Logs.ToArray()
17 | )
18 | { }
19 |
20 | public CompilationErrorsException(Diagnostic[] diagnostics) : base("Invalid snippet code")
21 | {
22 | this.diagnostics = diagnostics.ToImmutableList();
23 | }
24 |
25 | public IEnumerable ErrorDiagnostics =>
26 | Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error);
27 |
28 | public IEnumerable Errors =>
29 | ErrorDiagnostics.Select(QsCompiler.Diagnostics.Formatting.MsBuildFormat);
30 | private readonly ImmutableList diagnostics;
31 | public IEnumerable Diagnostics => diagnostics;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/Core/Exceptions/InvalidWorkspaceException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace Microsoft.Quantum.IQSharp.Common
9 | {
10 | ///
11 | /// This Exception gets triggered whenever the user tries to access operations
12 | /// on the current Workspace, but the Workspace was not correctly built.
13 | ///
14 | public class InvalidWorkspaceException : InvalidOperationException
15 | {
16 | public InvalidWorkspaceException(params string[] errors) : base("Invalid workspace")
17 | {
18 | this.Errors = errors;
19 | }
20 |
21 | public string[] Errors { get; }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Core/Extensions/Async.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp;
5 |
6 | public static partial class Extensions
7 | {
8 |
9 | internal static async Task> Collect(this IAsyncEnumerable source)
10 | {
11 | var result = new List();
12 | await foreach (var item in source)
13 | {
14 | result.Add(item);
15 | }
16 | return result;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/Core/Extensions/FSharp.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 |
5 | namespace Microsoft.Quantum.IQSharp;
6 |
7 | public static partial class Extensions
8 | {
9 |
10 | public static T? AsObj(this FSharp.Core.FSharpOption option)
11 | where T: class =>
12 | FSharp.Core.FSharpOption.get_IsSome(option)
13 | ? option.Value
14 | : (T?)null;
15 | }
16 |
--------------------------------------------------------------------------------
/src/Core/Extensions/IO.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.IO;
9 | using System.Linq;
10 | using System.Runtime.CompilerServices;
11 | using System.Threading;
12 | using System.Threading.Tasks;
13 | using Microsoft.Quantum.IQSharp.Common;
14 | using NuGet.Protocol.Core.Types;
15 |
16 | namespace Microsoft.Quantum.IQSharp
17 | {
18 |
19 | internal static class IoExtensions
20 | {
21 |
22 | public static async IAsyncEnumerable ReadAllLinesAsync(this StreamReader reader)
23 | {
24 | while (true)
25 | {
26 | var line = await reader.ReadLineAsync();
27 | if (line == null)
28 | {
29 | yield break;
30 | }
31 | else
32 | {
33 | yield return line;
34 | }
35 | }
36 | }
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Core/Extensions/Qsharp.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System.Collections.Generic;
5 | using System.Data;
6 | using Microsoft.Quantum.QsCompiler.SyntaxTree;
7 | using Microsoft.Quantum.Simulation.Simulators;
8 |
9 | namespace Microsoft.Quantum.IQSharp
10 | {
11 | ///
12 | /// Extensions for Q# components.
13 | ///
14 | public static partial class Extensions
15 | {
16 | public static readonly QsQualifiedName UNKNOWN_OPERATION = new QsQualifiedName("UNKNOWN", "UNKNOWN");
17 |
18 | ///
19 | /// Returns the source of the given QsNamespaceElement (either QsCallable or QsCustomTypes)
20 | ///
21 | public static string SourceFile(this QsNamespaceElement e) =>
22 | (e switch
23 | {
24 | QsNamespaceElement.QsCallable { Item: var callable } => callable.Source,
25 | QsNamespaceElement.QsCustomType { Item: var type } => type.Source,
26 | _ => null
27 | })?.AssemblyOrCodeFile ?? "[Unknown]";
28 |
29 | ///
30 | /// Returns the name of the given QsNamespaceElement (either QsCallable or QsCustomTypes)
31 | ///
32 | public static string ToFullName(this QsNamespaceElement e)
33 | {
34 | var name = UNKNOWN_OPERATION;
35 |
36 | if (e is QsNamespaceElement.QsCallable c)
37 | {
38 | name = c.Item.FullName;
39 | }
40 | else if (e is QsNamespaceElement.QsCustomType t)
41 | {
42 | name = t.Item.FullName;
43 | }
44 |
45 | return $"{name.Namespace}.{name.Name}";
46 | }
47 |
48 | ///
49 | /// Formats a qualified name using dotted-name syntax.
50 | ///
51 | public static string ToFullName(this QsQualifiedName name) =>
52 | name?.Namespace + "." + name?.Name;
53 |
54 | ///
55 | /// Removes the given namespace, from the given name, iff name starts with namespace.
56 | ///
57 | public static string WithoutNamespace(this string name, string ns) => name.StartsWith(ns) ? name.Substring(ns.Length + 1) : name;
58 |
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/Core/Extensions/ServiceCollection.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System;
7 | using System.Threading.Tasks;
8 | using Microsoft.Extensions.DependencyInjection;
9 | using Microsoft.Extensions.Logging;
10 |
11 | namespace Microsoft.Quantum.IQSharp
12 | {
13 | ///
14 | /// Extensions for IServiceCollection
15 | ///
16 | public static partial class Extensions
17 | {
18 | public static T AddIQSharp(this T services)
19 | where T: IServiceCollection
20 | {
21 | services.AddSingleton();
22 | services.AddSingleton();
23 | services.AddSingleton();
24 | services.AddSingleton();
25 | services.AddSingleton();
26 | services.AddSingleton();
27 | services.AddSingleton();
28 | services.AddSingleton();
29 | services.AddSingleton();
30 |
31 | return services;
32 | }
33 |
34 | public static Task GetRequiredServiceInBackground(this IServiceProvider services, ILogger? logger = null)
35 | {
36 | var eventService = services.GetRequiredService();
37 | eventService.OnServiceInitialized().On += (service) =>
38 | {
39 | logger?.LogInformation(
40 | "Service {Service} initialized {Time} after startup.",
41 | typeof(T),
42 | DateTime.UtcNow - System.Diagnostics.Process.GetCurrentProcess().StartTime.ToUniversalTime()
43 | );
44 | };
45 | return Task.Run(() => services.GetRequiredService());
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Core/Extensions/String.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Text.RegularExpressions;
6 |
7 | namespace Microsoft.Quantum.IQSharp
8 | {
9 | public static partial class Extensions
10 | {
11 | ///
12 | /// Removes common indents from each line in a string,
13 | /// similarly to Python's textwrap.dedent() function.
14 | ///
15 | public static string Dedent(this string text)
16 | {
17 | // First, start by finding the length of common indents,
18 | // disregarding lines that are only whitespace.
19 | var leadingWhitespaceRegex = new Regex(@"^[ \t]*");
20 | var minWhitespace = int.MaxValue;
21 | foreach (var line in text.Split("\n"))
22 | {
23 | if (!string.IsNullOrWhiteSpace(line))
24 | {
25 | var match = leadingWhitespaceRegex.Match(line);
26 | minWhitespace = match.Success
27 | ? System.Math.Min(minWhitespace, match.Value.Length)
28 | : minWhitespace = 0;
29 | }
30 | }
31 |
32 | // We can use that to build a new regex that strips
33 | // out common indenting.
34 | var leftTrimRegex = new Regex(@$"^[ \t]{{{minWhitespace}}}", RegexOptions.Multiline);
35 | return leftTrimRegex.Replace(text, "");
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Core/Extensions/Type.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 |
6 | namespace Microsoft.Quantum.IQSharp
7 | {
8 | ///
9 | /// Extensions for C# Types.
10 | ///
11 | public static partial class Extensions
12 | {
13 | private static Type WithoutTypeParameters(this Type type) =>
14 | type.IsGenericType ? type.GetGenericTypeDefinition() : type;
15 |
16 | internal static bool IsSubclassOfGenericType(this Type subType, Type baseType)
17 | {
18 | // Remove any type parameters of subType as applicable.
19 | subType = subType?.WithoutTypeParameters();
20 | if (subType == baseType)
21 | {
22 | return true;
23 | }
24 | else
25 | {
26 | // Check the next level up in inheritance from subtype, if it
27 | // exists.
28 | return subType?.BaseType?.IsSubclassOfGenericType(baseType) ?? false;
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/Core/Loggers/NugetLogger.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | #nullable enable
4 |
5 | using Microsoft.Extensions.Logging;
6 |
7 | namespace Microsoft.Quantum.IQSharp.Common
8 | {
9 | ///
10 | /// A simple class to keep track of Nuget logs.
11 | ///
12 | public class NuGetLogger : NuGet.Common.LoggerBase
13 | {
14 | private ILogger? _logger { get; set; }
15 | public List Logs { get; private set; }
16 |
17 | public NuGetLogger(ILogger? logger)
18 | {
19 | _logger = logger;
20 | this.Logs = new List();
21 | }
22 |
23 | public static LogLevel MapLevel(NuGet.Common.LogLevel original) =>
24 | original switch
25 | {
26 | NuGet.Common.LogLevel.Error => LogLevel.Error,
27 | NuGet.Common.LogLevel.Warning => LogLevel.Warning,
28 | NuGet.Common.LogLevel.Information => LogLevel.Information,
29 | NuGet.Common.LogLevel.Debug => LogLevel.Debug,
30 | _ => LogLevel.Trace
31 | };
32 |
33 | public override void Log(NuGet.Common.ILogMessage m)
34 | {
35 | _logger?.Log(MapLevel(m.Level), m.Message);
36 | Logs.Add(m);
37 | }
38 |
39 | public override Task LogAsync(NuGet.Common.ILogMessage m)
40 | {
41 | Log(m);
42 | return Task.CompletedTask;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Core/Metadata/ClientInformation.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp;
5 |
6 | ///
7 | /// Represents information that the kernel has about the client connected
8 | /// to IQ#.
9 | ///
10 | public record ClientInformation
11 | {
12 | ///
13 | /// A string passed by the client containing additional information
14 | /// that should be appended to the user agent (e.g.: packaging
15 | /// metadata).
16 | ///
17 | public string? UserAgentExtra { get; init; }
18 |
19 | ///
20 | /// A string passed by the client representing the name of the client.
21 | ///
22 | public string? UserAgent { get; init; }
23 |
24 | ///
25 | /// A string passed by the client representing the environment in which
26 | /// the client is running (e.g.: continuous integration, a hosted
27 | /// notebook service, etc.).
28 | ///
29 | public string? HostingEnvironment { get; init; }
30 |
31 | ///
32 | /// A string that is set to turn off the telemetry
33 | ///
34 | public string? TelemetryOptOut { get; init; }
35 |
36 | ///
37 | /// A boolean, based on the TelemetryOptOut string property
38 | ///
39 | public bool IsTelemetryOptOut => !string.IsNullOrEmpty(TelemetryOptOut);
40 | }
41 |
--------------------------------------------------------------------------------
/src/Core/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System.Runtime.CompilerServices;
5 |
6 | [assembly: InternalsVisibleTo("Tests.IQsharp" + SigningConstants.PUBLIC_KEY)]
7 | [assembly: InternalsVisibleTo("Microsoft.Quantum.IQSharp.Kernel" + SigningConstants.PUBLIC_KEY)]
--------------------------------------------------------------------------------
/src/Core/Properties/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | // This file is used by Code Analysis to maintain SuppressMessage
5 | // attributes that are applied to this project.
6 | // Project-level suppressions either have no target or are given
7 | // a specific target and scoped to a namespace, type, member, etc.
8 |
9 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "We're not following this convention")]
--------------------------------------------------------------------------------
/src/Core/Properties/KnownUris.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | ///
5 | /// URIs of well-known resources used across the IQ# project.
6 | ///
7 | public static class KnownUris
8 | {
9 | ///
10 | /// The URI for the reference documentation for IQ# magic commands.
11 | ///
12 | public const string MagicCommandReference = "https://docs.microsoft.com/qsharp/api/iqsharp-magic/";
13 |
14 | public static string ReferenceForMagicCommand(string commandName) =>
15 | MagicCommandReference + commandName;
16 | }
17 |
--------------------------------------------------------------------------------
/src/Core/References/INugetPackages.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | #nullable enable
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Collections.Immutable;
7 | using System.Threading.Tasks;
8 | using NuGet.Packaging.Core;
9 | using NuGet.Protocol.Core.Types;
10 | using NuGet.Versioning;
11 |
12 | namespace Microsoft.Quantum.IQSharp
13 | {
14 | ///
15 | /// This service provides the ability to download and keep track of Nuget Packages.
16 | ///
17 | public interface INugetPackages
18 | {
19 | ///
20 | /// List of Packages already installed.
21 | ///
22 | IEnumerable Items { get; }
23 |
24 | ///
25 | /// List of Assemblies from current Packages.
26 | ///
27 | IEnumerable Assemblies { get; }
28 |
29 | ///
30 | /// Keeps track of what package version to use for certain packages specified in appsettings.json.
31 | /// This way we can better control what the correct version of Microsoft.Quantum
32 | /// packages to use, since all of them should ideally be in-sync.
33 | ///
34 | IReadOnlyDictionary DefaultVersions { get; }
35 |
36 | SourceRepository GlobalPackagesSource { get; }
37 |
38 | ///
39 | /// Add a package.
40 | ///
41 | Task Add(string package, Action? statusCallback = null);
42 |
43 | Task> Get(PackageIdentity pkgId, Action? statusCallback = null);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Core/Resolver/IOperationResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using Microsoft.Quantum.IQSharp.Common;
8 |
9 | namespace Microsoft.Quantum.IQSharp
10 | {
11 | public interface IOperationResolver
12 | {
13 | OperationInfo Resolve(string input);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/Core/Snippets/Snippet.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.IO;
7 | using Microsoft.Quantum.QsCompiler.SyntaxTree;
8 |
9 | using Newtonsoft.Json;
10 | using Microsoft.VisualStudio.LanguageServer.Protocol;
11 |
12 | namespace Microsoft.Quantum.IQSharp;
13 |
14 | ///
15 | /// A Snippet represents a piece of Q# code provided by the user.
16 | /// These snippets are ephemeral thus not part of the environment.
17 | /// Each Snippet represents a single entry from the user.
18 | /// During execution, a user may provide multiple Snippets.
19 | ///
20 | public record Snippet
21 | {
22 | ///
23 | /// An id of the snippet. This gives users control on whether they are updating
24 | /// or creating a new Snippet.
25 | ///
26 | public string? Id { get; init; }
27 |
28 | ///
29 | /// The actual source code from the user.
30 | ///
31 | public string? Code { get; init; }
32 |
33 | ///
34 | /// Any compilation warnings trigger for this Snippet.
35 | ///
36 | public string[]? Warnings { get; init; }
37 |
38 | [Obsolete("Please use Snippet.Warnings.")]
39 | public string[]? warnings => Warnings;
40 |
41 | public IEnumerable? Diagnostics { get; init; }
42 |
43 | ///
44 | /// The Q# compiled version of the operations.
45 | ///
46 | [JsonIgnore]
47 | public QsNamespaceElement[]? Elements { get; set; }
48 |
49 | [JsonIgnore]
50 | internal string? FileName => Path.GetFullPath(Path.Combine("/", $"snippet_{Id}.qs"));
51 |
52 | ///
53 | /// The compiler needs an actual URI for each piece of Q# code
54 | /// that it is going to compile.
55 | ///
56 | [JsonIgnore]
57 | public Uri Uri => new Uri(FileName);
58 | }
59 |
--------------------------------------------------------------------------------
/src/Core/Telemetry/ITelemetryService.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp
5 | {
6 | ///
7 | /// Telemetry service
8 | ///
9 | public interface ITelemetryService
10 | {
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/Core/Telemetry/NullTelemetryService.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.Extensions.Logging;
5 |
6 | namespace Microsoft.Quantum.IQSharp
7 | {
8 | ///
9 | /// Null telemetry service that does not do anything (does not log or send any data).
10 | /// This is used when telemetry is opted-out.
11 | ///
12 | public class NullTelemetryService: ITelemetryService
13 | {
14 | public NullTelemetryService(
15 | ILogger logger
16 | )
17 | {
18 | logger.LogInformation("--> IQ# Telemetry opted-out. No telemetry data will be generated or sent.");
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/ExecutionPathTracer/ExecutionPathTracer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | x64
6 | Microsoft.Quantum.IQSharp.ExecutionPathTracer
7 | Microsoft.Quantum.IQSharp.ExecutionPathTracer
8 | true
9 |
10 |
11 |
12 | 0162
13 | Microsoft
14 | Microsoft Quantum's Execution Path Tracer.
15 | © Microsoft Corporation. All rights reserved.
16 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes
17 | MIT
18 | https://github.com/Microsoft/IQsharp/tree/main/src/ExecutionPathTracer
19 | qdk-nuget-icon.png
20 | Quantum Q# Qsharp
21 | Microsoft.Quantum.IQSharp.ExecutionPathTracer
22 | \
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/src/ExecutionPathTracer/Extensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.Collections.Generic;
7 | using Microsoft.Quantum.Simulation.Common;
8 |
9 | namespace Microsoft.Quantum.IQSharp.ExecutionPathTracer
10 | {
11 | ///
12 | /// Extension methods to be used with and by .
13 | ///
14 | public static class Extensions
15 | {
16 | ///
17 | /// Attaches event listeners to the simulator to generate
18 | /// the of the operation performed by the simulator.
19 | ///
20 | public static T WithExecutionPathTracer(this T sim, ExecutionPathTracer tracer)
21 | where T : SimulatorBase
22 | {
23 | sim.OnOperationStart += tracer.OnOperationStartHandler;
24 | sim.OnOperationEnd += tracer.OnOperationEndHandler;
25 | return sim;
26 | }
27 |
28 | ///
29 | /// Gets the value associated with the specified key and creates a new entry with the defaultVal if
30 | /// the key doesn't exist.
31 | ///
32 | public static TValue GetOrCreate(this IDictionary dict, TKey key, TValue defaultVal)
33 | {
34 | TValue val;
35 | if (!dict.TryGetValue(key, out val))
36 | {
37 | val = defaultVal;
38 | dict.Add(key, val);
39 | }
40 | return val;
41 | }
42 |
43 | ///
44 | /// Gets the value associated with the specified key and creates a new entry of the default type if
45 | /// the key doesn't exist.
46 | ///
47 | public static TValue GetOrCreate(this IDictionary dict, TKey key)
48 | where TValue : new() => dict.GetOrCreate(key, new TValue());
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/Jupyter/ChannelWriter.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System.Text;
5 |
6 | #nullable enable
7 |
8 | namespace Microsoft.Quantum.IQSharp
9 | {
10 | ///
11 | /// A simpler wrapper to be able to use ChannelWriter as a TextWriter.
12 | ///
13 | public class ChannelWriter : System.IO.TextWriter
14 | {
15 | private IChannel? Channel { get; }
16 |
17 | ///
18 | /// The default constructor.
19 | ///
20 | /// The channel to write output to.
21 | public ChannelWriter(IChannel? channel)
22 | {
23 | Channel = channel;
24 | }
25 |
26 | ///
27 | public override Encoding Encoding => Encoding.UTF8;
28 |
29 | ///
30 | public override void Write(string message) =>
31 | Channel?.Stdout(message);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/Jupyter/Compat.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace System.Runtime.CompilerServices;
5 | /// Allows using init-only properties in netstandard2.1 project. Note that
6 | /// init-only is only enforced for net5.0 and later callers.
7 | public class IsExternalInit {}
8 |
--------------------------------------------------------------------------------
/src/Jupyter/CompilationErrorStyle.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.IQSharp.Jupyter;
5 |
6 | ///
7 | /// Configuration values for controlling how compilation errors are
8 | /// reported to clients.
9 | ///
10 | public enum CompilationErrorStyle
11 | {
12 | ///
13 | /// Specifies that diagnostics should be formatted as basic strings,
14 | /// similar to MSBuild output logs.
15 | ///
16 | Basic,
17 |
18 | ///
19 | /// Specifies that diagnostics should be formatted with annotated
20 | /// source and additional links to documentation where appropriate.
21 | ///
22 | ///
23 | Fancy
24 | }
25 |
--------------------------------------------------------------------------------
/src/Jupyter/Jupyter.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | x64
6 | Microsoft.Quantum.IQSharp.Jupyter
7 | Microsoft.Quantum.IQSharp.Jupyter
8 | true
9 | 10.0
10 |
11 |
12 |
13 | 0162
14 | Microsoft
15 | Microsoft's IQ# Library with Jupyter Extensions.
16 | © Microsoft Corporation. All rights reserved.
17 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes
18 | MIT
19 | https://github.com/Microsoft/IQSharp
20 | qdk-nuget-icon.png
21 | Quantum Q# Qsharp
22 | Microsoft.Quantum.IQSharp.Jupyter
23 | \
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/src/Jupyter/Magic/ExperimentalBuildInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Microsoft.Quantum.IQSharp;
7 | using Microsoft.Quantum.IQSharp.Jupyter;
8 | using Microsoft.Quantum.Simulation.Simulators;
9 | namespace Microsoft.Quantum.Experimental;
10 |
11 | public class ExperimentalBuildInfoMagic : AbstractMagic
12 | {
13 |
14 | public ExperimentalBuildInfoMagic() : base(
15 | "experimental.build_info",
16 | new Microsoft.Jupyter.Core.Documentation
17 | {
18 | Summary = "Reports build info for the experimental simulators.",
19 | Description = @"
20 | > **⚠ WARNING:** This magic command is **experimental**,
21 | > is not supported, and may be removed from future versions without notice.
22 | ".Dedent(),
23 | Examples = new string[]
24 | {
25 | @"
26 | Return the build info for experimental simulators:
27 | ```
28 | In []: %experimental.build_info
29 | ```
30 | ".Dedent(),
31 | }
32 | })
33 | { }
34 |
35 | ///
36 | public override ExecutionResult Run(string input, IChannel channel)
37 | {
38 | return OpenSystemsSimulator.BuildInfo.ToExecutionResult();
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/Jupyter/Magic/Resolution/IMagicResolver.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using Microsoft.Extensions.Configuration;
10 | using Microsoft.Extensions.DependencyInjection;
11 | using Microsoft.Extensions.Logging;
12 | using Microsoft.Jupyter.Core;
13 | using Microsoft.Quantum.IQSharp.Common;
14 |
15 | using Newtonsoft.Json;
16 |
17 | namespace Microsoft.Quantum.IQSharp.Jupyter
18 | {
19 | ///
20 | /// Subinterface of
21 | /// with additional functionality for discovering magic symbols.
22 | ///
23 | public interface IMagicSymbolResolver : ISymbolResolver
24 | {
25 | ISymbol? ISymbolResolver.Resolve(string symbolName) =>
26 | this.Resolve(symbolName);
27 |
28 | ///
29 | /// Returns the corresponding to the given symbol name,
30 | /// searching all loaded assemblies for classes derived from .
31 | ///
32 | /// The magic symbol name to resolve.
33 | /// The resolved object, or null if none was found.
34 | public new MagicSymbol? Resolve(string symbolName);
35 |
36 | ///
37 | /// Given a type representing an assembly, adds that assembly to the
38 | /// list of assemblies to be searched for built-in magic commands.
39 | ///
40 | public IMagicSymbolResolver AddKernelAssembly();
41 |
42 | ///
43 | /// Returns the list of all objects defined in loaded assemblies.
44 | ///
45 | public IEnumerable FindAllMagicSymbols();
46 |
47 | ///
48 | /// Finds the MagicSymbols inside an assembly, and returns an instance of each.
49 | ///
50 | public IEnumerable FindMagic(AssemblyInfo assm);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Jupyter/Magic/WhoMagic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System.Linq;
5 | using Microsoft.Extensions.Logging;
6 | using Microsoft.Jupyter.Core;
7 | using Microsoft.Quantum.IQSharp;
8 |
9 | namespace Microsoft.Quantum.IQSharp.Jupyter
10 | {
11 | ///
12 | /// A magic command that can be used to query the functions and operations
13 | /// defined within an IQ# session.
14 | ///
15 | public class WhoMagic : AbstractMagic
16 | {
17 | ///
18 | /// Given a given snippets collection, constructs a new magic command
19 | /// that queries callables defined in that snippets collection.
20 | ///
21 | public WhoMagic(ISnippets snippets, ILogger logger) : base(
22 | "who",
23 | new Microsoft.Jupyter.Core.Documentation
24 | {
25 | Summary = "Lists the Q# operations available in the current session.",
26 | Description = @"
27 | This magic command returns a list of Q# operations and functions that are available
28 | in the current IQ# session for use with magic commands such as `%simulate`
29 | and `%estimate`.
30 |
31 | The list will include Q# operations and functions which have been defined interactively
32 | within cells in the current notebook (after the cells have been executed),
33 | as well as any Q# operations and functions defined within .qs files in the current folder.
34 | ".Dedent(),
35 | Examples = new []
36 | {
37 | @"
38 | Display the list of Q# operations and functions available in the current session:
39 | ```
40 | In []: %who
41 | Out[]:
42 | ```
43 | ".Dedent(),
44 | }
45 | }, logger)
46 | {
47 | this.Snippets = snippets;
48 | }
49 |
50 | ///
51 | /// The snippets collection queried by this magic command.
52 | ///
53 | public ISnippets Snippets { get; }
54 |
55 | ///
56 | public override ExecutionResult Run(string input, IChannel channel) =>
57 | Snippets.Operations
58 | .Select(op => op.FullName)
59 | .OrderBy(name => name)
60 | .ToArray()
61 | .ToExecutionResult();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/Jupyter/NoiseModelSource/INoiseModelSource.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 | using Microsoft.Quantum.Simulation.OpenSystems.DataModel;
6 |
7 | namespace Microsoft.Quantum.IQSharp.Jupyter;
8 |
9 | ///
10 | /// A dependency injection service that stores a noise model for use in
11 | /// open systems simulation.
12 | ///
13 | public interface INoiseModelSource
14 | {
15 | ///
16 | /// The current noise model in effect for open systems simulation.
17 | ///
18 | NoiseModel NoiseModel { get; set; }
19 | }
20 |
--------------------------------------------------------------------------------
/src/Jupyter/NoiseModelSource/NoiseModelSource.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 | using Microsoft.Quantum.Simulation.OpenSystems.DataModel;
6 |
7 | namespace Microsoft.Quantum.IQSharp.Jupyter;
8 |
9 | ///
10 | public record NoiseModelSource : INoiseModelSource
11 | {
12 | ///
13 | public NoiseModel NoiseModel { get; set; } =
14 | NoiseModel.TryGetByName("ideal", out var ideal)
15 | ? ideal
16 | : throw new Exception("Could not load ideal noise model.");
17 | }
18 |
--------------------------------------------------------------------------------
/src/Jupyter/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System.Runtime.CompilerServices;
5 |
6 | #pragma warning disable CS0436 // Type conflicts with imported type
7 | [assembly: InternalsVisibleTo("Tests.IQsharp" + SigningConstants.PUBLIC_KEY)]
8 | #pragma warning restore CS0436 // Type conflicts with imported type
9 |
--------------------------------------------------------------------------------
/src/Jupyter/Properties/GlobalUsings.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | global using Microsoft.Jupyter.Core;
5 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/DebugContent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | #nullable enable
4 |
5 | using System.Collections.Generic;
6 | using System.Numerics;
7 | using Microsoft.Jupyter.Core;
8 | using Microsoft.Jupyter.Core.Protocol;
9 | using Newtonsoft.Json;
10 |
11 | namespace Microsoft.Quantum.IQSharp.Jupyter
12 | {
13 | ///
14 | /// Contains information for rendering the status of a client debugging session.
15 | ///
16 | public class DebugStatusContent : MeasurementHistogramContent
17 | {
18 | ///
19 | /// Contains the identifier of the client debugging session.
20 | ///
21 | [JsonProperty("debug_session")]
22 | public string DebugSession { get; set; } = string.Empty;
23 | }
24 |
25 | ///
26 | /// Contains information for rendering the content of a client debugging session.
27 | ///
28 | public class DebugSessionContent : MessageContent
29 | {
30 | ///
31 | /// Contains the identifier of the client debugging session.
32 | ///
33 | [JsonProperty("debug_session")]
34 | public string DebugSession { get; set; } = string.Empty;
35 |
36 | ///
37 | /// Contains the identifier of the HTML element for the client to render
38 | /// the debugging information.
39 | ///
40 | [JsonProperty("div_id")]
41 | public string DivId { get; set; } = string.Empty;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/DisplayableHtmlElementEncoder.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | namespace Microsoft.Quantum.IQSharp.Jupyter;
7 |
8 | ///
9 | /// Represents an HTML string to be rendered as an HTML element.
10 | ///
11 | ///
12 | /// HTML string to be rendered.
13 | ///
14 | public record DisplayableHtmlElement(
15 | string Html
16 | );
17 |
18 | ///
19 | /// Encodes instances as HTML elements.
20 | ///
21 | public class DisplayableHtmlElementEncoder : IResultEncoder
22 | {
23 | ///
24 | public string MimeType => MimeTypes.Html;
25 |
26 | ///
27 | /// Checks if a given display object is an ,
28 | /// and if so, returns its HTML element.
29 | ///
30 | public EncodedData? Encode(object displayable) =>
31 | (displayable is DisplayableHtmlElement dis)
32 | ? dis.Html.ToEncodedData() as EncodedData?
33 | : null;
34 | }
35 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/IDisplayable.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using System.Diagnostics.CodeAnalysis;
7 |
8 | namespace Microsoft.Quantum.IQSharp.Jupyter;
9 |
10 | public interface IDisplayable
11 | {
12 | public bool TryAsDisplayData(string mimeType, [NotNullWhen(true)] out EncodedData? displayData);
13 | }
14 |
15 | public record DisplayableEncoder(string MimeType) : IResultEncoder
16 | {
17 | public EncodedData? Encode(object obj)
18 | {
19 | if (obj is IDisplayable displayable && displayable.TryAsDisplayData(MimeType, out var encoded))
20 | {
21 | return encoded;
22 | }
23 | return null;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/LsMagicEncoders.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 | #nullable enable
4 |
5 |
6 | namespace Microsoft.Quantum.IQSharp.Jupyter
7 | {
8 | internal static class TableExtensions
9 | {
10 | internal static Table AsJupyterTable(
11 | this IEnumerable magicSymbols
12 | ) =>
13 | new Table
14 | {
15 | Columns = new List<(string, Func)>
16 | {
17 | ("Name", symbol => symbol.Name),
18 | ("Summary", symbol => symbol.Documentation.Summary),
19 | ("Assembly", symbol => symbol.AssemblyName)
20 | },
21 | Rows = magicSymbols.ToList()
22 | };
23 | }
24 |
25 | ///
26 | /// Encodes results from the %lsmagic magic command as an HTML
27 | /// table.
28 | ///
29 | public class MagicSymbolSummariesToHtmlEncoder : IResultEncoder
30 | {
31 | private static readonly IResultEncoder tableEncoder = new TableToHtmlDisplayEncoder();
32 |
33 | ///
34 | public string MimeType => MimeTypes.Html;
35 |
36 | ///
37 | /// Checks if a displayable object represents a list of magic symbol
38 | /// summaries, and if so, returns an encoding into an HTML table.
39 | ///
40 | public EncodedData? Encode(object displayable) =>
41 | displayable is IEnumerable summaries
42 | ? tableEncoder.Encode(summaries.AsJupyterTable())
43 | : null;
44 | }
45 |
46 | ///
47 | /// Encodes instances as plain-text
48 | /// tables.
49 | ///
50 | public class MagicSymbolSummariesToTextEncoder : IResultEncoder
51 | {
52 | private static readonly IResultEncoder tableEncoder = new TableToTextDisplayEncoder();
53 |
54 | ///
55 | public string MimeType => MimeTypes.PlainText;
56 |
57 | ///
58 | /// Checks if a displayable object represents a list of magic symbol
59 | /// summaries, and if so, returns an encoding into a plain-text table.
60 | ///
61 | public EncodedData? Encode(object displayable) =>
62 | displayable is IEnumerable summaries
63 | ? tableEncoder.Encode(summaries.AsJupyterTable())
64 | : null;
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/MeasurementHistogramContent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Microsoft.Jupyter.Core.Protocol;
7 | using Microsoft.Quantum.Simulation.Simulators;
8 | using Newtonsoft.Json;
9 |
10 | namespace Microsoft.Quantum.IQSharp.Jupyter
11 | {
12 | ///
13 | /// Contains information for rendering a histogram on the client.
14 | ///
15 | public class MeasurementHistogramContent : MessageContent
16 | {
17 | ///
18 | /// Information about the state to be displayed.
19 | ///
20 | [JsonProperty("state")]
21 | public CommonNativeSimulator.DisplayableState State { get; set; } = new CommonNativeSimulator.DisplayableState();
22 |
23 | ///
24 | /// Unique identifier of the instance.
25 | ///
26 | [JsonProperty("id")]
27 | public string Id { get; set; } = $"{System.Guid.NewGuid()}";
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/PerformanceReportEncoders.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 | #nullable enable
4 |
5 | using System;
6 | using System.Collections;
7 | using System.Collections.Generic;
8 | using System.Collections.Immutable;
9 | using System.Data;
10 | using System.Linq;
11 | using Microsoft.Jupyter.Core;
12 | using Microsoft.Quantum.QsCompiler.Diagnostics;
13 | using Microsoft.Quantum.Simulation.Simulators;
14 |
15 | namespace Microsoft.Quantum.IQSharp.Jupyter
16 | {
17 | public class ForwardedCompilerPerformanceEvent
18 | {
19 | public CompilationTaskEventType Type { get; }
20 | public string? Parent { get; } = null;
21 | public string Task { get; }
22 | private TimeSpan TimeSinceCellStart { get; }
23 |
24 | public ForwardedCompilerPerformanceEvent(CompilationTaskEventType type, string? parent, string task, TimeSpan timeSinceCellStart)
25 | {
26 | Type = type;
27 | Parent = parent;
28 | Task = task;
29 | TimeSinceCellStart = timeSinceCellStart;
30 | }
31 |
32 | public override string ToString() =>
33 | $"[T+{TimeSinceCellStart.TotalMilliseconds}ms] Q# compiler: {Type} {(Parent == null ? "" : $"{Parent} / ")}{Task}";
34 |
35 | }
36 |
37 | public class TaskProgressToHtmlEncoder : IResultEncoder
38 | {
39 | ///
40 | public string MimeType => MimeTypes.Html;
41 |
42 | private EncodedData Wrap(string plainText, int depth) =>
43 | $"{plainText}
".ToEncodedData();
44 |
45 | ///
46 | /// Checks if a displayable object represents a list of magic symbol
47 | /// summaries, and if so, returns an encoding into an HTML table.
48 | ///
49 | public EncodedData? Encode(object displayable) =>
50 | displayable switch
51 | {
52 | TaskPerformanceArgs perfArgs =>
53 | Wrap(perfArgs.ToString(), perfArgs.Task.Depth),
54 | TaskCompleteArgs completeArgs =>
55 | Wrap(completeArgs.ToString(), completeArgs.Task.Depth),
56 | ForwardedCompilerPerformanceEvent fwdEvent =>
57 | Wrap(fwdEvent.ToString(), 0),
58 | _ => (EncodedData?)null
59 | };
60 | }
61 |
62 | // NB: plain text should be handled by just the ToString output.
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/Jupyter/Visualization/TraceVisualization.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using Newtonsoft.Json;
5 | using Newtonsoft.Json.Converters;
6 |
7 | namespace Microsoft.Quantum.IQSharp.Jupyter
8 | {
9 | ///
10 | /// Represents different styles for displaying the Q# execution path
11 | /// visualization as HTML.
12 | ///
13 | [JsonConverter(typeof(StringEnumConverter))]
14 | public enum TraceVisualizationStyle
15 | {
16 | ///
17 | /// Default style with coloured gates.
18 | ///
19 | Default,
20 | ///
21 | /// Black and white style.
22 | ///
23 | BlackAndWhite,
24 | ///
25 | /// Inverted black and white style (for black backgrounds).
26 | ///
27 | Inverted
28 | }
29 | }
--------------------------------------------------------------------------------
/src/Kernel/Compat.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace System.Runtime.CompilerServices;
5 | /// Allows using init-only properties in netstandard2.1 project. Note that
6 | /// init-only is only enforced for net5.0 and later callers.
7 | public class IsExternalInit {}
8 |
--------------------------------------------------------------------------------
/src/Kernel/ExperimentalFeatures.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.Jupyter.Core.Protocol;
5 | using Newtonsoft.Json;
6 |
7 | namespace Microsoft.Quantum.IQSharp.Kernel
8 | {
9 |
10 | ///
11 | /// Message content to be received when a client asks for an
12 | /// experimental feature to be turned on.
13 | ///
14 | public class ExperimentalFeatureContent : MessageContent
15 | {
16 | ///
17 | /// The name of the experimental feature to be enabled.
18 | ///
19 | [JsonProperty("feature_name")]
20 | public string? FeatureName { get; set; }
21 |
22 | ///
23 | /// The names and versions of any optional packages used with the
24 | /// requested experimental feature.
25 | ///
26 | [JsonProperty("optional_dependencies")]
27 | public List? OptionalDependencies { get; set; }
28 | }
29 |
30 | ///
31 | /// Event type for when a Python client enables an experimental
32 | /// feature.
33 | ///
34 | public record ExperimentalFeatureEnabledEvent : Event;
35 |
36 | ///
37 | /// Shell handler that allows for firing off events when a Python
38 | /// client enables an experimental feature via
39 | /// qsharp.experimental.
40 | ///
41 | internal class ExperimentalFeaturesShellHandler : IShellHandler
42 | {
43 | public string MessageType => "iqsharp_python_enable_experimental";
44 | private readonly IEventService events;
45 |
46 | public ExperimentalFeaturesShellHandler(IEventService events)
47 | {
48 | this.events = events;
49 | }
50 |
51 | public Task HandleAsync(Message message)
52 | {
53 | var content = message.To();
54 | events?.Trigger(content);
55 | return Task.CompletedTask;
56 | }
57 | }
58 |
59 | }
--------------------------------------------------------------------------------
/src/Kernel/Kernel.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | x64
6 | Microsoft.Quantum.IQSharp.Kernel
7 | Microsoft.Quantum.IQSharp.Kernel
8 | true
9 | enable
10 | 10.0
11 | true
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | Never
40 |
41 |
42 | all
43 | runtime; build; native; contentfiles; analyzers
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/Kernel/KernelProperties.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System.Reflection;
5 | using Microsoft.Jupyter.Core;
6 |
7 | namespace Microsoft.Quantum.IQSharp.Kernel
8 | {
9 | ///
10 | /// These are the list of properties for the Q# Jupyter Kernel.
11 | ///
12 | public static class Constants
13 | {
14 | ///
15 | /// The properties for this kernel (e.g. versions, language name,
16 | /// etc.).
17 | ///
18 | public static readonly KernelProperties IQSharpKernelProperties = new KernelProperties
19 | {
20 | FriendlyName = "Q#",
21 | KernelName = "iqsharp",
22 | KernelVersion =
23 | typeof(IQSharpEngine).Assembly.GetCustomAttribute()?.InformationalVersion
24 | ?? typeof(IQSharpEngine).Assembly.GetName().Version.ToString(),
25 | DisplayName = "Q#",
26 |
27 | LanguageName = "qsharp",
28 | LanguageVersion = "0.27",
29 | LanguageMimeType = "text/x-qsharp",
30 | LanguageFileExtension = ".qs",
31 |
32 | Description = "A kernel for the Q# language."
33 | };
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/Kernel/Magic/AttachMagic.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 |
6 | using Microsoft.Extensions.Logging;
7 | using Microsoft.Jupyter.Core;
8 | using Microsoft.Quantum.IQSharp.Jupyter;
9 |
10 | #if DEBUG
11 |
12 | namespace Microsoft.Quantum.IQSharp.Kernel
13 | {
14 | ///
15 | /// Magic command to attach a debugger to the current IQ# session.
16 | ///
17 | public class AttachMagic : AbstractMagic
18 | {
19 | ///
20 | /// Creates an instance of the magic command using the given
21 | /// dependencies.
22 | ///
23 | public AttachMagic(ILogger logger) : base(
24 | "attach",
25 | new Microsoft.Jupyter.Core.Documentation
26 | {
27 | Summary = "Attaches a debugger to the current IQ# session.",
28 | Description = @"
29 | If no debugger is attached to the current IQ# session, launches a new debugger and attaches it, allowing for stepping through IQ# implementation code.
30 |
31 | If a debugger is already attached, this magic command acts as a breakpoint when executed.
32 |
33 | > **NOTE:** This command is not included in release versions of the IQ# kernel, and is only intended for use by IQ# contributors.
34 | > If you are interested in debugging Q# code written in IQ#, please see the [`%debug` magic command](https://docs.microsoft.com/qsharp/api/iqsharp-magic/debug) instead.
35 | ".Dedent(),
36 | Examples = new string []
37 | {
38 | @"
39 | Attach a debugger to the current IQ# session:
40 | ```
41 | %attach
42 | ```
43 | ".Dedent()
44 | }
45 | }, logger)
46 | { }
47 |
48 |
49 | ///
50 | public override ExecutionResult Run(string? input, IChannel channel)
51 | {
52 | if (System.Diagnostics.Debugger.IsAttached)
53 | {
54 | System.Diagnostics.Debugger.Break();
55 | }
56 | else
57 | {
58 | System.Diagnostics.Debugger.Launch();
59 | }
60 |
61 | return ExecuteStatus.Ok.ToExecutionResult();
62 | }
63 | }
64 | }
65 |
66 | #endif
67 |
--------------------------------------------------------------------------------
/src/Kernel/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using System.Runtime.CompilerServices;
5 |
6 | #pragma warning disable CS0436 // Type conflicts with imported type
7 | [assembly: InternalsVisibleTo("Tests.IQsharp" + SigningConstants.PUBLIC_KEY)]
8 | #pragma warning restore CS0436 // Type conflicts with imported type
9 |
--------------------------------------------------------------------------------
/src/Kernel/Properties/GlobalUsings.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | global using System;
5 | global using System.Collections.Generic;
6 | global using System.Threading.Tasks;
7 | global using Microsoft.Jupyter.Core;
8 | global using Microsoft.Quantum.IQSharp.Jupyter;
9 | global using System.Linq;
10 |
--------------------------------------------------------------------------------
/src/Kernel/client/ipython.d.ts:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | // This file provides TypeScript type declarations for the window.IPython
5 | // object used for extensibility in Jupyter Notebook.
6 |
7 | export interface IPython {
8 | notebook: Notebook;
9 | }
10 |
11 | export interface Notebook {
12 | kernel: Kernel;
13 | }
14 |
15 | export type ShellCallbacks = {
16 | shell?: {
17 | reply?: (message: Message) => void,
18 | payload?: {[payload_name: string]: (message: Message) => void}
19 | },
20 | iopub?: {
21 | output?: (message: Message) => void,
22 | clear_output?: (message: Message) => void
23 | },
24 | input?: (message: Message) => void,
25 | clear_on_done?: boolean,
26 | shell_done?: (message: Message) => void,
27 | iopub_done?: (message: Message) => void
28 | }
29 | export interface Events {
30 | on(event: string, callback: (any) => void);
31 | }
32 |
33 | export interface CommSession {
34 | send(data: any): string;
35 | on_msg(callback: (message: Message<{ comm_id: string, data: any }>) => void): void;
36 | on_close(callback: (message: any) => void): void;
37 | close(data?: any): void;
38 | }
39 |
40 | export interface MessageHeader {
41 | date: string;
42 | msg_id: string;
43 | msg_type: string;
44 | session: string;
45 | username: string;
46 | version: string;
47 | }
48 |
49 | export interface Message {
50 | buffers: any[];
51 | channel: "iopub" | "shell";
52 | content: TContents;
53 | header: MessageHeader;
54 | metdata: any;
55 | msg_id: string;
56 | msg_type: string;
57 | parent_header: MessageHeader;
58 | }
59 |
60 | export type CommMessage = Message<{
61 | comm_id: string,
62 | data: TData,
63 | target_name: string
64 | }>;
65 |
66 | export interface CommManager {
67 | new_comm(target_name: string, data?: any): CommSession;
68 | register_target(target_name, callback: (comm: CommSession, msg: CommMessage) => void): void;
69 | }
70 |
71 | export interface Kernel {
72 | events: Events;
73 |
74 | is_connected: () => Boolean;
75 | execute(code: string, callbacks: ShellCallbacks | undefined, options: {silent?: boolean, user_expressions?: object, allow_stdin?: boolean} | undefined): string;
76 | register_iopub_handler(msg_type: string, callback: (message: Message) => void);
77 | send_shell_message(msg_type: string, content: object, callbacks?: ShellCallbacks, metadata?: object, buffers?: Array) : string;
78 | comm_manager: CommManager;
79 | }
80 |
--------------------------------------------------------------------------------
/src/Kernel/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "@microsoft/quantum-viz.js": "^1.0.2",
4 | "chart.js": "2.9.4",
5 | "lodash": "^4.17.21"
6 | },
7 | "devDependencies": {
8 | "@types/chart.js": "2.8.0",
9 | "@types/codemirror": "0.0.56",
10 | "canvas": "^2.8.0",
11 | "typescript": "^3.9.6",
12 | "tar": "^6.1.9"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Kernel/res/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore generated files.
2 | bundle.js
3 |
--------------------------------------------------------------------------------
/src/Kernel/res/kernel.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | requirejs.config({
4 | bundles: {
5 | 'bundle': ['kernel'],
6 | 'chart': ['chart.js'],
7 | 'quantum-viz': ['@microsoft/quantum-viz.js'],
8 | },
9 | paths: {
10 | 'bundle': window.IPython.notebook.base_url + 'kernelspecs/iqsharp/bundle',
11 | 'chart': window.IPython.notebook.base_url + 'kernelspecs/iqsharp/chart',
12 | 'quantum-viz': window.IPython.notebook.base_url + 'kernelspecs/iqsharp/quantum-viz',
13 | },
14 | });
15 |
16 | define(["exports", "kernel"], function (exports, kernel) {
17 | Object.defineProperty(exports, "onload", { enumerable: true, get: function () { return kernel.onload; } });
18 | });
19 |
--------------------------------------------------------------------------------
/src/Kernel/res/logo-64x64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/src/Kernel/res/logo-64x64.png
--------------------------------------------------------------------------------
/src/Kernel/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "noImplicitAny": false,
4 | "noEmitOnError": true,
5 | "removeComments": true,
6 | "sourceMap": false,
7 | "target": "ES5",
8 | "baseUrl": ".",
9 | "outDir": "res",
10 | "outFile": "res/bundle.js",
11 | "lib": [ "DOM", "ES2019" ],
12 | "module": "AMD",
13 | "moduleResolution": "node"
14 | },
15 | "exclude": ["node_modules", "wwwroot", "client/__tests__"],
16 | "include": ["client/**/*"]
17 | }
18 |
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Chemistry/Library.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | //
5 | // These are mock classes that resemble the data structures defined in the chemistry library
6 | //
7 | namespace Mock.Chemistry {
8 | open Microsoft.Quantum.Intrinsic;
9 | open Microsoft.Quantum.Canon;
10 |
11 | /// # Summary
12 | /// Format of data passed from C# to Q# to represent a term of the Hamiltonian.
13 | /// The meaning of the data represented is determined by the algorithm that receives it.
14 | newtype HTerm = (Int[], Double[]);
15 |
16 | /// # Summary
17 | /// Format of data passed from C# to Q# to represent terms of the Hamiltonian.
18 | /// The meaning of the data represented is determined by the algorithm that receives it.
19 | newtype JWOptimizedHTerms = (HTerm[], HTerm[], HTerm[], HTerm[]);
20 |
21 | /// # Summary
22 | /// Format of data passed from C# to Q# to represent preparation of the initial state
23 | /// The meaning of the data represented is determined by the algorithm that receives it.
24 | newtype JordanWignerInputState = ((Double, Double), Int[]);
25 |
26 | /// # Summary
27 | /// Format of data passed from C# to Q# to represent all information for Hamiltonian simulation.
28 | /// The meaning of the data represented is determined by the algorithm that receives it.
29 | newtype JordanWignerEncodingData = (Int, JWOptimizedHTerms, (Int, JordanWignerInputState[]), Double);
30 | }
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Chemistry/Mock.Chemistry.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Standard/Arrays.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.Quantum.Simulation.Core;
5 | using System;
6 |
7 | namespace Mock.Standard
8 | {
9 | public partial class ForEach<__T__, __U__>
10 | {
11 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args)
12 | {
13 | var metadata = base.GetRuntimeMetadata(args);
14 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}.");
15 | metadata.IsComposite = true;
16 | return metadata;
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Standard/Arrays.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | //
5 | // These are mock classes that resemble the data structures defined in the Microsoft.Quantum.Arrays library
6 | //
7 | namespace Mock.Standard {
8 | open Microsoft.Quantum.Arrays;
9 |
10 | /// # Summary
11 | /// Given an array and an operation that is defined
12 | /// for the elements of the array, returns a new array that consists
13 | /// of the images of the original array under the operation.
14 | ///
15 | /// # Remarks
16 | /// The operation is defined for generic types, i.e., whenever we have
17 | /// an array `'T[]` and an operation `action : 'T -> 'U` we can map the elements
18 | /// of the array and produce a new array of type `'U[]`.
19 | ///
20 | /// # Type Parameters
21 | /// ## 'T
22 | /// The type of `array` elements.
23 | /// ## 'U
24 | /// The result type of the `action` operation.
25 | ///
26 | /// # Input
27 | /// ## action
28 | /// An operation from `'T` to `'U` that is applied to each element.
29 | /// ## array
30 | /// An array of elements over `'T`.
31 | ///
32 | /// # Output
33 | /// An array `'U[]` of elements that are mapped by the `action` operation.
34 | operation ForEach<'T, 'U> (action : ('T => 'U), array : 'T[]) : 'U[] {
35 | mutable resultArray = new 'U[Length(array)];
36 |
37 | for idxElement in IndexRange(array) {
38 | set resultArray w/= idxElement <- action(array[idxElement]);
39 | }
40 |
41 | return resultArray;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Standard/Canon.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.Quantum.Simulation.Core;
5 | using System;
6 |
7 | namespace Mock.Standard
8 | {
9 | public partial class ApplyToEach<__T__>
10 | {
11 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args)
12 | {
13 | var metadata = base.GetRuntimeMetadata(args);
14 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}.");
15 | metadata.IsComposite = true;
16 | return metadata;
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Standard/Canon.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | //
5 | // These are mock classes that resemble the data structures defined in the Microsoft.Quantum.Canon library
6 | //
7 | namespace Mock.Standard {
8 | open Microsoft.Quantum.Arrays;
9 |
10 | /// # Summary
11 | /// Applies a single-qubit operation to each element in a register.
12 | ///
13 | /// # Input
14 | /// ## singleElementOperation
15 | /// Operation to apply to each qubit.
16 | /// ## register
17 | /// Array of qubits on which to apply the given operation.
18 | ///
19 | /// # Type Parameters
20 | /// ## 'T
21 | /// The target on which the operation acts.
22 | ///
23 | /// # Remarks
24 | /// ## Example
25 | /// Prepare a three-qubit $\ket{+}$ state:
26 | /// ```qsharp
27 | /// using (register = Qubit[3]) {
28 | /// ApplyToEach(H, register);
29 | /// }
30 | /// ```
31 | ///
32 | /// # See Also
33 | /// - Microsoft.Quantum.Canon.ApplyToEachC
34 | /// - Microsoft.Quantum.Canon.ApplyToEachA
35 | /// - Microsoft.Quantum.Canon.ApplyToEachCA
36 | operation ApplyToEach<'T> (singleElementOperation : ('T => Unit), register : 'T[]) : Unit
37 | {
38 | for idxQubit in IndexRange(register) {
39 | singleElementOperation(register[idxQubit]);
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/MockLibraries/Mock.Standard/Mock.Standard.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore autogenerated Python modules.
2 | qsharp/version.py
3 |
4 | # Python packaging artifacts
5 | *.egg-info/
6 | build/
7 | dist/
8 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/README.md:
--------------------------------------------------------------------------------
1 | # Q# Interoperability for Python #
2 |
3 | The `qsharp-core` package for Python provides interoperability with the Quantum Development Kit and with the Q# language, making it easy to simulate Q# operations and functions from within Python.
4 |
5 | For details on how to get started with Python and Q#, please see the [Getting Started with Python guide](https://docs.microsoft.com/azure/quantum/install-python-qdk).
6 |
7 | You can also try our [Quantum Computing Fundamentals](https://aka.ms/learnqc) learning path to get familiar with the basic concepts of quantum computing, build quantum programs, and identify the kind of problems that can be solved.
8 |
9 | ## Installing with Anaconda ##
10 |
11 | If you use Anaconda or Miniconda, installing the `qsharp` package will automatically include all dependencies:
12 |
13 | ```bash
14 | conda install -c quantum-engineering qsharp
15 | ```
16 |
17 | ## Installing from Source ##
18 |
19 | If you'd like to contribute to or experiment with the Python interoperability feature, it may be useful to install from source rather than from the `qsharp-core` package on the Python Package Index (PyPI).
20 | To do so, make sure that you are in the `Python` directory, and run `setup.py` with the `install` argument:
21 |
22 | ```bash
23 | cd iqsharp/src/Python/
24 | python setup.py install
25 | ```
26 |
27 | ## Building the `qsharp-core` Package ##
28 |
29 | The Python interoperability feature uses a standard `setuptools`-based packaging strategy.
30 | To build a platform-independent wheel, run the setup script with `bdist_wheel` instead:
31 |
32 | ```bash
33 | cd iqsharp/src/Python/
34 | python setup.py bdist_wheel
35 | ```
36 |
37 | By default, this will create a `qsharp-core` wheel in `dist/` with the version number set to 0.0.0.1.
38 | To provide a more useful version number, set the `PYTHON_VERSION` environment variable before running `setup.py`.
39 |
40 | ## Support and Q&A
41 |
42 | If you have questions about the Quantum Development Kit and the Q# language, or if you encounter issues while using any of the components of the kit, you can reach out to the quantum team and the community of users in [Stack Overflow](https://stackoverflow.com/questions/tagged/q%23) and in [Quantum Computing Stack Exchange](https://quantumcomputing.stackexchange.com/questions/tagged/q%23) tagging your questions with **q#**.
43 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/clients/__init__.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # __init__.py: Logic for launching and configuring Q# clients.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 |
11 | import os
12 | import sys
13 | import time
14 | import logging
15 | import jupyter_client
16 | from distutils.util import strtobool
17 |
18 | class IQSharpNotInstalledError(Exception):
19 | pass
20 |
21 | class IQSharpNotAvailableError(Exception):
22 | pass
23 |
24 | def _start_client():
25 | logger = logging.getLogger(__name__)
26 |
27 | client_name = os.getenv("QSHARP_PY_CLIENT", "iqsharp")
28 |
29 | if client_name == "iqsharp":
30 | # Allow users to override what kernel is used, making it easier to
31 | # test kernels side-by-side.
32 | kernel_name = os.getenv("QSHARP_PY_IQSHARP_KERNEL_NAME", "iqsharp")
33 | import qsharp.clients.iqsharp
34 | client = qsharp.clients.iqsharp.IQSharpClient(kernel_name=kernel_name)
35 | elif client_name == "mock":
36 | import qsharp.clients.mock
37 | client = qsharp.clients.mock.MockClient()
38 |
39 | try:
40 | client.start()
41 | except jupyter_client.kernelspec.NoSuchKernel as ex:
42 | message = "IQ# is not installed." + \
43 | "\nPlease follow the instructions at https://aka.ms/qdk-install/python."
44 | print(message)
45 | raise IQSharpNotInstalledError(message)
46 |
47 | # Check if the server is up and running:
48 | server_ready = False
49 | for idx_attempt in range(20):
50 | try:
51 | server_ready = client.is_ready()
52 | if server_ready:
53 | break
54 | if idx_attempt == 0:
55 | print("Preparing Q# environment...")
56 | else:
57 | print(".", end='', flush=True)
58 | time.sleep(1)
59 | except Exception as ex:
60 | logger.debug('Exception while checking Q# environment.', exc_info=ex)
61 | print("!", end='', flush=True)
62 | time.sleep(1)
63 | if not server_ready:
64 | message = "Q# environment was not available in allocated time." + \
65 | "\nPlease check the instructions at https://aka.ms/qdk-install/python."
66 | print(message)
67 | raise IQSharpNotAvailableError(message)
68 |
69 | return client
70 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/config.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # config.py: Provides access to IQ# configuration settings.
5 | ##
6 | # Copyright (c) Microsoft Corporation.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | from typing import Any
11 |
12 | ## CLASSES ##
13 |
14 | class Config(object):
15 | """
16 | Provides dictionary-like access to IQ# configuration settings.
17 | """
18 |
19 | def __init__(self, client):
20 | self._client = client
21 |
22 | def __getitem__(self, name : str) -> Any:
23 | """
24 | Returns the value of the specified IQ# configuration option.
25 | Options can be set by calls to qsharp.set_config() or by loading
26 | a file previously created by qsharp.save_config().
27 | See https://docs.microsoft.com/qsharp/api/iqsharp-magic/config for the list
28 | of supported IQ# configuration setting names and values.
29 | """
30 | return self._client.get_config()[name]
31 |
32 | def __setitem__(self, name : str, value : object) -> None:
33 | """
34 | Sets a specified IQ# configuration option with the specified value.
35 | See https://docs.microsoft.com/qsharp/api/iqsharp-magic/config for the list
36 | of supported IQ# configuration setting names and values.
37 | """
38 | self._client.set_config(name, value)
39 |
40 | def save(self) -> None:
41 | """
42 | Saves all current IQ# configuration options to a file named .iqsharp-config.json
43 | in the current working directory. This file is automatically loaded
44 | by the IQ# kernel at initialization time.
45 | See https://docs.microsoft.com/qsharp/api/iqsharp-magic/config for the list
46 | of supported IQ# configuration setting names and values.
47 | """
48 | self._client.save_config()
49 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/experimental.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # iqsharp.py: Client for the IQ# Jupyter kernel.
5 | ##
6 | # Copyright (c) Microsoft Corporation.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | """
11 | This module allow for using experimental features of the Quantum Development Kit,
12 | including noisy simulators for Q# programs.
13 | """
14 |
15 | import warnings
16 |
17 | # Re-export noise model APIs from their new locations.
18 | from qsharp.noise_model import *
19 |
20 | def enable_noisy_simulation():
21 | warnings.warn(
22 | "The open systems simulation feature is no longer experimental, such that enable_noisy_simulation "
23 | "no longer needs to be called before using simulate_noise. This function will be removed in "
24 | "a future version of the qsharp package.",
25 | DeprecationWarning
26 | )
27 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/ipython_magic.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # ipython_magic.py: Integration into the IPython notebook environment.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | # NB: This should ONLY be imported from an IPython session.
11 |
12 | import qsharp as qs
13 | from IPython.display import display
14 | from IPython.core.magic import (register_line_magic, register_cell_magic,
15 | register_line_cell_magic, needs_local_scope)
16 |
17 |
18 | def register_magics():
19 | @register_cell_magic
20 | @needs_local_scope
21 | def qsharp(magic_args, cell, local_ns=None):
22 | """Compiles a Q# snippet, exposing its operations and functions to
23 | the current local scope."""
24 | callables = qs.compile(cell)
25 | if isinstance(callables, qs.QSharpCallable):
26 | local_ns[callables._name] = callables
27 | elif callables:
28 | for qs_callable in callables:
29 | local_ns[qs_callable._name] = qs_callable
30 |
31 | def register_experimental_magics():
32 | import qsharp.experimental as exp
33 |
34 | @register_line_magic
35 | def noise_model(line):
36 | args = line.split(' ')
37 | if args[0] == '--set-by-name':
38 | exp.set_noise_model_by_name(args[1])
39 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/packages.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # packages.py: Abstraction to represent the list of packages.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | from distutils.version import LooseVersion
11 | from typing import Iterable, Tuple
12 |
13 | ## LOGGING ##
14 |
15 | import logging
16 | logger = logging.getLogger(__name__)
17 |
18 |
19 | ## CLASSES ##
20 |
21 | class Packages(object):
22 | """
23 | Represents the list of packages loaded into the current Q# session, and
24 | allows for adding new packages from NuGet.org or any other configured feeds.
25 | """
26 |
27 | def __init__(self, client):
28 | self._client = client
29 |
30 | def __iter__(self) -> Iterable[Tuple[str, LooseVersion]]:
31 | for pkg_spec in self._client.get_packages():
32 | name, version = pkg_spec.split("::", 1)
33 | yield name, LooseVersion(version)
34 |
35 | def __repr__(self) -> str:
36 | return repr(list(self))
37 | def __str__(self) -> str:
38 | return str(list(self))
39 |
40 | def add(self, package_name : str) -> None:
41 | """
42 | Adds a NuGet package with the given package name to the current Q#
43 | session, downloading the package from NuGet.org or any other configured
44 | feeds as necessary.
45 | """
46 | logger.info(f"Loading package: {package_name}")
47 | pkgs = self._client.add_package(package_name)
48 | logger.info("Loading complete: " + ';'.join(str(e) for e in pkgs))
49 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/projects.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # projects.py: Abstraction to represent the list of projects.
5 | ##
6 | # Copyright (c) Microsoft Corporation.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | from typing import Iterable, Tuple
11 |
12 | ## LOGGING ##
13 |
14 | import logging
15 | logger = logging.getLogger(__name__)
16 |
17 |
18 | ## CLASSES ##
19 |
20 | class Projects(object):
21 | """
22 | Represents the list of projects loaded into the current Q# session, and
23 | allows for adding references to additional .csproj files.
24 | """
25 |
26 | def __init__(self, client):
27 | self._client = client
28 |
29 | def __iter__(self) -> Iterable[str]:
30 | for project in self._client.get_projects():
31 | yield project
32 |
33 | def __repr__(self) -> str:
34 | return repr(list(self))
35 | def __str__(self) -> str:
36 | return str(list(self))
37 |
38 | def add(self, project_path : str) -> None:
39 | """
40 | Adds a reference to the given Q# project to be loaded
41 | into the current IQ# session.
42 |
43 | :param project_path: Path to the .csproj to be added. May be an absolute
44 | path or a path relative to the current workspace root folder.
45 | """
46 | logger.info(f"Loading project: {project_path}")
47 | loaded_projects = self._client.add_project(project_path)
48 | logger.info("Loading complete: " + ';'.join(str(p) for p in loaded_projects))
49 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/results/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/src/Python/qsharp-core/qsharp/results/__init__.py
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/iqsharp/82f1d6e0303e5cbfe473f8dc86e3786d63f15c68/src/Python/qsharp-core/qsharp/tests/__init__.py
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/tests/test_loader.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # test_loader.py: Tests that the loader correctly handles namespaces and
5 | # callables.
6 | ##
7 | # Copyright (c) Microsoft Corporation.
8 | # Licensed under the MIT License.
9 | ##
10 |
11 | ## IMPORTS ##
12 |
13 | import json
14 | import numpy as np
15 | import os
16 | import pytest
17 | import qsharp
18 | import qsharp.clients.mock
19 | from .utils import set_environment_variables
20 |
21 | print ( qsharp.component_versions() )
22 |
23 | old_client = qsharp.client
24 |
25 | ## SETUP ##
26 |
27 | def setup_module():
28 | # Override with the mock client.
29 | qsharp.client = qsharp.clients.mock.MockClient()
30 | # Set which operations the mock client will report in response to `%who`.
31 | qsharp.client.mock_operations = ["A.B.C", "A.B.D", "A.E.F"]
32 |
33 | def teardown_module():
34 | qsharp.client = old_client
35 |
36 | ## TESTS ##
37 |
38 | def test_can_import():
39 | import A.B
40 | import A.B
41 |
42 | def test_can_import_sub_ns():
43 | import A
44 |
45 | def test_import_dir_is_correct():
46 | import A
47 | assert dir(A) == ["B", "E"]
48 |
49 | import A.B
50 | assert dir(A.B) == ["C", "D"]
51 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/tests/utils.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # utils.py: Common functions for use in IQ# Python tests.
5 | ##
6 | # Copyright (c) Microsoft Corporation.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | import importlib
11 | import os
12 | import qsharp
13 | import sys
14 |
15 | def set_environment_variables():
16 | '''
17 | Sets environment variables for test execution and restarts the IQ# kernel.
18 | Also changes the working directory to the qsharp/tests folder
19 | so that the `Operations.qs` file will be correctly imported/loaded when
20 | the `qsharp` module reloads.
21 | '''
22 | os.chdir(os.path.dirname(os.path.abspath(__file__)))
23 | os.environ["AZURE_QUANTUM_ENV"] = "mock"
24 | os.environ["IQSHARP_AUTO_LOAD_PACKAGES"] = "$null"
25 | importlib.reload(qsharp)
26 | if "qsharp.chemistry" in sys.modules:
27 | importlib.reload(qsharp.chemistry)
28 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/tomography.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # tomography.py: Single qubit tomography of Q# operations.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | ## IMPORTS ##
11 |
12 | import qsharp
13 | import numpy as np
14 |
15 | try:
16 | import qinfer as qi
17 | except ImportError:
18 | qi = None
19 |
20 | try:
21 | import qutip as qt
22 | except ImportError:
23 | qt = None
24 |
25 | def projector(P):
26 | if qt is None:
27 | raise ImportError("This function requires QuTiP.")
28 |
29 | return (qt.qeye(2) + P) / 2.0
30 |
31 | def single_qubit_process_tomography(
32 | operation,
33 | n_measurements=2000,
34 | n_particles=4000
35 | ):
36 | """
37 | :param operation: A Q# operation of type ((Pauli, Pauli) => Result) whose
38 | inputs are named `prep` and `meas` (respectively), representing
39 | a state preparation, evolution, and measurement.
40 | """
41 | if qt is None:
42 | raise ImportError("This function requires QuTiP.")
43 | if qi is None:
44 | raise ImportError("This function requires QInfer.")
45 |
46 | print("Preparing tomography model...")
47 | state_basis = qi.tomography.pauli_basis(1)
48 | prior = qi.tomography.BCSZChoiDistribution(state_basis)
49 | model = qi.tomography.TomographyModel(prior.basis)
50 |
51 | updater = qi.SMCUpdater(model, n_particles, prior)
52 |
53 | print("Performing tomography...")
54 | for idx_experiment in range(n_measurements):
55 | prep = qsharp.Pauli.sample()
56 | meas = qsharp.Pauli.sample()
57 |
58 | # Convert into a QuTiP object by using the standard transformation
59 | # between state and process tomography.
60 | qobj = 2.0 * qt.tensor(
61 | projector(prep.as_qobj()).trans(), projector(meas.as_qobj())
62 | )
63 | expparams = np.array(
64 | [(model.basis.state_to_modelparams(qobj),)],
65 | dtype=model.expparams_dtype
66 | )
67 |
68 | datum = 1 - operation.simulate(prep=prep, meas=meas)
69 |
70 | updater.update(datum, expparams)
71 |
72 | return {
73 | # We multiply by 2 to turn into a Choi–Jamiłkowski operator instead
74 | # of a Choi–Jamiłkowski state.
75 | 'est_channel': 2.0 * model.basis.modelparams_to_state(updater.est_mean()),
76 | # Returning the updater allows for exploring properties not extracted
77 | # elsewhere.
78 | 'posterior': updater
79 | }
80 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/types.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # types.py: Provides types for interoperability with Q#.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | from enum import IntEnum
11 | import random
12 |
13 | from qsharp.utils import try_import_qutip
14 | qt = try_import_qutip(optional=True)
15 |
16 | ## ENUMS ######################################################################
17 |
18 | class Result(IntEnum):
19 | Zero = 0
20 | One = 1
21 |
22 | @classmethod
23 | def sample(cls):
24 | return random.choice(list(cls))
25 |
26 | class Pauli(IntEnum):
27 | I = 0b00
28 | X = 0b01
29 | Y = 0b11
30 | Z = 0b10
31 |
32 | @classmethod
33 | def sample(cls):
34 | return random.choice(list(cls))
35 |
36 | if qt is not None:
37 | def as_qobj(self):
38 | if self == Pauli.I:
39 | return qt.qeye(2)
40 | elif self == Pauli.X:
41 | return qt.sigmax()
42 | elif self == Pauli.Y:
43 | return qt.sigmay()
44 | elif self == Pauli.Z:
45 | return qt.sigmaz()
46 | else:
47 | raise ValueError(f"Unrecognized Pauli value {self}.")
48 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/qsharp/utils.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # utils.py: Utilities internal to the qsharp package.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | from dataclasses import dataclass
11 | import logging
12 | import warnings
13 | logger = logging.getLogger(__name__)
14 | from typing import Callable
15 |
16 | ## INTERNAL FUNCTIONS ##
17 |
18 | def log_messages(data, action : Callable[[str], None] = logger.error):
19 | msgs = data['messages']
20 | for msg in msgs:
21 | action(msg)
22 |
23 | @dataclass
24 | class ImportFailure:
25 | cause: ImportError
26 |
27 | _qutip_cache = None
28 | def try_import_qutip(warn=False, optional=False):
29 | global _qutip_cache
30 | if _qutip_cache is None:
31 | try:
32 | import qutip
33 | _qutip_cache = qutip
34 | except ImportError as ex:
35 | _qutip_cache = ImportFailure(ex)
36 |
37 | if warn and isinstance(_qutip_cache, ImportFailure):
38 | warnings.warn(f"Failed to import QuTiP with error: {_qutip_cache.cause.msg}", source=_qutip_cache.cause)
39 |
40 | if optional and isinstance(_qutip_cache, ImportFailure):
41 | # suppress failure when optional
42 | return None
43 |
44 | return _qutip_cache
45 |
--------------------------------------------------------------------------------
/src/Python/qsharp-core/setup.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 | # -*- coding: utf-8 -*-
3 | ##
4 | # setup.py: Installs Python host functionality for Q#.
5 | ##
6 | # Copyright (c) Microsoft Corporation. All rights reserved.
7 | # Licensed under the MIT License.
8 | ##
9 |
10 | ## IMPORTS ##
11 |
12 | import setuptools
13 | import os
14 |
15 | ## VERSION INFORMATION ##
16 | # Our build process sets the PYTHON_VERSION environment variable to a version
17 | # string that is compatible with PEP 440, and so we inherit that version number
18 | # here and propagate that to qsharp/version.py.
19 | #
20 | # To make sure that local builds still work without the same environment
21 | # variables, we'll default to 0.0.0.1 as a development version.
22 |
23 | version = os.environ.get('PYTHON_VERSION', '0.0.0.1')
24 |
25 | with open('./qsharp/version.py', 'w') as f:
26 | f.write(f'''# Auto-generated file, do not edit.
27 | ##
28 | # version.py: Specifies the version of the qsharp package.
29 | ##
30 | # Copyright (c) Microsoft Corporation.
31 | # Licensed under the MIT License.
32 | ##
33 | __version__ = "{version}"
34 | is_conda = False
35 | _user_agent_extra = "[{version}]"
36 | ''')
37 |
38 | ## DESCRIPTION ##
39 | # The long description metadata passed to setuptools is used to populate the
40 | # PyPI page for this package. Thus, we'll generate the description by using the
41 | # same README.md file that we use in the GitHub repo.
42 |
43 | with open("./README.md", "r") as fh:
44 | long_description = fh.read()
45 |
46 | ## SETUPTOOLS INVOCATION ##
47 |
48 | setuptools.setup(
49 | name="qsharp-core",
50 | version=version,
51 | author="Microsoft",
52 | author_email="que-contacts@microsoft.com",
53 | description="Python client for Q#, a domain-specific quantum programming language",
54 | long_description=long_description,
55 | long_description_content_type="text/markdown",
56 | url="https://github.com/microsoft/iqsharp",
57 | packages=setuptools.find_packages(),
58 | classifiers=[
59 | "Programming Language :: Python :: 3",
60 | "License :: OSI Approved :: MIT License",
61 | "Operating System :: OS Independent",
62 | ],
63 | install_requires=[
64 | 'jupyter_client>=7.3.4'
65 | ]
66 | )
67 |
--------------------------------------------------------------------------------
/src/Python/requirements.txt:
--------------------------------------------------------------------------------
1 | # This file includes requirements to build and test the Python packages.
2 | ipython==8.10.0 # to avoid high-severity issue.
3 | jupyter==1.0.0
4 | nbconvert==7.0.0
5 | notebook==6.5.2
6 | numpy==1.22.0
7 | pytest==7.2.0
8 | pygments==2.15.0 # to avoid high-severity issue.
9 | pyzmq==25.0.0
10 | qutip==4.7.2
11 | selenium==4.2.0
12 | setuptools==67.7.2
13 | traitlets==5.9.0 # traitlets==5.10.0 and notebook==6.5.2 are incompatible: https://github.com/jupyter/notebook/issues/7048
14 | wheel==0.38.1
15 | Markdown>=3.4.1
16 | python-markdown-math>=0.8
17 |
--------------------------------------------------------------------------------
/src/Tests/GlobalSuppressions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | // This file is used by Code Analysis to maintain SuppressMessage
5 | // attributes that are applied to this project.
6 | // Project-level suppressions either have no target or are given
7 | // a specific target and scoped to a namespace, type, member, etc.
8 |
9 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Not following this convention.")]
--------------------------------------------------------------------------------
/src/Tests/PackagesControllerTest.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.Quantum.IQSharp;
5 | using Microsoft.Quantum.IQSharp.Common;
6 | using Microsoft.VisualStudio.TestTools.UnitTesting;
7 | using NuGet.Packaging.Core;
8 | using System.Threading.Tasks;
9 |
10 | #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
11 | #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
12 |
13 | namespace Tests.IQSharp
14 | {
15 | [TestClass]
16 | public class PackagesControllerTest
17 | {
18 | public PackagesController Init(string root = @"Workspace")
19 | {
20 | return Startup.Create(root);
21 | }
22 |
23 | [TestMethod]
24 | public async Task ListPackages()
25 | {
26 | var controller = Init();
27 | var response = await controller.List();
28 | var references = (References)controller.References;
29 | var packageCount = references.AutoLoadPackages.Count;
30 |
31 | Assert.AreEqual(Status.Success, response.Status);
32 | Assert.AreEqual(0, response.Messages.Length);
33 | Assert.AreEqual(packageCount, response.Result.Length);
34 | }
35 |
36 | [TestMethod]
37 | public async Task AddPackage()
38 | {
39 | var controller = Init();
40 | var response = await controller.List();
41 | Assert.AreEqual(0, response.Messages.Length);
42 |
43 | var initCount = response.Result.Length;
44 |
45 | response = await controller.Add($"Microsoft.Quantum.Standard");
46 | Assert.AreEqual(Status.Success, response.Status);
47 | Assert.AreEqual(0, response.Messages.Length);
48 | Assert.AreEqual(initCount + 1, response.Result.Length);
49 |
50 | response = await controller.Add($"jquery::3.5.0.1");
51 | Assert.AreEqual(Status.Success, response.Status);
52 | Assert.AreEqual(0, response.Messages.Length);
53 | Assert.AreEqual(initCount + 2, response.Result.Length);
54 | }
55 | }
56 | }
57 |
58 | #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
59 | #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
60 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.Broken/BasicOps.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.qss {
5 | open Microsoft.Quantum.Intrinsic;
6 | //[ERROR]: MISSING Microsoft.Quantum.Standard;
7 |
8 | /// # Summary
9 | /// The simplest program. Just generate a debug Message on the console.
10 | operation HelloQ() : Unit
11 | {
12 | Message($"Hello from quantum world!");
13 | }
14 |
15 | /// # Summary:
16 | /// A more sophisticated program that shows how to
17 | /// specify parameters, instantiate qubits, and return values.
18 | operation HelloAgain(count: Int, name: String) : Result[]
19 | {
20 | Message($"Hello {name} again!");
21 |
22 | mutable r = new Result[count];
23 | using (q = Qubit()) {
24 | for (i in 1..count) {
25 | if (i == 2) { X(q); }
26 | set r w/= i-1 <- M(q);
27 | Reset(q);
28 | }
29 | }
30 |
31 | return r;
32 | }
33 |
34 | operation CCNOTDriver(applyT : Bool) : Unit {
35 | using(qubits = Qubit[3]) {
36 | CCNOT(qubits[0], qubits[1], qubits[2]);
37 | ApplyIf(applyT, T, qubits[0]);
38 | }
39 | }
40 | }
41 |
42 |
43 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.Broken/NoOp.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.qss {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 |
9 | operation NoOp () : Unit {
10 | //[ERROR]: Can't return anything here:
11 | return 5;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.Chemistry/Operation.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | // This file can only compile if the Mock.Chemistry project
5 | // is added as a reference.
6 | namespace Tests.IQSharp.Chemistry.Samples {
7 | open Mock.Chemistry;
8 |
9 | operation UseJordanWignerEncodingData (qSharpData: JordanWignerEncodingData, nBitsPrecision : Int, trotterStepSize : Double) : (Double, Double) {
10 | let (nSpinOrbitals, data, statePrepData, energyShift) = qSharpData!;
11 |
12 | // Prepare ProductState
13 | let estPhase = 2.0;
14 | let estEnergy = 3.0;
15 |
16 | return (estPhase, estEnergy);
17 | }
18 |
19 |
20 | operation UseHTerm (qSharpData: HTerm[]) : Unit {
21 | }
22 | }
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ExecutionPathTracer/Canon.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ExecutionPathTracer {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 | open Mock.Standard;
8 |
9 | operation ApplyToEachCirc() : Unit {
10 | using (qs = Qubit[3]) {
11 | ApplyToEach(H, qs);
12 | ResetAll(qs);
13 | }
14 | }
15 |
16 | operation ApplyDoubleX(q : Qubit) : Unit {
17 | X(q);
18 | X(q);
19 | }
20 |
21 | operation ApplyToEachDepth2Circ() : Unit {
22 | using (qs = Qubit[2]) {
23 | ApplyToEach(ApplyDoubleX, qs);
24 | ResetAll(qs);
25 | }
26 | }
27 |
28 | }
29 |
30 |
31 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ExecutionPathTracer/Circuits.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ExecutionPathTracer {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 | // Custom operation
9 | operation Foo(theta : Double, (qubit : Qubit, bar : String)) : Unit
10 | is Adj + Ctl { }
11 |
12 | operation FooCirc() : Unit {
13 | using (q = Qubit()) {
14 | Foo(2.1, (q, "bar"));
15 | }
16 | }
17 |
18 | operation ControlledFooCirc() : Unit {
19 | using (qs = Qubit[2]) {
20 | Controlled Foo([qs[0]], (2.1, (qs[1], "bar")));
21 | }
22 | }
23 |
24 | operation UnusedQubitCirc() : Unit {
25 | using (qs = Qubit[3]) {
26 | CNOT(qs[2], qs[0]);
27 | Reset(qs[0]);
28 | Reset(qs[2]);
29 | }
30 | }
31 |
32 | operation EmptyCirc() : Unit {
33 | using (qs = Qubit[3]) {
34 | }
35 | }
36 |
37 | operation NoQubitCirc(n : Int) : Unit { }
38 |
39 | operation NoQubitArgsCirc() : Unit {
40 | NoQubitCirc(2);
41 | }
42 |
43 | operation WithQArrayArgs(bits: Bool[]): Unit { }
44 |
45 | operation WithQArrayArgsCirc(): Unit {
46 | WithQArrayArgs([false, true]);
47 | }
48 |
49 | operation OperationCirc(op : (Qubit => Unit), n : Int) : Unit { }
50 |
51 | operation OperationArgsCirc() : Unit {
52 | OperationCirc(H, 5);
53 | }
54 |
55 | operation NestedCirc() : Unit {
56 | using (q = Qubit()) {
57 | H(q);
58 | HCirc();
59 | Reset(q);
60 | }
61 | }
62 |
63 | operation PartialOpCirc() : Unit {
64 | using (qs = Qubit[3]) {
65 | (Controlled H(qs[0..1], _))(qs[2]);
66 | ((Ry(_, _))(2.5, _))(qs[0]);
67 | ResetAll(qs);
68 | }
69 | }
70 |
71 | operation Bar((alpha : Double, beta : Double), (q : Qubit, name : String)) : Unit
72 | is Adj + Ctl { }
73 |
74 | operation BigCirc() : Unit {
75 | using (qs = Qubit[3]) {
76 | H(qs[0]);
77 | Ry(2.5, qs[1]);
78 | Bar((1.0, 2.1), (qs[0], "foo"));
79 | X(qs[0]);
80 | CCNOT(qs[0], qs[1], qs[2]);
81 | Controlled CNOT([qs[0]], (qs[1], qs[2]));
82 | Controlled Adjoint Bar([qs[2]], ((1.0, 2.1), (qs[0], "foo")));
83 | let res = M(qs[0]);
84 | ResetAll(qs);
85 | }
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ExecutionPathTracer/Intrinsic.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ExecutionPathTracer {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 | operation HCirc() : Unit {
9 | using (q = Qubit()) {
10 | H(q);
11 | Reset(q);
12 | }
13 | }
14 |
15 | operation MCirc() : Unit {
16 | using (q = Qubit()) {
17 | let res = M(q);
18 | }
19 | }
20 |
21 | operation CnotCirc() : Unit {
22 | using (qs = Qubit[2]) {
23 | CNOT(qs[0], qs[1]);
24 | ResetAll(qs);
25 | }
26 | }
27 |
28 | operation CcnotCirc() : Unit {
29 | using (qs = Qubit[3]) {
30 | CCNOT(qs[0], qs[2], qs[1]);
31 | ResetAll(qs);
32 | }
33 | }
34 |
35 | operation SwapCirc() : Unit {
36 | using (qs = Qubit[2]) {
37 | SWAP(qs[0], qs[1]);
38 | }
39 | }
40 |
41 | operation RxCirc() : Unit {
42 | using (q = Qubit()) {
43 | Rx(2.0, q);
44 | Reset(q);
45 | }
46 | }
47 |
48 | operation AdjointHCirc() : Unit {
49 | using (q = Qubit()) {
50 | Adjoint H(q);
51 | Reset(q);
52 | }
53 | }
54 |
55 | operation ControlledXCirc() : Unit {
56 | using (qs = Qubit[2]) {
57 | Controlled X([qs[0]], qs[1]);
58 | ResetAll(qs);
59 | }
60 | }
61 |
62 | operation ControlledAdjointSCirc() : Unit {
63 | using (qs = Qubit[2]) {
64 | Controlled Adjoint S([qs[0]], qs[1]);
65 | ResetAll(qs);
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ExecutionPathTracer/Measurement.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ExecutionPathTracer {
5 |
6 | open Microsoft.Quantum.Measurement;
7 | open Microsoft.Quantum.Arrays;
8 | open Mock.Standard;
9 |
10 | operation MResetXCirc() : Unit {
11 | using (q = Qubit()) {
12 | let res = MResetX(q);
13 | }
14 | }
15 |
16 | operation MResetYCirc() : Unit {
17 | using (q = Qubit()) {
18 | let res = MResetY(q);
19 | }
20 | }
21 |
22 | operation MResetZCirc() : Unit {
23 | using (q = Qubit()) {
24 | let res = MResetZ(q);
25 | }
26 | }
27 |
28 | operation ForEachMeasureCirc() : Unit {
29 | using (qs = Qubit[2]) {
30 | let res = ForEach(MResetZ, qs);
31 | }
32 | }
33 |
34 | }
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.HardwareTarget/Operation.qs:
--------------------------------------------------------------------------------
1 | namespace Tests.qss {
2 |
3 | open Microsoft.Quantum.Intrinsic;
4 |
5 | operation ValidEntryPoint() : Result {
6 | use q = Qubit();
7 | H(q);
8 | return M(q);
9 | }
10 |
11 | operation ClassicalControl() : Result {
12 | use q = Qubit[2];
13 | H(q[0]);
14 | if (M(q[0])== One) {
15 | X(q[1]);
16 | }
17 | return M(q[1]);
18 | }
19 | }
--------------------------------------------------------------------------------
/src/Tests/Workspace.ProjectReferences.ProjectA/ProjectA.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ProjectReferences.ProjectA/ProjectA.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ProjectReferences.ProjectA {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 | open Tests.ProjectReferences.ProjectB as ProjectB;
8 |
9 | operation RotateAndMeasure(q : Qubit) : Result {
10 | return ProjectB.RotateAndMeasure(q);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ProjectReferences.ProjectB/ProjectB.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | false
6 | false
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ProjectReferences.ProjectB/ProjectB.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ProjectReferences.ProjectB {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 | operation RotateAndMeasure(q : Qubit) : Result {
9 | Rx(1.0, q);
10 | return M(q);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ProjectReferences/Operation.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.ProjectReferences {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 | open Tests.ProjectReferences.ProjectA;
8 |
9 | operation MeasureSingleQubit() : Result {
10 | using (q = Qubit()) {
11 | return RotateAndMeasure(q);
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.ProjectReferences/Workspace.ProjectReferences.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | false
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/Tests/Workspace.QPRGen1/Operations.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.qss {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 | @EntryPoint()
9 | operation CompareMeasurementResult() : Result {
10 | using (q = Qubit()) {
11 | let r = M(q);
12 | if (r == One) {
13 | H(q);
14 | Reset(q);
15 | }
16 | return r;
17 | }
18 | }
19 | }
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/Tests/Workspace/BasicOps.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.qss {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 | // Note that we specify multiple @EntryPoint() operations in this file
9 | // to verify that these attributes have no impact on the compilation of
10 | // the file for use in IQ#.
11 |
12 | /// # Summary:
13 | /// The simplest program. Just generate a debug Message on the console.
14 | @EntryPoint()
15 | operation HelloQ() : Unit
16 | {
17 | Message($"Hello from quantum world!");
18 | }
19 |
20 | /// # Summary:
21 | /// A more sophisticated program that shows how to
22 | /// specify parameters, instantiate qubits, and return values.
23 | @EntryPoint()
24 | operation HelloAgain(count: Int, name: String) : Result[]
25 | {
26 | Message($"Hello {name} again!");
27 |
28 | mutable r = new Result[count];
29 | using (q = Qubit()) {
30 | for (i in 1..count) {
31 | if (i == 2) { X(q); }
32 | set r w/= i-1 <- M(q);
33 | Reset(q);
34 | }
35 | }
36 |
37 | return r;
38 | }
39 |
40 | /// # Summary:
41 | /// A more sophisticated program that shows how to
42 | /// specify parameters, instantiate qubits, and return values.
43 | @EntryPoint()
44 | operation SayHelloWithArray(names: String[]) : Unit {
45 | for name in names {
46 | Message($"Hello {name} again!");
47 | }
48 | }
49 |
50 | operation CCNOTDriver(applyT : Bool) : Unit {
51 | using(qubits = Qubit[3]) {
52 | CCNOT(qubits[0], qubits[1], qubits[2]);
53 | }
54 | }
55 | }
56 |
57 |
58 |
--------------------------------------------------------------------------------
/src/Tests/Workspace/NoOp.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | namespace Tests.qss {
5 |
6 | open Microsoft.Quantum.Intrinsic;
7 |
8 |
9 | operation NoOp () : Unit {
10 |
11 | }
12 |
13 | }
14 |
15 |
16 |
--------------------------------------------------------------------------------
/src/Tool/EnvironmentProvider.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | #nullable enable
5 | using System;
6 | using System.Collections;
7 | using System.Collections.Generic;
8 | using System.Collections.Immutable;
9 | using System.Linq;
10 | using Microsoft.Extensions.Configuration;
11 |
12 | namespace Microsoft.Quantum.IQSharp
13 | {
14 | public class NormalizedEnvironmentVariableConfigurationSource : IConfigurationSource
15 | {
16 | public IDictionary? Aliases { get; set; }
17 | public string? Prefix { get; set; }
18 | public IConfigurationProvider Build(IConfigurationBuilder builder) =>
19 | new NormalizedEnvironmentVariableConfigurationProvider(
20 | Prefix, Aliases
21 | );
22 | }
23 |
24 | public class NormalizedEnvironmentVariableConfigurationProvider : ConfigurationProvider
25 | {
26 | private readonly IImmutableDictionary Aliases;
27 | private readonly string Prefix;
28 |
29 | public NormalizedEnvironmentVariableConfigurationProvider(
30 | string? prefix = null,
31 | IDictionary? aliases = null
32 | )
33 | {
34 | Aliases = aliases?.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase)
35 | ?? ImmutableDictionary.Empty;
36 | Prefix = prefix ?? "";
37 | }
38 |
39 | public override void Load() =>
40 | Data = System.Environment
41 | .GetEnvironmentVariables()
42 | .Cast()
43 | .Where(variable =>
44 | ((string)variable.Key).StartsWith(Prefix)
45 | )
46 | .ToDictionary(
47 | variable => {
48 | var keyWithoutPrefix = ((string)variable.Key)
49 | .Substring(Prefix.Length);
50 | if (Aliases.TryGetValue(keyWithoutPrefix, out var newKey))
51 | {
52 | return newKey;
53 | }
54 | return keyWithoutPrefix;
55 | },
56 | variable => ((string)variable.Value!),
57 | StringComparer.OrdinalIgnoreCase
58 | );
59 | }
60 | }
--------------------------------------------------------------------------------
/src/Tool/Tool.csproj.orig:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | x64
6 | netcoreapp3.0
7 | Microsoft.Quantum.IQSharp
8 | Microsoft.Quantum.IQSharp
9 |
10 |
11 |
12 | 0162
13 | Microsoft
14 | Microsoft's IQ# Server.
15 | © Microsoft Corporation. All rights reserved.
16 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes
17 | MIT
18 | https://github.com/Microsoft/Quantum
19 | qdk-nuget-icon.png
20 | Quantum Q# Qsharp
21 | true
22 | dotnet-iqsharp
23 | Microsoft.Quantum.IQSharp
24 | \
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 | PreserveNewest
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/src/Tool/Untitled.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "id": "5f3293d1",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": []
10 | }
11 | ],
12 | "metadata": {
13 | "kernelspec": {
14 | "display_name": "Q#",
15 | "language": "qsharp",
16 | "name": "iqsharp"
17 | },
18 | "language_info": {
19 | "file_extension": ".qs",
20 | "mimetype": "text/x-qsharp",
21 | "name": "qsharp",
22 | "version": "0.27"
23 | }
24 | },
25 | "nbformat": 4,
26 | "nbformat_minor": 5
27 | }
28 |
--------------------------------------------------------------------------------
/src/Tool/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Warning"
5 | }
6 | },
7 | "AllowedHosts": "*",
8 | "DefaultPackageVersions": [
9 | "Microsoft.Quantum.Compiler::0.28.302812",
10 | "Microsoft.Quantum.CSharpGeneration::0.28.302812",
11 | "Microsoft.Quantum.QirGeneration::0.28.302812",
12 | "Microsoft.Quantum.Development.Kit::0.28.302812",
13 | "Microsoft.Quantum.Simulators::0.28.302812",
14 | "Microsoft.Quantum.Xunit::0.28.302812",
15 | "Microsoft.Quantum.Standard::0.28.302812",
16 | "Microsoft.Quantum.Standard.Visualization::0.28.302812",
17 | "Microsoft.Quantum.Chemistry::0.28.302812",
18 | "Microsoft.Quantum.Chemistry.Jupyter::0.28.302812",
19 | "Microsoft.Quantum.MachineLearning::0.28.302812",
20 | "Microsoft.Quantum.Numerics::0.28.302812",
21 | "Microsoft.Quantum.Katas::0.28.302812",
22 | "Microsoft.Quantum.Research::0.28.302812",
23 | "Microsoft.Quantum.Providers.Core::0.28.302812",
24 | "Microsoft.Quantum.Providers.IonQ::0.28.302812",
25 | "Microsoft.Quantum.Providers.Honeywell::0.28.302812",
26 | "Microsoft.Quantum.Providers.QCI::0.28.302812",
27 | "Microsoft.Quantum.Providers.Rigetti::0.28.302812"
28 | ]
29 | }
30 |
--------------------------------------------------------------------------------
/src/Web/Models/CompileSnippetModel.cs:
--------------------------------------------------------------------------------
1 | namespace Microsoft.Quantum.IQSharp.Web.Models
2 | {
3 | ///
4 | /// Model consumed by the .
5 | ///
6 | public class CompileSnippetModel
7 | {
8 | ///
9 | /// Q# source code to compile.
10 | ///
11 | public string Code { get; set; }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/Web/PackagesController.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation. All rights reserved.
2 | // Licensed under the MIT License.
3 |
4 | using Microsoft.AspNetCore.Mvc;
5 | using Microsoft.Quantum.IQSharp.Common;
6 | using System;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
11 | #pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
12 |
13 | namespace Microsoft.Quantum.IQSharp
14 | {
15 | ///
16 | /// Provides a mechanism to manage nuget packages.
17 | ///
18 | [Route("api/[controller]")]
19 | [ApiController]
20 | public class PackagesController : ControllerBase
21 | {
22 | public PackagesController(IReferences references)
23 | {
24 | this.References = references;
25 | }
26 |
27 | ///
28 | /// Packages are managed via the IReferences
29 | ///
30 | public IReferences References { get; }
31 |
32 | ///
33 | /// Default entry point. Returns the list of operations in the Workspace.
34 | ///
35 | [HttpGet]
36 | public async Task> List()
37 | {
38 | try
39 | {
40 | return new Response(Status.Success, new string[] { }, References.Packages?.ToArray());
41 | }
42 | catch (Exception e)
43 | {
44 | return new Response(Status.Error, new string[] { e.Message });
45 | }
46 | }
47 |
48 | ///
49 | /// Default entry point. Returns the list of operations in the Workspace.
50 | ///
51 | [HttpGet("add/{pkg}")]
52 | public async Task> Add(string pkg)
53 | {
54 | try
55 | {
56 | await References.AddPackage(pkg);
57 | return await List();
58 | }
59 | catch (Exception e)
60 | {
61 | return new Response(Status.Error, new string[] { e.Message });
62 | }
63 | }
64 | }
65 | }
66 |
67 | #pragma warning restore VSTHRD200 // Use "Async" suffix for async methods
68 | #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
69 |
--------------------------------------------------------------------------------
/src/Web/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | [assembly: InternalsVisibleTo("Tests.IQsharp" + SigningConstants.PUBLIC_KEY)]
4 |
--------------------------------------------------------------------------------
/src/Web/Response.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using Newtonsoft.Json;
7 | using Newtonsoft.Json.Converters;
8 |
9 | namespace Microsoft.Quantum.IQSharp.Common
10 | {
11 | ///
12 | /// The status after executing the requested operation.
13 | ///
14 | public enum Status
15 | {
16 | Success,
17 | Error
18 | }
19 |
20 | ///
21 | /// A data structure representing the response from one of the Controllers.
22 | ///
23 | ///
24 | public class Response
25 | {
26 | public Response() { }
27 |
28 | public Response(Status status, IEnumerable messages, T? result = default(T))
29 | {
30 | this.Status = status;
31 | this.Messages = messages.ToArray();
32 | this.Result = result;
33 | }
34 |
35 | ///
36 | /// Whether the request ended in success or error.
37 | ///
38 | [JsonConverter(typeof(StringEnumConverter))]
39 | public Status Status { get; set; }
40 |
41 | ///
42 | /// List of messages generated by the call. For example, it can return
43 | /// the list of warnings from a successful compilation, or the list of Messages
44 | /// from a Q# simulation.
45 | ///
46 | public string[]? Messages { get; set; }
47 |
48 | ///
49 | /// The actual result from the operation. From simulation this is the result of
50 | /// the operation being simulated. For compilation, the list of operations found in the snippet.
51 | ///
52 | public T? Result { get; set; }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/Web/Web.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | x64
6 | Microsoft.Quantum.IQSharp.Web
7 | Microsoft.Quantum.IQSharp.Web
8 |
9 |
10 |
11 |
14 |
17 |
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/test-containers/miniconda/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | {
2 | "image": "continuumio/miniconda3"
3 | }
4 |
--------------------------------------------------------------------------------
/test-containers/miniconda/environment.yml:
--------------------------------------------------------------------------------
1 | name: qsharp
2 | channels:
3 | - quantum-engineering
4 | dependencies:
5 | - qsharp
6 |
--------------------------------------------------------------------------------
/tests.live/All.Tests.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 | BeforeAll {
5 | # Makes sure all the required environment variables are set.
6 | function Test-Environment {
7 | $Env:AZURE_QUANTUM_SUBSCRIPTION_ID | Should -Not -BeNullOrEmpty
8 | $Env:AZURE_QUANTUM_WORKSPACE_RG | Should -Not -BeNullOrEmpty
9 | $Env:AZURE_QUANTUM_WORKSPACE_LOCATION | Should -Not -BeNullOrEmpty
10 | $Env:AZURE_QUANTUM_WORKSPACE_NAME | Should -Not -BeNullOrEmpty
11 |
12 | # These are needed for environment credentials:
13 | $Env:AZURE_TENANT_ID | Should -Not -BeNullOrEmpty
14 | # $Env:AZURE_CLIENT_ID | Should -Not -BeNullOrEmpty
15 | # $Env:AZURE_CLIENT_SECRET | Should -Not -BeNullOrEmpty
16 | }
17 |
18 | function Test-Notebook([string]$notebook) {
19 | if (Test-Path "obj") {
20 | Remove-Item obj -Recurse
21 | }
22 |
23 | "Running jupyter nbconvert on '$notebook'" | Write-Verbose
24 | jupyter nbconvert $notebook --execute --stdout --to markdown --ExecutePreprocessor.timeout=120 | Write-Verbose
25 |
26 | $LASTEXITCODE | Should -Be 0
27 | }
28 | }
29 |
30 | Describe "Test Jupyter Notebooks" {
31 | BeforeAll {
32 | Test-Environment
33 | Push-Location .\Notebooks
34 | }
35 |
36 | It "Converts IonQ.ipynb successfully" -Tag "submit.ionq" {
37 | Test-Notebook "IonQ.ipynb"
38 | }
39 |
40 | It "Converts ResourceEstimator.ipynb successfully" -Tag "submit.microsoft-qc" {
41 | Test-Notebook "ResourceEstimator.ipynb"
42 | }
43 |
44 | AfterAll { Pop-Location }
45 | }
46 |
47 | Describe "Test Python Integration" {
48 | BeforeAll {
49 | Test-Environment
50 | Push-Location .\Python
51 |
52 | if (Test-Path "obj") {
53 | Remove-Item obj -Recurse
54 | }
55 | }
56 |
57 | It "Runs pytest successfully for ionq" -Tag "submit.ionq" {
58 | python -m pytest -k ionq --junitxml="junit/TestResults-IonQ.xml" | Write-Verbose
59 | $LASTEXITCODE | Should -Be 0
60 | }
61 |
62 | It "Runs pytest successfully for Quantinuum" -Tag "submit.quantinuum" {
63 | python -m pytest -k quantinuum --junitxml="junit/TestResults-Quantinuum.xml" | Write-Verbose
64 | $LASTEXITCODE | Should -Be 0
65 | }
66 |
67 | It "Runs pytest successfully for estimator" -Tag "submit.microsoft-qc" {
68 | python -m pytest -k estimator --junitxml="junit/TestResults-Estimator.xml" | Write-Verbose
69 | $LASTEXITCODE | Should -Be 0
70 | }
71 |
72 | AfterAll { Pop-Location }
73 | }
74 |
75 |
--------------------------------------------------------------------------------
/tests.live/Python/qsharp/estimator/Estimator.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | microsoft.estimator
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/tests.live/Python/qsharp/estimator/Operation.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.Tests {
5 | open Microsoft.Quantum.Arithmetic;
6 |
7 | operation EstimateMultiplication(bitwidth : Int) : Unit {
8 | use factor1 = Qubit[bitwidth];
9 | use factor2 = Qubit[bitwidth];
10 | use product = Qubit[2 * bitwidth];
11 |
12 | MultiplyI(LittleEndian(factor1), LittleEndian(factor2), LittleEndian(product));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/tests.live/Python/qsharp/ionq/IonQ.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | ionq.simulator
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/tests.live/Python/qsharp/ionq/Operations.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.Tests {
5 | open Microsoft.Quantum.Intrinsic;
6 | open Microsoft.Quantum.Canon;
7 |
8 | /// # Summary
9 | /// A quantum random number generator with a variable number of qubits.
10 | operation SampleQrng(count : Int, name : String) : Result[] {
11 | Message($"Hello {name} again!");
12 |
13 | mutable r = [Zero, size = count];
14 | use q = Qubit[count];
15 |
16 | ApplyToEach(H, q);
17 |
18 | for i in 1..count {
19 | set r w/= i-1 <- M(q[i-1]);
20 | }
21 |
22 | return r;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/tests.live/Python/qsharp/quantinuum/Operations.qs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft Corporation.
2 | // Licensed under the MIT License.
3 |
4 | namespace Microsoft.Quantum.Tests {
5 | open Microsoft.Quantum.Intrinsic;
6 | open Microsoft.Quantum.Canon;
7 |
8 | operation RunTeleportWithPlus() : Result {
9 | return RunTeleport(true);
10 | }
11 |
12 | /// # Summary
13 | /// Direct implementation of Teleport's circuit
14 | operation RunTeleport(doPlus: Bool) : Result {
15 | Message("Running teleport circuit");
16 |
17 | use qubits = Qubit[3];
18 | // Entangle
19 | H(qubits[1]);
20 | CNOT(qubits[1], qubits[2]);
21 |
22 | // Encode
23 | if (doPlus) {
24 | SetPlus(qubits[0]);
25 | } else {
26 | SetMinus(qubits[0]);
27 | }
28 |
29 | CNOT(qubits[0], qubits[1]);
30 | H(qubits[0]);
31 | let classicInfo = M(qubits[0]);
32 |
33 | // Decode
34 | if (M(qubits[1]) == One) { X(qubits[2]); }
35 | if (classicInfo == One) { Z(qubits[2]); }
36 |
37 | // Report message received:
38 | return Measure([PauliX], qubits[2..2]);
39 | }
40 |
41 | /// # Summary
42 | /// Sets the qubit's state to |+>
43 | operation SetPlus(q: Qubit) : Unit {
44 | H(q);
45 | }
46 |
47 | /// # Summary
48 | /// Sets the qubit's state to |->
49 | operation SetMinus(q: Qubit) : Unit {
50 | X(q);
51 | H(q);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/tests.live/Python/qsharp/quantinuum/Quantinuum.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | qci.qpu
6 | AdaptiveExecution
7 | true
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/tests.live/README.md:
--------------------------------------------------------------------------------
1 | # IQ# Live tests
2 |
3 | This folder contains Live tests for IQ#.
4 | Live tests are end-to-end tests that require an actual connection with Azure Quantum
5 | to complete successfully.
6 |
7 | Notice these tests are currently not part of IQ#'s CI pipeline.
8 | Please run them manually if making Azure Quantum related changes.
9 |
10 | ## Running locally
11 |
12 | To run these tests:
13 |
14 | 1. Use [Install-Artifacts.ps1](./Install-Artifacts.ps1) to install IQ#, either from
15 | from the local [`/src`](../src) folder, or from build artifacts by specifying the following
16 | environment variables:
17 | * `NUGET_OUTDIR`: with the location of the build's NuGet packages
18 | * `NUGET_VERSION`: with the packages' NuGet version.
19 | * `PYTHON_OUTDIR`: with the location of the build's Python wheels
20 | 2. Set up the following environment variables pointing to an Azure Quantum Workspace that has the Microsoft, IonQ and Quantinuum providers enabled:
21 | * `$Env:AZURE_QUANTUM_SUBSCRIPTION_ID=""`
22 | * `$Env:AZURE_QUANTUM_WORKSPACE_RG=""`
23 | * `$Env:AZURE_QUANTUM_WORKSPACE_LOCATION=""`
24 | * `$Env:AZURE_QUANTUM_WORKSPACE_NAME=""`
25 | * `$Env:AZURE_TENANT_ID=""`
26 | * `$Env:AZURE_CLIENT_ID=""`
27 | * `$Env:AZURE_CLIENT_SECRET=""`
28 | 3. Use [`.\Run.ps1 -SkipInstall`](.\Run.ps1) to run all the tests.
29 |
30 | Optionally, instead of providing `AZURE_CLIENT_ID` AND `AZURE_CLIENT_SECRET` as environment variables,
31 | you can login to Azure using either:
32 | * the [Azure Account extension in VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account)
33 | * `az login` from the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/)
34 | and change the value of the `credential=` parameter in the tests to the corresponding value.
35 |
--------------------------------------------------------------------------------
/tests.live/Run.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 | param (
4 | [Parameter()]
5 | [switch]
6 | $SkipInstall=$False
7 | )
8 |
9 | # For debug, print all relevant environment variables:
10 | Get-ChildItem env:AZURE*, env:*VERSION, env:*OUTDIR | Format-Table | Out-String | Write-Host
11 |
12 | if (-not $SkipInstall) {
13 | .\Install-Artifacts.ps1
14 | }
15 |
16 | # Install and run Pester
17 | Import-Module Pester
18 |
19 | $config = [PesterConfiguration]::Default
20 | $config.Run.Exit = $true
21 | $config.TestResult.Enabled = $true
22 | $config.TestResult.OutputPath = "TestResults.xml"
23 | $config.TestResult.OutputFormat = "JUnitXml"
24 | $config.Output.Verbosity = "Detailed"
25 |
26 | if (Test-Path Env:AZURE_QUANTUM_CAPABILITIES) {
27 | $config.Filter.Tag = $Env:AZURE_QUANTUM_CAPABILITIES -Split ";" | ForEach-Object { $_.trim() }
28 | } else {
29 | "Missing AZURE_QUANTUM_CAPABILITIES env variable. Will run all tests." | Write-Warning
30 | }
31 |
32 | Invoke-Pester -Configuration $config -Verbose
--------------------------------------------------------------------------------