# Copyright 2021-2024 Cambridge Quantum Computing Ltd.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Checkpoint==========Module containing the lambeq checkpoint class."""from__future__importannotationsfromcollections.abcimportIterator,MappingimportosimportpicklefromtypingimportAnyfromlambeq.typingimportStrPathT
[docs]classCheckpoint(Mapping):"""Checkpoint class. Attributes ---------- entries : dict All data, stored as part of the checkpoint. """
[docs]def__init__(self)->None:"""Initialise a :py:class:`Checkpoint`."""self.entries:dict[str,Any]={}
def__len__(self)->int:"""Returns the number of the entries in the checkpoint."""returnlen(self.entries)def__setitem__(self,key:str,value:Any)->None:"""Sets the value in the checkpoint. Parameters ---------- key : str Key under which the data is stored value : Any Value to be stored as part of the checkpoint """self.entries[key]=valuedef__getitem__(self,key:str)->Any:"""Accesses the value in the checkpoint. Parameters ---------- key : str Key under which the data is stored. Raises ------ KeyError If the key does not exist in the checkpoint. """ifkeynotinself.entries:raiseKeyError(f'Key {key} not found in the checkpoint.')returnself.entries[key]def__iter__(self)->Iterator[str]:# pragma: no coverreturnself.entries.__iter__()
[docs]defadd_many(self,values:Mapping[str,Any])->None:"""Adds several values into the checkpoint. Parameters ---------- values : Mapping from str to any The values to be added into the checkpoint. """forkeyiniter(values):self.entries[key]=values[key]
[docs]@classmethoddeffrom_file(cls,path:StrPathT)->Checkpoint:"""Load the checkpoint contents from the file. Parameters ---------- path : str or PathLike Path to the checkpoint file. Raises ------ FileNotFoundError If no file is found at the given path. """checkpoint=cls()ifos.path.exists(path):withopen(path,'rb')asckp:checkpoint.entries=pickle.load(ckp)else:raiseFileNotFoundError('Checkpoint not found! Check path 'f'{path}')returncheckpoint
[docs]defto_file(self,path:StrPathT)->None:"""Save entries to a file and deletes the in-memory copy. Parameters ---------- path : str or PathLike Path to the checkpoint file. """try:withopen(path,'wb+')asckp:pickle.dump(self.entries,ckp)exceptFileNotFoundErrorase:raiseFileNotFoundError('The directory does not exist. Check path `{path}`')fromeself.entries={}