-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathProtocolZoo.jl
More file actions
519 lines (453 loc) · 27.6 KB
/
ProtocolZoo.jl
File metadata and controls
519 lines (453 loc) · 27.6 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
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
module ProtocolZoo
using QuantumSavory
import QuantumSavory: get_time_tracker, Tag, isolderthan, onchange
using QuantumSavory: Wildcard, alwaystrue
using QuantumSavory: timestr, compactstr
using QuantumSavory.CircuitZoo: EntanglementSwap, LocalEntanglementSwap, Purify2to1
using DocStringExtensions
using Distributions: Geometric
using ConcurrentSim: Simulation, @yield, timeout, @process, now
import ConcurrentSim: Process
import ResumableFunctions
using ResumableFunctions: @resumable
import SumTypes
using PrettyTables: PrettyTables, pretty_table
export
# protocols
EntanglerProt, SwapperProt, EntanglementTracker, EntanglementConsumer, CutoffProt, BBPSSWProt,
# tags
EntanglementCounterpart, EntanglementHistory, DistilledTag, EntanglementUpdateX, EntanglementUpdateZ,
# from Switches
SimpleSwitchDiscreteProt, SwitchRequest,
# from QTCP
QDatagram, Flow, LinkLevelRequest,
QTCPPairBegin, QTCPPairEnd,
LinkLevelReply, LinkLevelReplyAtHop, LinkLevelReplyAtSource,
NetworkNodeController, EndNodeController, LinkController
abstract type AbstractProtocol end
"""
Check whether a protocol permits virtual edges between nodes.
Virtual edges refer to protocol connections between two nodes that do not correspond
to actual network edges/links. Some protocols like [`EntanglementConsumer`](@ref) can operate
between any two nodes in the network regardless of physical connectivity.
"""
permits_virtual_edge(::AbstractProtocol) = false
get_time_tracker(prot::AbstractProtocol) = prot.sim::Simulation
Process(prot::AbstractProtocol, args...; kwargs...) = Process((e,a...;k...)->prot(a...;k...), get_time_tracker(prot), args...; kwargs...)
"""Display all available background types in QuantumSavory along with their documentation.
The `InteractiveUtils` package must be installed and imported."""
function available_protocol_types end
const QueryArgs = Union{Int,Function,Wildcard}
"""
$TYPEDEF
Indicates the current entanglement status with a remote node's slot. Added when a new entanglement is generated through [`EntanglerProt`](@ref) or when a swap happens and
the [`EntanglementTracker`](@ref) receives an [`EntanglementUpdate`] message.
$TYPEDFIELDS
"""
@kwdef struct EntanglementCounterpart
"the id of the remote node to which we are entangled"
remote_node::Int
"the slot in the remote node containing the qubit we are entangled to"
remote_slot::Int
end
Base.show(io::IO, tag::EntanglementCounterpart) = print(io, "Entangled to $(tag.remote_node).$(tag.remote_slot)")
Tag(tag::EntanglementCounterpart) = Tag(EntanglementCounterpart, tag.remote_node, tag.remote_slot)
"""
$TYPEDEF
This tag is used to store the outdated entanglement information after a
swap. It helps to direct incoming entanglement update messages to the right node after a swap.
It helps in situations when locally we have performed a swap, but we are now receiving a message
from a distant node that does not know yet that the swap has occurred (thus the distant node might
have outdated information about who is entangled to whom and we need to update that information).
$TYPEDFIELDS
"""
@kwdef struct EntanglementHistory
"the id of the remote node we used to be entangled to"
remote_node::Int
"the slot of the remote node we used to be entangled to"
remote_slot::Int
"the id of remote node to which we are entangled after the swap"
swap_remote_node::Int
"the slot of the remote node to which we are entangled after the swap"
swap_remote_slot::Int
"the slot in this register with whom we performed a swap"
swapped_local::Int
end
Base.show(io::IO, tag::EntanglementHistory) = print(io, "Was entangled to $(tag.remote_node).$(tag.remote_slot), but swapped with .$(tag.swapped_local) which was entangled to $(tag.swap_remote_node).$(tag.swap_remote_slot)")
Tag(tag::EntanglementHistory) = Tag(EntanglementHistory, tag.remote_node, tag.remote_slot, tag.swap_remote_node, tag.swap_remote_slot, tag.swapped_local)
"""
$TYPEDEF
This tag arrives as a message from a remote node to which the current node was entangled to update the
entanglement information and apply an `X` correction after the remote node performs an entanglement swap.
$TYPEDFIELDS
"""
@kwdef struct EntanglementUpdateX
"the id of the node to which you were entangled before the swap"
past_local_node::Int
"the slot of the node to which you were entangled before the swap"
past_local_slot::Int
"the slot of your node that we were entangled to"
past_remote_slot::Int
"the id of the node to which you are now entangled after the swap"
new_remote_node::Int
"the slot of the node to which you are now entangled after the swap"
new_remote_slot::Int
"what Pauli correction you need to perform"
correction::Int
end
Base.show(io::IO, tag::EntanglementUpdateX) = print(io, "Update slot .$(tag.past_remote_slot) which used to be entangled to $(tag.past_local_node).$(tag.past_local_slot) to be entangled to $(tag.new_remote_node).$(tag.new_remote_slot) and apply correction Z$(tag.correction)")
Tag(tag::EntanglementUpdateX) = Tag(EntanglementUpdateX, tag.past_local_node, tag.past_local_slot, tag.past_remote_slot, tag.new_remote_node, tag.new_remote_slot, tag.correction)
"""
$TYPEDEF
This tag arrives as a message from a remote node to which the current node was entangled to update the
entanglement information and apply a `Z` correction after the remote node performs an entanglement swap.
$TYPEDFIELDS
"""
@kwdef struct EntanglementUpdateZ
"the id of the node to which you were entangled before the swap"
past_local_node::Int
"the slot of the node to which you were entangled before the swap"
past_local_slot::Int
"the slot of your node that we were entangled to"
past_remote_slot::Int
"the id of the node to which you are now entangled after the swap"
new_remote_node::Int
"the slot of the node to which you are now entangled after the swap"
new_remote_slot::Int
"what Pauli correction you need to perform"
correction::Int
end
Base.show(io::IO, tag::EntanglementUpdateZ) = print(io, "Update slot .$(tag.past_remote_slot) which used to be entangled to $(tag.past_local_node).$(tag.past_local_slot) to be entangled to $(tag.new_remote_node).$(tag.new_remote_slot) and apply correction X$(tag.correction)")
Tag(tag::EntanglementUpdateZ) = Tag(EntanglementUpdateZ, tag.past_local_node, tag.past_local_slot, tag.past_remote_slot, tag.new_remote_node, tag.new_remote_slot, tag.correction)
"""
$TYPEDEF
This tag arrives as a message from a remote node's Cutoff Protocol to which the current node was entangled,
to update the classical metadata of the entangled slot and empty it.
It is also stored at a node to handle incoming `EntanglementUpdate` and `EntanglementDelete` messages.
$TYPEDFIELDS
See also: [`CutoffProt`](@ref)
"""
@kwdef struct EntanglementDelete
"the node that sent the deletion announcement message after they delete their local qubit"
send_node::Int
"the sender's slot containing the decohered qubit"
send_slot::Int
"the node receiving the message for qubit deletion"
rec_node::Int
"the slot containing decohered qubit"
rec_slot::Int
end
Base.show(io::IO, tag::EntanglementDelete) = print(io, "Deleted $(tag.send_node).$(tag.send_slot) which was entangled to $(tag.rec_node).$(tag.rec_slot)")
Tag(tag::EntanglementDelete) = Tag(EntanglementDelete, tag.send_node, tag.send_slot, tag.rec_node, tag.rec_slot)
"""
$TYPEDEF
A protocol that generates entanglement between two nodes.
Whenever a pair of empty slots is available, the protocol locks them
and starts probabilistic attempts to establish entanglement.
$TYPEDFIELDS
"""
@kwdef struct EntanglerProt <: AbstractProtocol
"""time-and-schedule-tracking instance from `ConcurrentSim`"""
sim::Simulation # TODO check that
"""a network graph of registers"""
net::RegisterNet
"""the vertex index of node A"""
nodeA::Int
"""the vertex index of node B"""
nodeB::Int
"""the state being generated (supports symbolic, numeric, noisy, and pure)"""
pairstate::SymQObj = StabilizerState("ZZ XX")
"""success probability of one attempt of entanglement generation"""
success_prob::Float64 = 0.001
"""duration of single entanglement attempt"""
attempt_time::Float64 = 0.001
"""fixed "busy time" duration immediately before starting entanglement generation attempts"""
local_busy_time_pre::Float64 = 0.0
"""fixed "busy time" duration immediately after the a successful entanglement generation attempt"""
local_busy_time_post::Float64 = 0.0
"""how long to wait before retrying to lock qubits if no qubits are available (`nothing` for queuing up)"""
retry_lock_time::Union{Float64,Nothing} = 0.1
"""how many rounds of this protocol to run (`-1` for infinite)"""
rounds::Int = -1
"""maximum number of attempts to make per round (`-1` for infinite)"""
attempts::Int = -1
"""function `Int->Bool` or an integer slot number, specifying the slot to take among available free slots in node A"""
chooseslotA::Union{Int,Function} = alwaystrue
"""function `Int->Bool` or an integer slot number, specifying the slot to take among available free slots in node B"""
chooseslotB::Union{Int,Function} = alwaystrue
"""whether the protocol should find the first available free slots in the nodes to be entangled or check for free slots randomly from the available slots"""
randomize::Bool = false
"""whether the protocol should look for unlocked slots to entangle and lock them during the protocol"""
uselock::Bool = true
"""Repeated rounds of this protocol may lead to monopolizing all slots of a pair of registers, starving or deadlocking other protocols. This field can be used to always leave a minimum number of slots free if there already exists entanglement between the current pair of nodes."""
margin::Int = 0
"""Like `margin`, but it is enforced even when no entanglement has been established yet. Usually smaller than `margin`."""
hardmargin::Int = 0
"""Tag to be added to the entangled qubits or nothing to not add any tag. The created tag will be of the form `tag(remote_node, remote_slot)`, by default `EntanglementCounterpart`."""
tag::Union{DataType,Nothing} = EntanglementCounterpart
end
"""Convenience constructor for specifying `rate` of generation instead of success probability and time"""
function EntanglerProt(sim::Simulation, net::RegisterNet, nodeA::Int, nodeB::Int; rate::Union{Nothing,Float64}=nothing, kwargs...)
if isnothing(rate)
return EntanglerProt(;sim, net, nodeA, nodeB, kwargs...)
else
return EntanglerProt(;sim, net, nodeA, nodeB, kwargs..., success_prob=0.001, attempt_time=0.001/rate)
end
end
EntanglerProt(net::RegisterNet, nodeA::Int, nodeB::Int; kwargs...) = EntanglerProt(get_time_tracker(net), net, nodeA, nodeB; kwargs...)
#TODO """Convenience constructor for specifying `fidelity` of generation instead of success probability and time"""
@resumable function (prot::EntanglerProt)()
rounds = prot.rounds
round = 1
last_a, last_b = nothing, nothing
regA = prot.net[prot.nodeA]
regB = prot.net[prot.nodeB]
while rounds != 0
isentangled = !isnothing(prot.tag) && !isnothing(query(regA, prot.tag, prot.nodeB, ❓; assigned=true))
margin = isentangled ? prot.margin : prot.hardmargin
(; chooseslotA, chooseslotB, randomize, uselock) = prot
a_ = findfreeslot(regA; chooseslot=chooseslotA, randomize=randomize, locked=!uselock, margin=margin)
b_ = findfreeslot(regB; chooseslot=chooseslotB, randomize=randomize, locked=!uselock, margin=margin)
if isnothing(a_) || isnothing(b_)
if isnothing(prot.retry_lock_time)
@debug "$(timestr(prot.sim)) EntanglerProt($(compactstr(regA)), $(compactstr(regB))), round $(round): Failed to find free slots, waiting for changes to tags..."
@yield onchange(regA, Tag) | onchange(regB, Tag)
else
@debug "$(timestr(prot.sim)) EntanglerProt($(compactstr(regA)), $(compactstr(regB))), round $(round): Failed to find free slots, waiting a fixed amount of time..."
@yield timeout(prot.sim, prot.retry_lock_time::Float64)
end
continue
end
# we are now certain that a_ and b_ are not nothing. The compiler is not smart enough to figure this out
# on its own, so we need to tell it explicitly. A new variable name is needed due to @resumable.
a = a_::RegRef
b = b_::RegRef
if uselock
@yield lock(a) & lock(b) # this yield is expected to return immediately
end
@yield timeout(prot.sim, prot.local_busy_time_pre)
attempts = if isone(prot.success_prob)
1
else
rand(Geometric(prot.success_prob))+1
end
if prot.attempts == -1 || prot.attempts >= attempts
@yield timeout(prot.sim, attempts * prot.attempt_time)
initialize!((a,b), prot.pairstate; time=now(prot.sim))
@yield timeout(prot.sim, prot.local_busy_time_post)
# tag local node a with EntanglementCounterpart remote_node_idx_b remote_slot_idx_b
isnothing(prot.tag) || tag!(a, prot.tag, prot.nodeB, b.idx)
last_a = a.idx
# tag local node b with EntanglementCounterpart remote_node_idx_a remote_slot_idx_a
isnothing(prot.tag) || tag!(b, prot.tag, prot.nodeA, a.idx)
last_b = b.idx
@debug "$(timestr(prot.sim)) EntanglerProt($(compactstr(regA)), $(compactstr(regB))), round $(round): Entangled .$(a.idx) and .$(b.idx)"
else
@yield timeout(prot.sim, prot.attempts * prot.attempt_time)
@debug "$(timestr(prot.sim)) EntanglerProt($(compactstr(regA)), $(compactstr(regB))), round $(round): Performed the maximum number of attempts and gave up"
end
if uselock
unlock(a)
unlock(b)
end
rounds==-1 || (rounds -= 1)
round += 1
end
return prot.nodeA, last_a, prot.nodeB, last_b
end
"""
$TYPEDEF
A protocol, running at a given node, listening for messages that indicate something has happened to a remote qubit entangled with one of the local qubits.
$TYPEDFIELDS
"""
@kwdef struct EntanglementTracker <: AbstractProtocol
"""time-and-schedule-tracking instance from `ConcurrentSim`"""
sim::Simulation
"""a network graph of registers"""
net::RegisterNet
"""the vertex of the node where the tracker is working"""
node::Int
end
EntanglementTracker(net::RegisterNet, node::Int) = EntanglementTracker(get_time_tracker(net), net, node)
@resumable function (prot::EntanglementTracker)()
nodereg = prot.net[prot.node]
mb = messagebuffer(prot.net, prot.node)
while true
workwasdone = true # waiting is not enough because we might have multiple rounds of work to do
while workwasdone
workwasdone = false
for (updatetagsymbol, updategate) in ((EntanglementUpdateX, Z), (EntanglementUpdateZ, X), (EntanglementDelete, nothing)) # TODO this is getting ugly. Refactor EntanglementUpdateX and EntanglementUpdateZ to be the same parameterized tag
# look for EntanglementUpdate? or EntanglementDelete message sent to us
if !isnothing(updategate) # EntanglementUpdate
msg = querydelete!(mb, updatetagsymbol, ❓, ❓, ❓, ❓, ❓, ❓)
isnothing(msg) && continue
(src, (_, pastremotenode, pastremoteslotid, localslotid, newremotenode, newremoteslotid, correction)) = msg
else # EntanglementDelete
msg = querydelete!(mb, updatetagsymbol, ❓, ❓, ❓, ❓)
isnothing(msg) && continue
(src, (_, pastremotenode, pastremoteslotid, _, localslotid)) = msg
end
@debug "EntanglementTracker @$(prot.node): Received from $(msg.src).$(msg.tag[3]) | message=`$(msg.tag)` | time=$(now(prot.sim))"
workwasdone = true
localslot = nodereg[localslotid]
# Check if the local slot is still present and believed to be entangled.
# We will need to perform a correction operation due to the swap or a deletion due to the qubit being thrown out,
# but there will be no message forwarding necessary.
@debug "EntanglementTracker @$(prot.node): EntanglementCounterpart requesting lock at $(now(prot.sim))"
@yield lock(localslot)
@debug "EntanglementTracker @$(prot.node): EntanglementCounterpart getting lock at $(now(prot.sim))"
counterpart = querydelete!(localslot, EntanglementCounterpart, pastremotenode, pastremoteslotid)
unlock(localslot)
if !isnothing(counterpart)
# time_before_lock = now(prot.sim)
@yield lock(localslot)
# time_after_lock = now(prot.sim)
# time_before_lock != time_after_lock && @debug "EntanglementTracker @$(prot.node): Needed Δt=$(time_after_lock-time_before_lock) to get a lock"
if !isassigned(localslot)
unlock(localslot)
error("There was an error in the entanglement tracking protocol `EntanglementTracker`. We were attempting to forward a classical message from a node that performed a swap to the remote entangled node. However, on reception of that message it was found that the remote node has lost track of its part of the entangled state although it still keeps a `Tag` as a record of it being present.") # TODO make it configurable whether an error is thrown and plug it into the logging module
end
if !isnothing(updategate) # EntanglementUpdate
# Pauli frame correction gate
if correction==2
apply!(localslot, updategate)
end
if newremotenode != -1 #TODO: this is a bit hacky
# tag local with updated EntanglementCounterpart new_remote_node new_remote_slot_idx
tag!(localslot, EntanglementCounterpart, newremotenode, newremoteslotid)
end
else # EntanglementDelete
traceout!(localslot)
end
unlock(localslot)
continue
end
# If there is nothing still stored locally, check if we have a record of the entanglement being swapped to a different remote node,
# and forward the message to that node.
history = querydelete!(localslot, EntanglementHistory,
pastremotenode, pastremoteslotid, # who we were entangled to (node, slot)
❓, ❓, # who we swapped with (node, slot)
❓) # which local slot used to be entangled with whom we swapped with
if !isnothing(history)
_, _, _, whoweswappedwith_node, whoweswappedwith_slotidx, swappedlocal_slotidx = history.tag
if !isnothing(updategate) # EntanglementUpdate
# Forward the update tag to the swapped node and store a new history tag so that we can forward the next update tag to the new node
tag!(localslot, EntanglementHistory, newremotenode, newremoteslotid, whoweswappedwith_node, whoweswappedwith_slotidx, swappedlocal_slotidx)
@debug "EntanglementTracker @$(prot.node): history=`$(history)` | message=`$msg` | Sending to $(whoweswappedwith_node).$(whoweswappedwith_slotidx)"
msghist = Tag(updatetagsymbol, pastremotenode, pastremoteslotid, whoweswappedwith_slotidx, newremotenode, newremoteslotid, correction)
put!(channel(prot.net, prot.node=>whoweswappedwith_node; permit_forward=true), msghist)
else # EntanglementDelete
# We have a delete message but the qubit was swapped so add a tag and forward to swapped node
@debug "EntanglementTracker @$(prot.node): history=`$(history)` | message=`$msg` | Sending to $(whoweswappedwith_node).$(whoweswappedwith_slotidx)"
msghist = Tag(updatetagsymbol, pastremotenode, pastremoteslotid, whoweswappedwith_node, whoweswappedwith_slotidx)
tag!(localslot, updatetagsymbol, prot.node, localslot.idx, whoweswappedwith_node, whoweswappedwith_slotidx)
put!(channel(prot.net, prot.node=>whoweswappedwith_node; permit_forward=true), msghist)
end
continue
end
# Finally, if there the history of a swap is not present in the log anymore,
# it must be because a delete message was received, and forwarded,
# and the entanglement history was deleted, and replaced with an entanglement delete tag.
if !isnothing(querydelete!(localslot, EntanglementDelete, prot.node, localslot.idx, pastremotenode, pastremoteslotid)) #deletion from both sides of the swap, deletion msg when both qubits of a pair are deleted, or when EU arrives after ED at swap node with two simultaneous swaps and deletion on one side
if !(isnothing(updategate)) # EntanglementUpdate
# to handle a possible delete-swap-swap case, we need to update the EntanglementDelete tag
tag!(localslot, EntanglementDelete, prot.node, localslot.idx, newremotenode, newremoteslotid)
@debug "EntanglementTracker @$(prot.node): message=`$msg` for deleted qubit handled and EntanglementDelete tag updated"
else # EntanglementDelete
# when the message is EntanglementDelete and the slot history also has an EntanglementDelete tag (both qubits were deleted), do nothing
@debug "EntanglementTracker @$(prot.node): message=`$msg` is for a deleted qubit and is thus dropped"
end
continue
end
error("`EntanglementTracker` on node $(prot.node) received a message $(msg) that it does not know how to handle (due to the absence of corresponding `EntanglementCounterpart` or `EntanglementHistory` or `EntanglementDelete` tags). This might have happened due to `CutoffProt` deleting qubits while swaps are happening. Make sure that the retention times in `CutoffProt` are sufficiently larger than the `agelimit` in `SwapperProt`. Otherwise, this is a bug in the protocol and should not happen -- please report an issue at QuantumSavory's repository.")
end
end
@debug "EntanglementTracker @$(prot.node): Starting message wait at $(now(prot.sim)) with MessageBuffer containing: $(mb.buffer)"
@yield onchange(mb)
@debug "EntanglementTracker @$(prot.node): Message wait ends at $(now(prot.sim))"
end
end
"""
$TYPEDEF
A protocol running between two nodes, checking periodically for any entangled pairs between the two nodes and consuming/emptying the qubit slots.
This protocol permits virtual edges, meaning it can operate between any two nodes in the network regardless of whether they are physically connected by an edge.
$FIELDS
"""
@kwdef struct EntanglementConsumer <: AbstractProtocol
"""time-and-schedule-tracking instance from `ConcurrentSim`"""
sim::Simulation
"""a network graph of registers"""
net::RegisterNet
"""the vertex index of node A"""
nodeA::Int
"""the vertex index of node B"""
nodeB::Int
"""time period between successive queries on the nodes (`nothing` for queuing up and waiting for available pairs)"""
period::Union{Float64,Nothing} = 0.1
"""tag type which the consumer is looking for -- the consumer query will be `query(node, EntanglementConsumer.tag, remote_node)` and it will be expected that `remote_node` possesses the symmetric reciprocal tag; defaults to `EntanglementCounterpart`"""
tag::Any = EntanglementCounterpart
"""stores the time and resulting observable from querying nodeA and nodeB for `EntanglementCounterpart`"""
_log::Vector{@NamedTuple{t::Float64, obs1::Float64, obs2::Float64}} = @NamedTuple{t::Float64, obs1::Float64, obs2::Float64}[]
end
function EntanglementConsumer(sim::Simulation, net::RegisterNet, nodeA::Int, nodeB::Int; kwargs...)
return EntanglementConsumer(;sim, net, nodeA, nodeB, kwargs...)
end
function EntanglementConsumer(net::RegisterNet, nodeA::Int, nodeB::Int; kwargs...)
return EntanglementConsumer(get_time_tracker(net), net, nodeA, nodeB; kwargs...)
end
permits_virtual_edge(::EntanglementConsumer) = true
@resumable function (prot::EntanglementConsumer)()
regA = prot.net[prot.nodeA]
regB = prot.net[prot.nodeB]
while true
query1 = query(regA, prot.tag, prot.nodeB, ❓; locked=false, assigned=true) # TODO Need a `querydelete!` dispatch on `Register` rather than using `query` here followed by `untag!` below
if isnothing(query1)
if isnothing(prot.period)
@debug "$(timestr(prot.sim)) EntanglementConsumer($(compactstr(regA)), $(compactstr(regB))): query on first node found no entanglement. Waiting on tag updates in $(compactstr(regA))."
@yield onchange(regA, Tag)
else
@debug "$(timestr(prot.sim)) EntanglementConsumer($(compactstr(regA)), $(compactstr(regB))): query on first node found no entanglement. Waiting a fixed amount of time."
@yield timeout(prot.sim, prot.period::Float64)
end
continue
else
query2 = query(regB, prot.tag, prot.nodeA, query1.slot.idx; locked=false, assigned=true)
if isnothing(query2) # in case EntanglementUpdate hasn't reached the second node yet, but the first node has the EntanglementCounterpart
if isnothing(prot.period)
@debug "$(timestr(prot.sim)) EntanglementConsumer($(compactstr(regA)), $(compactstr(regB))): query on second node found no entanglement (yet...). Waiting on tag updates in $(compactstr(regB))."
@yield onchange(regB, Tag)
else
@debug "$(timestr(prot.sim)) EntanglementConsumer($(compactstr(regA)), $(compactstr(regB))): query on second node found no entanglement (yet...). Waiting a fixed amount of time."
@yield timeout(prot.sim, prot.period::Float64)
end
continue
end
end
q1 = query1.slot
q2 = query2.slot
@yield lock(q1) & lock(q2)
@debug "$(timestr(prot.sim)) EntanglementConsumer($(compactstr(regA)), $(compactstr(regB))): queries successful, consuming entanglement between .$(q1.idx) and .$(q2.idx)"
untag!(q1, query1.id)
untag!(q2, query2.id)
# TODO do we need to add EntanglementHistory or EntanglementDelete and should that be a different EntanglementHistory since the current one is specifically for Swapper
# TODO currently when calculating the observable we assume that EntanglerProt.pairstate is always (|00⟩ + |11⟩)/√2, make it more general for other states
ob1 = real(observable((q1, q2), Z⊗Z))
ob2 = real(observable((q1, q2), X⊗X))
traceout!(regA[q1.idx], regB[q2.idx])
push!(prot._log, (now(prot.sim), ob1, ob2))
unlock(q1)
unlock(q2)
if !isnothing(prot.period)
@yield timeout(prot.sim, prot.period)
end
end
end
include("cutoff.jl")
include("swapping.jl")
include("distillation.jl")
include("switches.jl")
using .Switches
include("qtcp.jl")
using .QTCP
include("show.jl")
end # module