I am simulating a surface code where the edges in the syndrome graph change slightly from shot to shot based on erasures that occur in the circuit (i.e. I have a syndrome graph corresponding to the case of no erasures and only Pauli errors and for every shot some of the edges are replaced with edges corresponding to an erasure in that position).

In order to save time, I would like to generate the pymatching.Matching object once and then modify it for every shot, replacing/adding relevant edges.

I had two ideas how to go about this but both cause some issues:

  1. Create a copy.copy of the Matching object. This does not work since a shallow copy does not copy the matching graph and adding an edge to the copy also adds it to the original. copy.deepcopy does not work either, however, since it throws an error (TypeError: cannot pickle 'pymatching._cpp_pymatching.MatchingGraph' object).
    (Additionally: I am not quite sure but I guess this method has the potential to be almost as slow as or even slower than loading the Matching object from a modified stim.DetectorErrorModel every time?)
  2. Before adding an edge, check if that edge already exists and replace the new edges with the original edges after every shot. This does not work, since I cannot find a remove_edge function, which would be necessary if the edge to be added was not in the syndrome graph to begin with.
    A workaround might be to set the weight of this edge to the maximum value (and the probability to 0) but that does not seem very elegant, especially since later shots would potentially have to deal with a steadily growing number of "ghost edges" with maximal weights, that would connect otherwise disjunct parts of the syndrome graph.

Am I missing something? Is there another (reasonably fast) way to get a deepcopy or to completely remove edges from the matching graph?


1 Answer 1


Even if you manage to change the graph from the python API in the way you want, you will just trigger a complete internal recreation of the C++ data structures used for decoding. Pymatching is just currently not set up for small edits to be efficient.

I think the easiest way to do what you want, without it being horribly slow, is to edit the C++ code. Something like this:

  1. Clone the C++ code from https://github.com/oscarhiggott/PyMatching

  2. Follow the developer documentation to get the C++ code building on your machine (you can use either cmake or bazel)

  3. Add a field original_weights to the DetectorNode class in detector_node.h.

  4. On initial creation of a matcher, copy neighbor_weights into original_weights.

  5. On beginning decoding of a shot, memcpy all original_weights over neighbor_weights and then update neighbor_weights in whatever way you want.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.