Source code for qurry.process.string_operator.strop_core
"""Post Processing - String Operator - String Operator Core(:mod:`qurry.process.string_operator.strop_core`)"""fromtypingimportUnion,Callable,Literalimportnumpyasnpfrom..availabilityimport(availablility,default_postprocessing_backend,PostProcessingBackendLabel,)from..exceptionsimportPostProcessingRustImportErrortry:from...boorustimportstring_operator# type: ignorestring_operator_core_rust_source=string_operator.string_operator_core_rustRUST_AVAILABLE=TrueFAILED_RUST_IMPORT=NoneexceptImportErroraserr:RUST_AVAILABLE=FalseFAILED_RUST_IMPORT=errdefstring_operator_core_rust_source(*args,**kwargs):"""Dummy function for string_operator_core_rust."""raisePostProcessingRustImportError("Rust is not available, using python to calculate string operator.")fromFAILED_RUST_IMPORTBACKEND_AVAILABLE=availablility("string_operator.strop_core",[("Rust",RUST_AVAILABLE,FAILED_RUST_IMPORT)],)DEFAULT_PROCESS_BACKEND=default_postprocessing_backend(RUST_AVAILABLE,False)add_or_reducer:Callable[[str],Literal[1,-1]]=lambdabitstring:(1ifsum(int(bit)forbitinbitstring)%2==0else-1)"""The add or reduce function.If the sum of the bitstring is even, return 1.If the sum of the bitstring is odd, return -1.Args: bitstring (str): The bitstring.Returns: Literal[1, -1]: 1 or -1."""
[docs]defstring_operator_core(shots:int,counts:list[dict[str,int]],backend:PostProcessingBackendLabel=DEFAULT_PROCESS_BACKEND,)->Union[float,np.float64]:"""The core function of magnet square by Python and Rust. Args: shots (int): Shots of the experiment on quantum machine. counts (list[dict[str, int]]): Counts of the experiment on quantum machine. backend (PostProcessingBackendLabel, optional): Post Processing backend. Defaults to DEFAULT_PROCESS_BACKEND. Returns: Union[float, np.float64]: String operator value. """ifbackend=="Rust":returnstring_operator_core_rust_source(shots,counts)iflen(counts)!=1:raiseValueError(f"counts should be a list of counts with length 1, but got {len(counts)}")only_counts=counts[0]sample_shots=sum(only_counts.values())assertsample_shots==shots,f"shots {shots} does not match sample_shots {sample_shots}"order_per_bitstring_without_div_by_shots={s:add_or_reducer(s)*mfors,minonly_counts.items()}order=sum(order_per_bitstring_without_div_by_shots.values())/sample_shotsreturnorder