forked from Thorium/FSharp.Azure.Quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkspaceExample.fsx
More file actions
380 lines (326 loc) · 14.3 KB
/
Copy pathWorkspaceExample.fsx
File metadata and controls
380 lines (326 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Azure Quantum Workspace Example
// Demonstrates SDK-powered workspace management
//#r "nuget: FSharp.Azure.Quantum"
#r "nuget: Microsoft.Azure.Quantum.Client"
#r "../../src/FSharp.Azure.Quantum/bin/Debug/net10.0/FSharp.Azure.Quantum.dll"
open System
open FSharp.Azure.Quantum.Backends.AzureQuantumWorkspace
printfn "========================================="
printfn "Azure Quantum Workspace Example"
printfn "=========================================\n"
// ============================================================================
// Example 1: Create Workspace Connection
// ============================================================================
printfn "Example 1: Create Workspace\n"
// Create workspace with your Azure Quantum credentials
// Note: Workspace implements IDisposable for proper resource cleanup
use workspace =
createDefault
"your-subscription-id" // Azure subscription ID
"your-resource-group" // Resource group name
"your-workspace-name" // Workspace name
"eastus" // Azure region
printfn "✅ Workspace created: %s" workspace.Config.WorkspaceName
printfn " Location: %s" workspace.Config.Location
printfn " (Using 'use' keyword for automatic disposal)"
printfn ""
// ============================================================================
// Example 2: Check Quota (Requires Real Azure Quantum Workspace)
// ============================================================================
printfn "Example 2: Check Quota (requires valid credentials)\n"
// Uncomment to test with real workspace:
(*
async {
try
let! quota = workspace.GetTotalQuotaAsync()
printfn "Quota Status:"
match quota.Limit with
| Some limit -> printfn " Total Limit: %.2f credits" limit
| None -> printfn " Total Limit: Unlimited"
match quota.Used with
| Some used -> printfn " Used: %.2f credits" used
| None -> printfn " Used: 0.00 credits"
match quota.Remaining with
| Some remaining ->
printfn " Remaining: %.2f credits" remaining
if remaining < 100.0 then
printfn " ⚠️ WARNING: Low quota remaining!"
| None -> printfn " Remaining: Unlimited"
with ex ->
printfn "❌ Could not fetch quota: %s" ex.Message
printfn " (This is expected without valid Azure Quantum credentials)"
} |> Async.RunSynchronously
*)
printfn "💡 To test quota checking:"
printfn " 1. Set up Azure Quantum workspace at https://portal.azure.com"
printfn " 2. Update credentials in this script"
printfn " 3. Uncomment the async block above"
printfn ""
// ============================================================================
// Example 3: List Providers (Requires Real Workspace)
// ============================================================================
printfn "Example 3: List Quantum Providers\n"
// Uncomment to test with real workspace:
(*
async {
try
let! providers = workspace.ListProvidersAsync()
printfn "Available Quantum Providers:"
for provider in providers do
printfn ""
printfn " Provider: %s" provider.ProviderId
match provider.CurrentAvailability with
| Some status -> printfn " Status: %s" status
| None -> printfn " Status: Unknown"
printfn " Targets: %d" provider.TargetCount
with ex ->
printfn "❌ Could not fetch providers: %s" ex.Message
} |> Async.RunSynchronously
*)
printfn "💡 Typical providers include:"
printfn " - ionq (Trapped ion quantum computers)"
printfn " - rigetti (Superconducting quantum processors)"
printfn " - quantinuum (Trapped ion systems)"
printfn ""
// ============================================================================
// Example 4: Environment-Based Configuration (Production Pattern)
// ============================================================================
printfn "Example 4: Environment Configuration\n"
printfn "For production, use environment variables:"
printfn " export AZURE_QUANTUM_SUBSCRIPTION_ID=\"...\""
printfn " export AZURE_QUANTUM_RESOURCE_GROUP=\"...\""
printfn " export AZURE_QUANTUM_WORKSPACE_NAME=\"...\""
printfn " export AZURE_QUANTUM_LOCATION=\"eastus\""
printfn ""
match createFromEnvironment() with
| Ok ws ->
printfn "✅ Workspace loaded from environment"
printfn " Workspace: %s" ws.Config.WorkspaceName
| Error err ->
printfn "⚠️ Environment variables not set"
printfn " %s" err.Message
printfn ""
printfn "========================================="
printfn "Example 5: Hybrid Workspace + HTTP Pattern (RECOMMENDED)"
printfn "=========================================\n"
printfn "Best practice: Use workspace for quota/discovery, HTTP backends for execution\n"
// Create a backend using the workspace
open FSharp.Azure.Quantum.Core.BackendAbstraction
printfn "Step 1: Check quota before execution"
printfn ""
// Uncomment to test with real workspace:
(*
async {
try
let! quota = workspace.GetTotalQuotaAsync()
match quota.Remaining with
| Some remaining when remaining < 10.0 ->
printfn "⚠️ Low quota (%.2f credits) - stopping execution" remaining
return None
| Some remaining ->
printfn "✅ Sufficient quota (%.2f credits remaining)" remaining
return Some remaining
| None ->
printfn "✅ Unlimited quota"
return Some System.Double.MaxValue
with ex ->
printfn "❌ Could not check quota: %s" ex.Message
return None
} |> Async.RunSynchronously
*)
printfn ""
printfn "Step 2: Create HTTP backend for proven execution"
printfn ""
printfn "Code example:"
printfn ""
printfn " open System.Net.Http"
printfn " use httpClient = new HttpClient()"
printfn ""
printfn " let backend = createIonQBackend"
printfn " httpClient"
printfn " \"https://your-workspace.quantum.azure.com\""
printfn " \"ionq.simulator\""
printfn ""
printfn " // Convert circuit to provider format"
printfn " let circuit = quantumCircuit { H 0; CNOT 0 1 }"
printfn " let wrapper = CircuitWrapper(circuit) :> ICircuit"
printfn ""
printfn " match convertCircuitToProviderFormat wrapper \"ionq.simulator\" with"
printfn " | Ok json -> "
printfn " // Execute on backend"
printfn " match backend.Execute wrapper 1000 with"
printfn " | Ok result -> printfn \"Success!\""
printfn " | Error msg -> printfn \"Error: %s\" msg"
printfn " | Error msg -> "
printfn " printfn \"Circuit conversion failed: %s\" msg"
printfn ""
printfn "Benefits of this hybrid approach:"
printfn " ✅ Workspace quota checking and provider discovery"
printfn " ✅ Circuit format conversion helpers (Phase 2)"
printfn " ✅ Proven HTTP backends for job execution"
printfn " ✅ Full job submission, polling, and result parsing"
printfn " ✅ Production-ready NOW (no SDK API exploration needed)"
printfn ""
printfn "========================================="
printfn "Example 6: Circuit Conversion Helpers (Phase 2)"
printfn "=========================================\n"
printfn "Convert circuits to provider-specific formats:\n"
printfn "Code example:"
printfn ""
printfn " // Your circuit"
printfn " let circuit = quantumCircuit {"
printfn " H 0"
printfn " CNOT 0 1"
printfn " RX (0, Math.PI / 4.0)"
printfn " }"
printfn ""
printfn " let wrapper = CircuitWrapper(circuit) :> ICircuit"
printfn ""
printfn " // Convert to IonQ JSON format"
printfn " match convertCircuitToProviderFormat wrapper \"ionq.simulator\" with"
printfn " | Ok ionqJson ->"
printfn " printfn \"IonQ JSON: %s\" ionqJson"
printfn " | Error msg ->"
printfn " printfn \"Error: %s\" msg"
printfn ""
printfn " // Convert to Rigetti Quil format"
printfn " match convertCircuitToProviderFormat wrapper \"rigetti.sim.qvm\" with"
printfn " | Ok quilProgram ->"
printfn " printfn \"Rigetti Quil: %s\" quilProgram"
printfn " | Error msg ->"
printfn " printfn \"Error: %s\" msg"
printfn ""
printfn "Features:"
printfn " ✅ Automatic provider detection from target ID"
printfn " ✅ Gate transpilation for backend compatibility"
printfn " ✅ Support for CircuitWrapper and QaoaCircuitWrapper"
printfn " ✅ IonQ and Rigetti providers (Quantinuum coming soon)"
printfn ""
printfn "========================================="
printfn "Example 7: SDK Backend - Full Integration (NEW!)"
printfn "=========================================\n"
printfn "Use SDK backend for complete Azure Quantum integration:\n"
printfn "Code example:"
printfn ""
printfn " // Step 1: Create workspace"
printfn " use workspace = createDefault \"sub-id\" \"rg\" \"ws-name\" \"eastus\""
printfn ""
printfn " // Step 2: Create SDK backend"
printfn " open FSharp.Azure.Quantum.Core.BackendAbstraction"
printfn " let backend = createFromWorkspace workspace \"ionq.simulator\""
printfn ""
printfn " // Step 3: Build a circuit"
printfn " open FSharp.Azure.Quantum.Core.Circuits"
printfn " let circuit = quantumCircuit {"
printfn " H 0"
printfn " CNOT 0 1"
printfn " MEASURE_ALL"
printfn " }"
printfn ""
printfn " let wrapper = CircuitWrapper(circuit) :> ICircuit"
printfn ""
printfn " // Step 4: Execute on Azure Quantum"
printfn " match backend.Execute wrapper 1000 with"
printfn " | Ok result ->"
printfn " printfn \"✅ Job completed!\""
printfn " printfn \" Backend: %s\" result.BackendName"
printfn " printfn \" Shots: %d\" result.NumShots"
printfn " printfn \" Job ID: %s\" (result.Metadata.[\"job_id\"] :?> string)"
printfn " // Analyze measurements"
printfn " let counts = result.Measurements |> Array.countBy id"
printfn " counts |> Array.iter (fun (bitstring, count) ->"
printfn " printfn \" %A: %d times\" bitstring count)"
printfn " | Error msg ->"
printfn " printfn \"❌ Execution failed: %s\" msg"
printfn ""
printfn "SDK Backend Features:"
printfn " ✅ Full job lifecycle: submit → poll → retrieve results"
printfn " ✅ Automatic circuit format conversion (IonQ/Rigetti)"
printfn " ✅ Exponential backoff polling (1s → 30s max)"
printfn " ✅ Rich metadata: job_id, provider, target, status"
printfn " ✅ Histogram parsing and measurement extraction"
printfn " ✅ IDisposable workspace for proper resource cleanup"
printfn ""
printfn "========================================="
printfn "Example 8: Backend Comparison - HTTP vs SDK"
printfn "=========================================\n"
printfn "Three backend options available:\n"
printfn "1️⃣ Local Simulator Backend"
printfn " let backend = createLocalBackend()"
printfn " • ✅ Fast (milliseconds)"
printfn " • ✅ No Azure account needed"
printfn " • ⚠️ Limited to 20 qubits"
printfn " • ⚠️ No real quantum hardware"
printfn ""
printfn "2️⃣ HTTP Backend (Recommended for production)"
printfn " use httpClient = new HttpClient()"
printfn " let backend = createIonQBackend httpClient workspaceUrl \"ionq.simulator\""
printfn " • ✅ Production-proven (used by existing algorithms)"
printfn " • ✅ Direct REST API control"
printfn " • ✅ Lower-level error handling"
printfn " • ⚠️ Manual job lifecycle management"
printfn ""
printfn "3️⃣ SDK Backend (NEW - Full Integration)"
printfn " use workspace = createDefault \"sub\" \"rg\" \"ws\" \"eastus\""
printfn " let backend = createFromWorkspace workspace \"ionq.simulator\""
printfn " • ✅ Full Azure Quantum integration"
printfn " • ✅ Quota checking and provider discovery"
printfn " • ✅ Automatic job polling with backoff"
printfn " • ✅ IDisposable resource management"
printfn " • ⚠️ Requires Microsoft.Azure.Quantum.Client SDK"
printfn ""
printfn "When to use each:"
printfn " • Local: Development, testing, small circuits (<20 qubits)"
printfn " • HTTP: Production workloads, proven stability, manual control"
printfn " • SDK: Full workspace features, quota management, easier setup"
printfn ""
printfn "========================================="
printfn "Example 9: SDK Backend with Quota Check"
printfn "=========================================\n"
printfn "Check quota before execution to avoid surprise costs:\n"
printfn "Code example:"
printfn ""
printfn " async {"
printfn " // Check quota first"
printfn " let! quota = workspace.GetTotalQuotaAsync()"
printfn " "
printfn " match quota.Remaining with"
printfn " | Some remaining when remaining < 10.0 ->"
printfn " printfn \"⚠️ Low quota: %.2f credits\" remaining"
printfn " printfn \"Stopping execution\""
printfn " | Some remaining ->"
printfn " printfn \"✅ Quota available: %.2f credits\" remaining"
printfn " "
printfn " // Create backend and execute"
printfn " let backend = createFromWorkspace workspace \"ionq.simulator\""
printfn " match backend.Execute circuit 1000 with"
printfn " | Ok result -> printfn \"Success!\""
printfn " | Error msg -> printfn \"Error: %s\" msg"
printfn " | None ->"
printfn " printfn \"✅ Unlimited quota\""
printfn " let backend = createFromWorkspace workspace \"ionq.simulator\""
printfn " // Execute..."
printfn " } |> Async.RunSynchronously"
printfn ""
printfn "Best Practice Pattern:"
printfn " 1. Check quota before execution"
printfn " 2. Estimate cost (shots × circuit_complexity)"
printfn " 3. Execute only if sufficient quota"
printfn " 4. Monitor remaining quota after execution"
printfn ""
printfn "========================================="
printfn "Next Steps"
printfn "=========================================\n"
printfn "1. Set up Azure Quantum workspace:"
printfn " https://docs.microsoft.com/azure/quantum/"
printfn ""
printfn "2. Get your credentials from Azure Portal"
printfn ""
printfn "3. Choose your backend approach:"
printfn " • Local: createLocalBackend() - for testing"
printfn " • HTTP: createIonQBackend(...) - for production (recommended)"
printfn " • SDK: createFromWorkspace(...) - for full integration (new!)"
printfn ""
printfn "4. Start building quantum circuits:"
printfn " See examples/CircuitBuilder/QuantumCircuits.fsx"
printfn ""