idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
229,600
def delete_request ( self , alias , uri , data = None , json = None , params = None , headers = None , allow_redirects = None , timeout = None ) : session = self . _cache . switch ( alias ) data = self . _format_data_according_to_header ( session , data , headers ) redir = True if allow_redirects is None else allow_red...
Send a DELETE request on the session object found using the given alias
229,601
def head_request ( self , alias , uri , headers = None , allow_redirects = None , timeout = None ) : session = self . _cache . switch ( alias ) redir = False if allow_redirects is None else allow_redirects response = self . _head_request ( session , uri , headers , redir , timeout ) logger . info ( 'Head Request using ...
Send a HEAD request on the session object found using the given alias
229,602
def options_request ( self , alias , uri , headers = None , allow_redirects = None , timeout = None ) : session = self . _cache . switch ( alias ) redir = True if allow_redirects is None else allow_redirects response = self . _options_request ( session , uri , headers , redir , timeout ) logger . info ( 'Options Reques...
Send an OPTIONS request on the session object found using the given alias
229,603
def _get_url ( self , session , uri ) : url = session . url if uri : slash = '' if uri . startswith ( '/' ) else '/' url = "%s%s%s" % ( session . url , slash , uri ) return url
Helper method to get the full url
229,604
def _json_pretty_print ( self , content ) : temp = json . loads ( content ) return json . dumps ( temp , sort_keys = True , indent = 4 , separators = ( ',' , ': ' ) )
Pretty print a JSON object
229,605
def get_measurements ( self , measurement = 'Weight' , lower_bound = None , upper_bound = None ) : if upper_bound is None : upper_bound = datetime . date . today ( ) if lower_bound is None : lower_bound = upper_bound - datetime . timedelta ( days = 30 ) if lower_bound > upper_bound : lower_bound , upper_bound = upper_b...
Returns measurements of a given name between two dates .
229,606
def set_measurements ( self , measurement = 'Weight' , value = None ) : if value is None : raise ValueError ( "Cannot update blank value." ) document = self . _get_document_for_url ( self . _get_url_for_measurements ( ) ) measurement_ids = self . _get_measurement_ids ( document ) if measurement not in measurement_ids ....
Sets measurement for today s date .
229,607
def get_measurement_id_options ( self ) : document = self . _get_document_for_url ( self . _get_url_for_measurements ( ) ) measurement_ids = self . _get_measurement_ids ( document ) return measurement_ids
Returns list of measurement choices .
229,608
def file_supports_color ( file_obj ) : plat = sys . platform supported_platform = plat != 'Pocket PC' and ( plat != 'win32' or 'ANSICON' in os . environ ) is_a_tty = file_is_a_tty ( file_obj ) return ( supported_platform and is_a_tty )
Returns True if the running system s terminal supports color .
229,609
def load_report ( identifier = None ) : path = os . path . join ( report_dir ( ) , identifier + '.pyireport' ) return ProfilerSession . load ( path )
Returns the session referred to by identifier
229,610
def save_report ( session ) : previous_reports = glob . glob ( os . path . join ( report_dir ( ) , '*.pyireport' ) ) previous_reports . sort ( reverse = True ) while len ( previous_reports ) > 10 : report_file = previous_reports . pop ( ) os . remove ( report_file ) identifier = time . strftime ( '%Y-%m-%dT%H-%M-%S' , ...
Saves the session to a temp file and returns that path . Also prunes the number of reports to 10 so there aren t loads building up .
229,611
def root_frame ( self , trim_stem = True ) : root_frame = None frame_stack = [ ] for frame_tuple in self . frame_records : identifier_stack = frame_tuple [ 0 ] time = frame_tuple [ 1 ] for stack_depth , frame_identifier in enumerate ( identifier_stack ) : if stack_depth < len ( frame_stack ) : if frame_identifier != fr...
Parses the internal frame records and returns a tree of Frame objects
229,612
def remove_from_parent ( self ) : if self . parent : self . parent . _children . remove ( self ) self . parent . _invalidate_time_caches ( ) self . parent = None
Removes this frame from its parent and nulls the parent link
229,613
def add_child ( self , frame , after = None ) : frame . remove_from_parent ( ) frame . parent = self if after is None : self . _children . append ( frame ) else : index = self . _children . index ( after ) + 1 self . _children . insert ( index , frame ) self . _invalidate_time_caches ( )
Adds a child frame updating the parent link . Optionally insert the frame in a specific position by passing the frame to insert this one after .
229,614
def add_children ( self , frames , after = None ) : if after is not None : for frame in reversed ( frames ) : self . add_child ( frame , after = after ) else : for frame in frames : self . add_child ( frame )
Convenience method to add multiple frames at once .
229,615
def file_path_short ( self ) : if not hasattr ( self , '_file_path_short' ) : if self . file_path : result = None for path in sys . path : try : candidate = os . path . relpath ( self . file_path , path ) except ValueError : continue if not result or ( len ( candidate . split ( os . sep ) ) < len ( result . split ( os ...
Return the path resolved against the closest entry in sys . path
229,616
def exit_frames ( self ) : if self . _exit_frames is None : exit_frames = [ ] for frame in self . frames : if any ( c . group != self for c in frame . children ) : exit_frames . append ( frame ) self . _exit_frames = exit_frames return self . _exit_frames
Returns a list of frames whose children include a frame outside of the group
229,617
def first_interesting_frame ( self ) : root_frame = self . root_frame ( ) frame = root_frame while len ( frame . children ) <= 1 : if frame . children : frame = frame . children [ 0 ] else : return root_frame return frame
Traverse down the frame hierarchy until a frame is found with more than one child
229,618
def aggregate_repeated_calls ( frame , options ) : if frame is None : return None children_by_identifier = { } for child in frame . children : if child . identifier in children_by_identifier : aggregate_frame = children_by_identifier [ child . identifier ] aggregate_frame . self_time += child . self_time if child . chi...
Converts a timeline into a time - aggregate summary .
229,619
def merge_consecutive_self_time ( frame , options ) : if frame is None : return None previous_self_time_frame = None for child in frame . children : if isinstance ( child , SelfTimeFrame ) : if previous_self_time_frame : previous_self_time_frame . self_time += child . self_time child . remove_from_parent ( ) else : pre...
Combines consecutive self time frames
229,620
def remove_unnecessary_self_time_nodes ( frame , options ) : if frame is None : return None if len ( frame . children ) == 1 and isinstance ( frame . children [ 0 ] , SelfTimeFrame ) : child = frame . children [ 0 ] frame . self_time += child . self_time child . remove_from_parent ( ) for child in frame . children : re...
When a frame has only one child and that is a self - time frame remove that node since it s unnecessary - it clutters the output and offers no additional information .
229,621
def open_in_browser ( self , session , output_filename = None ) : if output_filename is None : output_file = tempfile . NamedTemporaryFile ( suffix = '.html' , delete = False ) output_filename = output_file . name with codecs . getwriter ( 'utf-8' ) ( output_file ) as f : f . write ( self . render ( session ) ) else : ...
Open the rendered HTML in a webbrowser .
229,622
def run ( self ) : if subprocess . call ( [ 'npm' , '--version' ] ) != 0 : raise RuntimeError ( 'npm is required to build the HTML renderer.' ) self . check_call ( [ 'npm' , 'install' ] , cwd = HTML_RENDERER_DIR ) self . check_call ( [ 'npm' , 'run' , 'build' ] , cwd = HTML_RENDERER_DIR ) self . copy_file ( HTML_RENDER...
compile the JS then run superclass implementation
229,623
def deprecated ( func , * args , ** kwargs ) : warnings . warn ( '{} is deprecated and should no longer be used.' . format ( func ) , DeprecationWarning , stacklevel = 3 ) return func ( * args , ** kwargs )
Marks a function as deprecated .
229,624
def deprecated_option ( option_name , message = '' ) : def caller ( func , * args , ** kwargs ) : if option_name in kwargs : warnings . warn ( '{} is deprecated. {}' . format ( option_name , message ) , DeprecationWarning , stacklevel = 3 ) return func ( * args , ** kwargs ) return decorator ( caller )
Marks an option as deprecated .
229,625
def THUMBNAIL_OPTIONS ( self ) : from django . core . exceptions import ImproperlyConfigured size = self . _setting ( 'DJNG_THUMBNAIL_SIZE' , ( 200 , 200 ) ) if not ( isinstance ( size , ( list , tuple ) ) and len ( size ) == 2 and isinstance ( size [ 0 ] , int ) and isinstance ( size [ 1 ] , int ) ) : raise Improperly...
Set the size as a 2 - tuple for thumbnailed images after uploading them .
229,626
def get_context ( self , name , value , attrs ) : context = super ( NgWidgetMixin , self ) . get_context ( name , value , attrs ) if callable ( getattr ( self . _field , 'update_widget_rendering_context' , None ) ) : self . _field . update_widget_rendering_context ( context ) return context
Some widgets require a modified rendering context if they contain angular directives .
229,627
def errors ( self ) : if not hasattr ( self , '_errors_cache' ) : self . _errors_cache = self . form . get_field_errors ( self ) return self . _errors_cache
Returns a TupleErrorList for this field . This overloaded method adds additional error lists to the errors as detected by the form validator .
229,628
def css_classes ( self , extra_classes = None ) : if hasattr ( extra_classes , 'split' ) : extra_classes = extra_classes . split ( ) extra_classes = set ( extra_classes or [ ] ) field_css_classes = getattr ( self . form , 'field_css_classes' , None ) if hasattr ( field_css_classes , 'split' ) : extra_classes . update (...
Returns a string of space - separated CSS classes for the wrapping element of this input field .
229,629
def get_field_errors ( self , field ) : identifier = format_html ( '{0}[\'{1}\']' , self . form_name , field . name ) errors = self . errors . get ( field . html_name , [ ] ) return self . error_class ( [ SafeTuple ( ( identifier , self . field_error_css_classes , '$pristine' , '$pristine' , 'invalid' , e ) ) for e in ...
Return server side errors . Shall be overridden by derived forms to add their extra errors for AngularJS .
229,630
def update_widget_attrs ( self , bound_field , attrs ) : if bound_field . field . has_subwidgets ( ) is False : widget_classes = getattr ( self , 'widget_css_classes' , None ) if widget_classes : if 'class' in attrs : attrs [ 'class' ] += ' ' + widget_classes else : attrs . update ( { 'class' : widget_classes } ) retur...
Updated the widget attributes which shall be added to the widget when rendering this field .
229,631
def rectify_multipart_form_data ( self , data ) : for name , field in self . base_fields . items ( ) : try : field . implode_multi_values ( name , data ) except AttributeError : pass return data
If a widget was converted and the Form data was submitted through a multipart request then these data fields must be converted to suit the Django Form validation
229,632
def rectify_ajax_form_data ( self , data ) : for name , field in self . base_fields . items ( ) : try : data [ name ] = field . convert_ajax_data ( data . get ( name , { } ) ) except AttributeError : pass return data
If a widget was converted and the Form data was submitted through an Ajax request then these data fields must be converted to suit the Django Form validation
229,633
def djng_locale_script ( context , default_language = 'en' ) : language = get_language_from_request ( context [ 'request' ] ) if not language : language = default_language return format_html ( 'angular-locale_{}.js' , language . lower ( ) )
Returns a script tag for including the proper locale script in any HTML page . This tag determines the current language with its locale .
229,634
def update_widget_attrs ( self , bound_field , attrs ) : bound_field . form . update_widget_attrs ( bound_field , attrs ) widget_classes = self . widget . attrs . get ( 'class' , None ) if widget_classes : if 'class' in attrs : attrs [ 'class' ] += ' ' + widget_classes else : attrs . update ( { 'class' : widget_classes...
Update the dictionary of attributes used while rendering the input widget
229,635
def implode_multi_values ( self , name , data ) : mkeys = [ k for k in data . keys ( ) if k . startswith ( name + '.' ) ] mvls = [ data . pop ( k ) [ 0 ] for k in mkeys ] if mvls : data . setlist ( name , mvls )
Due to the way Angular organizes it model when Form data is sent via a POST request then for this kind of widget the posted data must to be converted into a format suitable for Django s Form validation .
229,636
def convert_ajax_data ( self , field_data ) : data = [ key for key , val in field_data . items ( ) if val ] return data
Due to the way Angular organizes it model when this Form data is sent using Ajax then for this kind of widget the sent data has to be converted into a format suitable for Django s Form validation .
229,637
def process_request ( self , request ) : if request . path == self . ANGULAR_REVERSE : url_name = request . GET . get ( 'djng_url_name' ) url_args = request . GET . getlist ( 'djng_url_args' , [ ] ) url_kwargs = { } url_args = filter ( lambda x : x , url_args ) for param in request . GET : if param . startswith ( 'djng...
Reads url name args kwargs from GET parameters reverses the url and resolves view function Returns the result of resolved view function called with provided args and kwargs Since the view function is called directly it isn t ran through middlewares so the middlewares must be added manually The final result is exactly t...
229,638
def ng_delete ( self , request , * args , ** kwargs ) : if 'pk' not in request . GET : raise NgMissingParameterError ( "Object id is required to delete." ) obj = self . get_object ( ) response = self . build_json_response ( obj ) obj . delete ( ) return response
Delete object and return it s data in JSON encoding The response is build before the object is actually deleted so that we can still retrieve a serialization in the response even with a m2m relationship
229,639
def _post_clean ( self ) : super ( NgModelFormMixin , self ) . _post_clean ( ) if self . _errors and self . prefix : self . _errors = ErrorDict ( ( self . add_prefix ( name ) , value ) for name , value in self . _errors . items ( ) )
Rewrite the error dictionary so that its keys correspond to the model fields .
229,640
def percentage ( self ) : if self . max_value is None or self . max_value is base . UnknownLength : return None elif self . max_value : todo = self . value - self . min_value total = self . max_value - self . min_value percentage = todo / total else : percentage = 1 return percentage * 100
Return current percentage returns None if no max_value is given
229,641
def example ( fn ) : @ functools . wraps ( fn ) def wrapped ( ) : try : sys . stdout . write ( 'Running: %s\n' % fn . __name__ ) fn ( ) sys . stdout . write ( '\n' ) except KeyboardInterrupt : sys . stdout . write ( '\nSkipping example.\n\n' ) time . sleep ( 0.2 ) examples . append ( wrapped ) return wrapped
Wrap the examples so they generate readable output
229,642
def load_stdgraphs ( size : int ) -> List [ nx . Graph ] : from pkg_resources import resource_stream if size < 6 or size > 32 : raise ValueError ( 'Size out of range.' ) filename = 'datasets/data/graph{}er100.g6' . format ( size ) fdata = resource_stream ( 'quantumflow' , filename ) return nx . read_graph6 ( fdata )
Load standard graph validation sets
229,643
def load_mnist ( size : int = None , border : int = _MNIST_BORDER , blank_corners : bool = False , nums : List [ int ] = None ) -> Tuple [ np . ndarray , np . ndarray , np . ndarray , np . ndarray ] : from keras . datasets import mnist def _filter_mnist ( x : np . ndarray , y : np . ndarray , nums : List [ int ] = None...
Download and rescale the MNIST database of handwritten digits
229,644
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
Covert numpy array to tensorflow tensor
229,645
def inner ( tensor0 : BKTensor , tensor1 : BKTensor ) -> BKTensor : N = rank ( tensor0 ) axes = list ( range ( N ) ) return tf . tensordot ( tf . math . conj ( tensor0 ) , tensor1 , axes = ( axes , axes ) )
Return the inner product between two states
229,646
def graph_cuts ( graph : nx . Graph ) -> np . ndarray : N = len ( graph ) diag_hamiltonian = np . zeros ( shape = ( [ 2 ] * N ) , dtype = np . double ) for q0 , q1 in graph . edges ( ) : for index , _ in np . ndenumerate ( diag_hamiltonian ) : if index [ q0 ] != index [ q1 ] : weight = graph [ q0 ] [ q1 ] . get ( 'weig...
For the given graph return the cut value for all binary assignments of the graph .
229,647
def depth ( self , local : bool = True ) -> int : G = self . graph if not local : def remove_local ( dagc : DAGCircuit ) -> Generator [ Operation , None , None ] : for elem in dagc : if dagc . graph . degree [ elem ] > 2 : yield elem G = DAGCircuit ( remove_local ( self ) ) . graph return nx . dag_longest_path_length (...
Return the circuit depth .
229,648
def components ( self ) -> List [ 'DAGCircuit' ] : comps = nx . weakly_connected_component_subgraphs ( self . graph ) return [ DAGCircuit ( comp ) for comp in comps ]
Split DAGCircuit into independent components
229,649
def zero_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . zeros ( shape = [ 2 ] * N ) ket [ ( 0 , ) * N ] = 1 return State ( ket , qubits )
Return the all - zero state on N qubits
229,650
def w_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . zeros ( shape = [ 2 ] * N ) for n in range ( N ) : idx = np . zeros ( shape = N , dtype = int ) idx [ n ] += 1 ket [ tuple ( idx ) ] = 1 / sqrt ( N ) return State ( ket , qubits )
Return a W state on N qubits
229,651
def ghz_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . zeros ( shape = [ 2 ] * N ) ket [ ( 0 , ) * N ] = 1 / sqrt ( 2 ) ket [ ( 1 , ) * N ] = 1 / sqrt ( 2 ) return State ( ket , qubits )
Return a GHZ state on N qubits
229,652
def random_state ( qubits : Union [ int , Qubits ] ) -> State : N , qubits = qubits_count_tuple ( qubits ) ket = np . random . normal ( size = ( [ 2 ] * N ) ) + 1j * np . random . normal ( size = ( [ 2 ] * N ) ) return State ( ket , qubits ) . normalize ( )
Return a random state from the space of N qubits
229,653
def join_states ( * states : State ) -> State : vectors = [ ket . vec for ket in states ] vec = reduce ( outer_product , vectors ) return State ( vec . tensor , vec . qubits )
Join two state vectors into a larger qubit state
229,654
def print_state ( state : State , file : TextIO = None ) -> None : state = state . vec . asarray ( ) for index , amplitude in np . ndenumerate ( state ) : ket = "" . join ( [ str ( n ) for n in index ] ) print ( ket , ":" , amplitude , file = file )
Print a state vector
229,655
def print_probabilities ( state : State , ndigits : int = 4 , file : TextIO = None ) -> None : prob = bk . evaluate ( state . probabilities ( ) ) for index , prob in np . ndenumerate ( prob ) : prob = round ( prob , ndigits ) if prob == 0.0 : continue ket = "" . join ( [ str ( n ) for n in index ] ) print ( ket , ":" ,...
Pretty print state probabilities .
229,656
def mixed_density ( qubits : Union [ int , Qubits ] ) -> Density : N , qubits = qubits_count_tuple ( qubits ) matrix = np . eye ( 2 ** N ) / 2 ** N return Density ( matrix , qubits )
Returns the completely mixed density matrix
229,657
def join_densities ( * densities : Density ) -> Density : vectors = [ rho . vec for rho in densities ] vec = reduce ( outer_product , vectors ) memory = dict ( ChainMap ( * [ rho . memory for rho in densities ] ) ) return Density ( vec . tensor , vec . qubits , memory )
Join two mixed states into a larger qubit state
229,658
def normalize ( self ) -> 'State' : tensor = self . tensor / bk . ccast ( bk . sqrt ( self . norm ( ) ) ) return State ( tensor , self . qubits , self . _memory )
Normalize the state
229,659
def sample ( self , trials : int ) -> np . ndarray : probs = np . real ( bk . evaluate ( self . probabilities ( ) ) ) res = np . random . multinomial ( trials , probs . ravel ( ) ) res = res . reshape ( probs . shape ) return res
Measure the state in the computational basis the the given number of trials and return the counts of each output configuration .
229,660
def expectation ( self , diag_hermitian : bk . TensorLike , trials : int = None ) -> bk . BKTensor : if trials is None : probs = self . probabilities ( ) else : probs = bk . real ( bk . astensorproduct ( self . sample ( trials ) / trials ) ) diag_hermitian = bk . astensorproduct ( diag_hermitian ) return bk . sum ( bk ...
Return the expectation of a measurement . Since we can only measure our computer in the computational basis we only require the diagonal of the Hermitian in that basis .
229,661
def measure ( self ) -> np . ndarray : probs = np . real ( bk . evaluate ( self . probabilities ( ) ) ) indices = np . asarray ( list ( np . ndindex ( * [ 2 ] * self . qubit_nb ) ) ) res = np . random . choice ( probs . size , p = probs . ravel ( ) ) res = indices [ res ] return res
Measure the state in the computational basis .
229,662
def asdensity ( self ) -> 'Density' : matrix = bk . outer ( self . tensor , bk . conj ( self . tensor ) ) return Density ( matrix , self . qubits , self . _memory )
Convert a pure state to a density matrix
229,663
def benchmark ( N , gates ) : qubits = list ( range ( 0 , N ) ) ket = qf . zero_state ( N ) for n in range ( 0 , N ) : ket = qf . H ( n ) . run ( ket ) for _ in range ( 0 , ( gates - N ) // 3 ) : qubit0 , qubit1 = random . sample ( qubits , 2 ) ket = qf . X ( qubit0 ) . run ( ket ) ket = qf . T ( qubit1 ) . run ( ket )...
Create and run a circuit with N qubits and given number of gates
229,664
def sandwich_decompositions ( coords0 , coords1 , samples = SAMPLES ) : decomps = [ ] for _ in range ( samples ) : circ = qf . Circuit ( ) circ += qf . CANONICAL ( * coords0 , 0 , 1 ) circ += qf . random_gate ( [ 0 ] ) circ += qf . random_gate ( [ 1 ] ) circ += qf . CANONICAL ( * coords1 , 0 , 1 ) gate = circ . asgate ...
Create composite gates decompose and return a list of canonical coordinates
229,665
def sX ( qubit : Qubit , coefficient : complex = 1.0 ) -> Pauli : return Pauli . sigma ( qubit , 'X' , coefficient )
Return the Pauli sigma_X operator acting on the given qubit
229,666
def sY ( qubit : Qubit , coefficient : complex = 1.0 ) -> Pauli : return Pauli . sigma ( qubit , 'Y' , coefficient )
Return the Pauli sigma_Y operator acting on the given qubit
229,667
def sZ ( qubit : Qubit , coefficient : complex = 1.0 ) -> Pauli : return Pauli . sigma ( qubit , 'Z' , coefficient )
Return the Pauli sigma_Z operator acting on the given qubit
229,668
def pauli_sum ( * elements : Pauli ) -> Pauli : terms = [ ] key = itemgetter ( 0 ) for term , grp in groupby ( heapq . merge ( * elements , key = key ) , key = key ) : coeff = sum ( g [ 1 ] for g in grp ) if not isclose ( coeff , 0.0 ) : terms . append ( ( term , coeff ) ) return Pauli ( tuple ( terms ) )
Return the sum of elements of the Pauli algebra
229,669
def pauli_product ( * elements : Pauli ) -> Pauli : result_terms = [ ] for terms in product ( * elements ) : coeff = reduce ( mul , [ term [ 1 ] for term in terms ] ) ops = ( term [ 0 ] for term in terms ) out = [ ] key = itemgetter ( 0 ) for qubit , qops in groupby ( heapq . merge ( * ops , key = key ) , key = key ) :...
Return the product of elements of the Pauli algebra
229,670
def pauli_pow ( pauli : Pauli , exponent : int ) -> Pauli : if not isinstance ( exponent , int ) or exponent < 0 : raise ValueError ( "The exponent must be a non-negative integer." ) if exponent == 0 : return Pauli . identity ( ) if exponent == 1 : return pauli y = Pauli . identity ( ) x = pauli n = exponent while n > ...
Raise an element of the Pauli algebra to a non - negative integer power .
229,671
def pauli_commuting_sets ( element : Pauli ) -> Tuple [ Pauli , ... ] : if len ( element ) < 2 : return ( element , ) groups : List [ Pauli ] = [ ] for term in element : pterm = Pauli ( ( term , ) ) assigned = False for i , grp in enumerate ( groups ) : if paulis_commute ( grp , pterm ) : groups [ i ] = grp + pterm ass...
Gather the terms of a Pauli polynomial into commuting sets .
229,672
def astensor ( array : TensorLike ) -> BKTensor : array = np . asarray ( array , dtype = CTYPE ) return array
Converts a numpy array to the backend s tensor object
229,673
def productdiag ( tensor : BKTensor ) -> BKTensor : N = rank ( tensor ) tensor = reshape ( tensor , [ 2 ** ( N // 2 ) , 2 ** ( N // 2 ) ] ) tensor = np . diag ( tensor ) tensor = reshape ( tensor , [ 2 ] * ( N // 2 ) ) return tensor
Returns the matrix diagonal of the product tensor
229,674
def tensormul ( tensor0 : BKTensor , tensor1 : BKTensor , indices : typing . List [ int ] ) -> BKTensor : r N = rank ( tensor1 ) K = rank ( tensor0 ) // 2 assert K == len ( indices ) out = list ( EINSUM_SUBSCRIPTS [ 0 : N ] ) left_in = list ( EINSUM_SUBSCRIPTS [ N : N + K ] ) left_out = [ out [ idx ] for idx in indices...
r Generalization of matrix multiplication to product tensors .
229,675
def invert_map ( mapping : dict , one_to_one : bool = True ) -> dict : if one_to_one : inv_map = { value : key for key , value in mapping . items ( ) } else : inv_map = { } for key , value in mapping . items ( ) : inv_map . setdefault ( value , set ( ) ) . add ( key ) return inv_map
Invert a dictionary . If not one_to_one then the inverted map will contain lists of former keys as values .
229,676
def bitlist_to_int ( bitlist : Sequence [ int ] ) -> int : return int ( '' . join ( [ str ( d ) for d in bitlist ] ) , 2 )
Converts a sequence of bits to an integer .
229,677
def int_to_bitlist ( x : int , pad : int = None ) -> Sequence [ int ] : if pad is None : form = '{:0b}' else : form = '{:0' + str ( pad ) + 'b}' return [ int ( b ) for b in form . format ( x ) ]
Converts an integer to a binary sequence of bits .
229,678
def spanning_tree_count ( graph : nx . Graph ) -> int : laplacian = nx . laplacian_matrix ( graph ) . toarray ( ) comatrix = laplacian [ : - 1 , : - 1 ] det = np . linalg . det ( comatrix ) count = int ( round ( det ) ) return count
Return the number of unique spanning trees of a graph using Kirchhoff s matrix tree theorem .
229,679
def rationalize ( flt : float , denominators : Set [ int ] = None ) -> Fraction : if denominators is None : denominators = _DENOMINATORS frac = Fraction . from_float ( flt ) . limit_denominator ( ) if frac . denominator not in denominators : raise ValueError ( 'Cannot rationalize' ) return frac
Convert a floating point number to a Fraction with a small denominator .
229,680
def symbolize ( flt : float ) -> sympy . Symbol : try : ratio = rationalize ( flt ) res = sympy . simplify ( ratio ) except ValueError : ratio = rationalize ( flt / np . pi ) res = sympy . simplify ( ratio ) * sympy . pi return res
Attempt to convert a real number into a simpler symbolic representation .
229,681
def pyquil_to_image ( program : pyquil . Program ) -> PIL . Image : circ = pyquil_to_circuit ( program ) latex = circuit_to_latex ( circ ) img = render_latex ( latex ) return img
Returns an image of a pyquil circuit .
229,682
def circuit_to_pyquil ( circuit : Circuit ) -> pyquil . Program : prog = pyquil . Program ( ) for elem in circuit . elements : if isinstance ( elem , Gate ) and elem . name in QUIL_GATES : params = list ( elem . params . values ( ) ) if elem . params else [ ] prog . gate ( elem . name , params , elem . qubits ) elif is...
Convert a QuantumFlow circuit to a pyQuil program
229,683
def pyquil_to_circuit ( program : pyquil . Program ) -> Circuit : circ = Circuit ( ) for inst in program . instructions : if isinstance ( inst , pyquil . Declare ) : continue if isinstance ( inst , pyquil . Halt ) : continue if isinstance ( inst , pyquil . Pragma ) : continue elif isinstance ( inst , pyquil . Measureme...
Convert a protoquil pyQuil program to a QuantumFlow Circuit
229,684
def quil_to_program ( quil : str ) -> Program : pyquil_instructions = pyquil . parser . parse ( quil ) return pyquil_to_program ( pyquil_instructions )
Parse a quil program and return a Program object
229,685
def state_to_wavefunction ( state : State ) -> pyquil . Wavefunction : amplitudes = state . vec . asarray ( ) amplitudes = amplitudes . transpose ( ) amplitudes = amplitudes . reshape ( [ amplitudes . size ] ) return pyquil . Wavefunction ( amplitudes )
Convert a QuantumFlow state to a pyQuil Wavefunction
229,686
def load ( self , binary : pyquil . Program ) -> 'QuantumFlowQVM' : assert self . status in [ 'connected' , 'done' ] prog = quil_to_program ( str ( binary ) ) self . _prog = prog self . program = binary self . status = 'loaded' return self
Load a pyQuil program and initialize QVM into a fresh state .
229,687
def run ( self ) -> 'QuantumFlowQVM' : assert self . status in [ 'loaded' ] self . status = 'running' self . _ket = self . _prog . run ( ) return self
Run a previously loaded program
229,688
def wavefunction ( self ) -> pyquil . Wavefunction : assert self . status == 'done' assert self . _ket is not None wavefn = state_to_wavefunction ( self . _ket ) return wavefn
Return the wavefunction of a completed program .
229,689
def evaluate ( tensor : BKTensor ) -> TensorLike : if isinstance ( tensor , _DTYPE ) : if torch . numel ( tensor ) == 1 : return tensor . item ( ) if tensor . numel ( ) == 2 : return tensor [ 0 ] . cpu ( ) . numpy ( ) + 1.0j * tensor [ 1 ] . cpu ( ) . numpy ( ) return tensor [ 0 ] . cpu ( ) . numpy ( ) + 1.0j * tensor ...
Return the value of a tensor
229,690
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
Return the number of dimensions of a tensor
229,691
def state_fidelity ( state0 : State , state1 : State ) -> bk . BKTensor : assert state0 . qubits == state1 . qubits tensor = bk . absolute ( bk . inner ( state0 . tensor , state1 . tensor ) ) ** bk . fcast ( 2 ) return tensor
Return the quantum fidelity between pure states .
229,692
def state_angle ( ket0 : State , ket1 : State ) -> bk . BKTensor : return fubini_study_angle ( ket0 . vec , ket1 . vec )
The Fubini - Study angle between states .
229,693
def states_close ( state0 : State , state1 : State , tolerance : float = TOLERANCE ) -> bool : return vectors_close ( state0 . vec , state1 . vec , tolerance )
Returns True if states are almost identical .
229,694
def purity ( rho : Density ) -> bk . BKTensor : tensor = rho . tensor N = rho . qubit_nb matrix = bk . reshape ( tensor , [ 2 ** N , 2 ** N ] ) return bk . trace ( bk . matmul ( matrix , matrix ) )
Calculate the purity of a mixed quantum state .
229,695
def bures_distance ( rho0 : Density , rho1 : Density ) -> float : fid = fidelity ( rho0 , rho1 ) op0 = asarray ( rho0 . asoperator ( ) ) op1 = asarray ( rho1 . asoperator ( ) ) tr0 = np . trace ( op0 ) tr1 = np . trace ( op1 ) return np . sqrt ( tr0 + tr1 - 2. * np . sqrt ( fid ) )
Return the Bures distance between mixed quantum states
229,696
def bures_angle ( rho0 : Density , rho1 : Density ) -> float : return np . arccos ( np . sqrt ( fidelity ( rho0 , rho1 ) ) )
Return the Bures angle between mixed quantum states
229,697
def density_angle ( rho0 : Density , rho1 : Density ) -> bk . BKTensor : return fubini_study_angle ( rho0 . vec , rho1 . vec )
The Fubini - Study angle between density matrices
229,698
def densities_close ( rho0 : Density , rho1 : Density , tolerance : float = TOLERANCE ) -> bool : return vectors_close ( rho0 . vec , rho1 . vec , tolerance )
Returns True if densities are almost identical .
229,699
def entropy ( rho : Density , base : float = None ) -> float : op = asarray ( rho . asoperator ( ) ) probs = np . linalg . eigvalsh ( op ) probs = np . maximum ( probs , 0.0 ) return scipy . stats . entropy ( probs , base = base )
Returns the von - Neumann entropy of a mixed quantum state .