libket 0.7.0

Runtime library for the Ket programming language
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// SPDX-FileCopyrightText: 2026 Evandro Chagas Ribeiro da Rosa <evandro@quantuloop.com>
//
// SPDX-License-Identifier: Apache-2.0

#![allow(clippy::missing_safety_doc, clippy::not_unsafe_ptr_arg_deref)]

//! C API for interacting with `Process` operations.

use std::ffi::{c_char, CStr, CString};

use crate::{
    c_api::{c_error, c_ok},
    error::KetError,
    ir::{block::BasicBlock, gate::Param, hamiltonian::Hamiltonian},
    process::{Process, ProcessState, QPUConfig},
};

/// Allocates a new [`Process`] using the provided QPU configuration.
///
/// `qpu_config` is consumed by this call: ownership is transferred to the
/// newly created `Process` and the pointer must not be used afterwards.
///
/// # Parameters
/// - `qpu_config`: Pointer to a [`QPUConfig`].
/// - `process`: Output: receives the pointer to the newly allocated
///   [`Process`]. Must eventually be freed with [`ket_process_delete`].
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_new(qpu_config: *mut QPUConfig, process: &mut *mut Process) -> i32 {
    let qpu_config = unsafe { *Box::from_raw(qpu_config) };
    *process = Box::into_raw(Box::new(Process::new(qpu_config)));
    c_ok()
}

/// Allocates a new [`QPUConfig`] for a QPU with the specified number of physical qubits.
///
/// The newly created configuration has **no execution backend** attached. A
/// `QuantumExecution` backend must be set (via `ket_quantum_execution_live`
/// or `ket_quantum_execution_batch`) before passing the config to
/// [`ket_process_new`].
///
/// # Parameters
/// - `num_qubits`: The number of physical qubits available on the QPU.
/// - `qpu_config`: Output: receives the pointer to the newly allocated
///   [`QPUConfig`]. Ownership is transferred to the caller until it is
///   consumed by [`ket_process_new`].
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_config_new(num_qubits: usize, qpu_config: &mut *mut QPUConfig) -> i32 {
    *qpu_config = Box::into_raw(Box::new(QPUConfig {
        num_qubits,
        quantum_execution: None,
    }));
    c_ok()
}

/// Deallocates the memory associated with a [`Process`].
///
/// # Parameters
/// - `process`: Pointer to the [`Process`] to free.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_delete(process: *mut Process) -> i32 {
    unsafe {
        let _ = Box::from_raw(process);
    }
    c_ok()
}

/// Allocates a new logical qubit in the process.
///
/// Returns an error if the process is in a state that does not accept new
/// qubits (e.g., `ProcessTerminated`) or if the QPU qubit limit has been
/// reached (`QubitLimitExceeded`).
///
/// # Parameters
/// - `process`: The process in which the qubit is allocated.
/// - `qubit`: Output: receives the index of the newly allocated logical qubit.
///
/// # Returns
/// `0` on success, non-zero error code on failure (including
/// `ProcessTerminated` and `QubitLimitExceeded`).
#[no_mangle]
pub extern "C" fn ket_process_alloc(process: &mut Process, qubit: &mut usize) -> i32 {
    *qubit = c_error!(process.alloc());
    c_ok()
}

/// Appends a [`BasicBlock`] of gates to the process.
///
/// The `block` is **consumed** by this call and must not be used afterwards.
/// Returns an error if the process state does not allow gate appending
/// (`GateAppendForbidden`) or if a qubit index referenced in the block is
/// out of range (`QubitIndexOutOfRange`).
///
/// # Parameters
/// - `process`: The process to which the block is appended.
/// - `block`: The block to consume and append. Ownership is transferred.
///
/// # Returns
/// `0` on success, non-zero error code on failure (including
/// `GateAppendForbidden` and `QubitIndexOutOfRange`).
#[no_mangle]
pub extern "C" fn ket_process_append_block(process: &mut Process, block: *mut BasicBlock) -> i32 {
    let block = unsafe { *Box::from_raw(block) };
    c_error(process.append_block(block))
}

/// Returns the accumulated gate instructions of the process as a JSON string.
///
/// The returned string is a JSON array of gate instruction objects representing
/// the gates in the process's main block. The string is heap-allocated and the
/// caller **must** free it with [`super::ket_string_delete`].
///
/// # Parameters
/// - `process`: The process whose gate list is serialized.
/// - `block`: Output: set to a pointer to a heap-allocated null-terminated
///   JSON string.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_gates_json(process: &Process, block: &mut *mut c_char) -> i32 {
    *block = to_json!(&process.main_block().gates).into_raw();
    c_ok()
}

/// Performs a single-shot mid-circuit measurement of `qubits`.
///
/// This function is only valid in **live mode**. Any gates accumulated since
/// the last measurement are dispatched to the backend before the measurement
/// is performed.
///
/// # Parameters
/// - `process`: The process on which the measurement is performed.
/// - `qubits`: Pointer to an array of qubit indices to measure.
/// - `qubits_len`: Number of elements in `qubits`.
/// - `result`: Output: the measurement result encoded as a bitmask
///   (bit `i` corresponds to `qubits[i]`).
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_measure(
    process: &mut Process,
    qubits: *const usize,
    qubits_len: usize,
    result: &mut u64,
) -> i32 {
    let qubits = unsafe { std::slice::from_raw_parts(qubits, qubits_len) };
    *result = c_error!(process.measure(qubits));
    c_ok()
}

/// Dumps the quantum state of `qubits` (live mode only).
///
/// Returns the full probability amplitude vector for the specified qubits as a
/// heap-allocated JSON string. The caller **must** free it with
/// [`super::ket_string_delete`].
///
/// # Parameters
/// - `process`: The process whose state is dumped.
/// - `qubits`: Pointer to an array of qubit indices to dump.
/// - `qubits_len`: Number of elements in `qubits`.
/// - `dump_json`: Output: set to a pointer to a heap-allocated
///   null-terminated JSON string encoding the quantum state.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_dump(
    process: &mut Process,
    qubits: *const usize,
    qubits_len: usize,
    dump_json: &mut *const c_char,
) -> i32 {
    let qubits = unsafe { std::slice::from_raw_parts(qubits, qubits_len) };
    *dump_json = to_json!(&c_error!(process.dump(qubits))).into_raw();

    c_ok()
}

/// Requests a measurement sample of `qubits` over `shots` repetitions.
///
/// In **live mode**, the circuit is executed immediately and the result is
/// returned as a heap-allocated JSON string (caller must free with
/// [`super::ket_string_delete`]). In **batch mode**, the request is recorded for the
/// next [`ket_process_execute`] call and `*sample_json` is set to a JSON
/// `null` string; the actual data becomes available after execution and can be
/// retrieved with [`ket_process_read_sample`].
///
/// # Parameters
/// - `process`: The process on which the sample is requested.
/// - `qubits`: Pointer to an array of qubit indices to sample.
/// - `qubits_len`: Number of elements in `qubits`.
/// - `shots`: Number of repetitions.
/// - `sample_json`: Output: set to a pointer to a heap-allocated
///   null-terminated JSON string (caller must free with [`super::ket_string_delete`]).
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_sample(
    process: &mut Process,
    qubits: *const usize,
    qubits_len: usize,
    shots: usize,
    sample_json: &mut *const c_char,
) -> i32 {
    let qubits = unsafe { std::slice::from_raw_parts(qubits, qubits_len) };
    *sample_json = to_json!(&c_error!(process.sample(qubits, shots))).into_raw();
    c_ok()
}

/// Returns a serialized JSON array of expectation values from the most recent execution.
///
/// If no execution has been performed yet, the returned JSON string contains
/// `null`. The string is heap-allocated; the caller **must** free it with
/// [`super::ket_string_delete`].
///
/// # Parameters
/// - `process`: The process from which expectation values are read.
/// - `result_json`: Output: set to a pointer to a heap-allocated
///   null-terminated JSON string.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_read_exp_value(
    process: &Process,
    result_json: &mut *const c_char,
) -> i32 {
    *result_json = to_json!(&process.read_exp_value()).into_raw();
    c_ok()
}

/// Returns a serialized JSON array of parameter-shift gradients from the most recent execution.
///
/// If no execution has been performed yet, the returned JSON string contains
/// `null`. The string is heap-allocated; the caller **must** free it with
/// [`super::ket_string_delete`].
///
/// # Parameters
/// - `process`: The process from which gradients are read.
/// - `result_json`: Output: set to a pointer to a heap-allocated
///   null-terminated JSON string.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_read_gradient(
    process: &Process,
    result_json: &mut *const c_char,
) -> i32 {
    *result_json = to_json!(&process.read_gradient()).into_raw();
    c_ok()
}

/// Registers a new differentiable parameter with the given initial value.
///
/// The returned `param_index` uniquely identifies this parameter within the
/// process. Use it to construct `Param::Ref` values when building
/// parameterised gate instructions. When the parameter value changes between
/// executions, gates that reference the same index are automatically updated
/// during the next compilation pass.
///
/// # Parameters
/// - `process`: The process in which the parameter is registered.
/// - `param`: The initial numeric value of the parameter.
/// - `param_index`: Output: receives the index that identifies this parameter
///   within the process.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_param(
    process: &mut Process,
    param: f64,
    param_index: &mut usize,
) -> i32 {
    let param = process.param(param);
    if let Param::Ref { index, .. } = param {
        *param_index = index;
    }
    c_ok()
}

/// Compiles and executes the accumulated circuit.
///
/// This is the primary entry point for **batch mode** execution. Calling it in
/// live mode returns an `ExplicitExecuteInLiveMode` error. If no pending
/// measurement or expectation-value requests have been recorded,
/// `NoPendingMeasurement` is returned. If the process is already in the
/// `Terminated` state, this call is idempotent and returns success.
///
/// # Parameters
/// - `process`: The process to compile and execute.
///
/// # Returns
/// `0` on success, non-zero error code on failure (including
/// `NoPendingMeasurement` and `ExplicitExecuteInLiveMode`).
#[no_mangle]
pub extern "C" fn ket_process_execute(process: &mut Process) -> i32 {
    c_error(process.execute())
}

/// Reads the cached sample data from a [`Process`].
///
/// Returns the sample counts recorded during the most recent execution as a
/// heap-allocated JSON string. If no execution has been performed yet, the
/// returned JSON string contains `null`. The caller **must** free the string
/// with [`super::ket_string_delete`].
///
/// # Parameters
/// - `process`: The process from which sample data is read.
/// - `sample_json`: Output: set to a pointer to a heap-allocated
///   null-terminated JSON string.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_read_sample(
    process: &mut Process,
    sample_json: &mut *const c_char,
) -> i32 {
    *sample_json = to_json!(&process.read_sample()).into_raw();

    c_ok()
}

/// Requests the expectation value computation for a given [`Hamiltonian`] (passed as JSON) on a [`Process`].
///
/// In **live mode**, the expectation value is computed immediately:
/// `*some_result` is set to `true` and the value is written to `*result`.
/// In **batch mode**, the request is recorded for the next
/// [`ket_process_execute`] call: `*some_result` is set to `false` and
/// `*result` is left unmodified until execution completes and
/// [`ket_process_read_exp_value`] is called.
///
/// # Parameters
/// - `process`: The process on which the expectation value is computed.
/// - `hamiltonian_json`: A null-terminated JSON string encoding the
///   Hamiltonian.
/// - `result`: Output: the computed expectation value (valid only when
///   `*some_result` is `true`).
/// - `some_result`: Output: set to `true` if the expectation value was
///   computed immediately (live mode), or `false` if the request was
///   deferred (batch mode).
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_exp_value(
    process: &mut Process,
    hamiltonian_json: *const c_char,
    result: &mut f64,
    some_result: &mut bool,
) -> i32 {
    let hamiltonian = from_json!(hamiltonian_json, Hamiltonian);
    match c_error!(process.exp_value(hamiltonian)) {
        Some(value) => {
            *result = value;
            *some_result = true;
        }
        None => {
            *some_result = false;
        }
    }
    c_ok()
}

/// Converts a [`ProcessState`] into the corresponding static C string.
///
/// Maps each variant to a null-terminated `&'static CStr`:
/// - [`ProcessState::AcceptingGate`] → `"AcceptingGate"`
/// - [`ProcessState::AcceptingHamiltonian`] → `"AcceptingHamiltonian"`
/// - [`ProcessState::ReadyToExecute`] → `"ReadyToExecute"`
/// - [`ProcessState::Terminated`] → `"Terminated"`
///
/// The returned pointer is valid for the lifetime of the program and must
/// **not** be freed.
impl From<ProcessState> for &'static CStr {
    fn from(value: ProcessState) -> Self {
        match value {
            ProcessState::AcceptingGate => c"AcceptingGate",
            ProcessState::AcceptingHamiltonian => c"AcceptingHamiltonian",
            ProcessState::ReadyToExecute => c"ReadyToExecute",
            ProcessState::Terminated => c"Terminated",
        }
    }
}

/// Returns the current status of the process as a static C string.
///
/// The string is one of:
/// - `"AcceptingGate"`: the process is ready to accept gate blocks.
/// - `"AcceptingHamiltonian"`: all gates have been appended; expectation-value
///   requests can now be submitted.
/// - `"ReadyToExecute"`: execution has been requested and the circuit is ready.
/// - `"Terminated"`: execution has completed and results are available.
///
/// The returned pointer points to a static string and must **not** be freed.
///
/// # Parameters
/// - `process`: The process whose status is queried.
/// - `status`: Output: set to a pointer to a static null-terminated string.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_status(process: &Process, status: &mut *const c_char) -> i32 {
    let process_status: &CStr = process.status().into();
    *status = process_status.as_ptr();
    c_ok()
}

/// Registers a new parameter with the given initial value in the process.
///
/// The parameter's index within the process parameter list is written to `index`.
///
/// # Parameters
/// - `process`: The process to register the parameter in.
/// - `value`: The initial value of the parameter.
/// - `index`: Output: set to the registered parameter's index.
///
/// # Returns
/// `0` on success, non-zero error code on failure.
#[no_mangle]
pub extern "C" fn ket_process_set_parameter(
    process: &mut Process,
    value: f64,
    index: &mut usize,
) -> i32 {
    let Param::Ref {
        index: param_index, ..
    } = process.param(value)
    else {
        unreachable!()
    };
    *index = param_index;

    c_ok()
}