INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns True if the running system's terminal supports color. Borrowed from Django https://github.com/django/django/blob/master/django/core/management/color.py
def file_supports_color(file_obj): """ Returns True if the running system's terminal supports color. Borrowed from Django https://github.com/django/django/blob/master/django/core/management/color.py """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or ...
Returns the session referred to by identifier
def load_report(identifier=None): ''' Returns the session referred to by identifier ''' path = os.path.join( report_dir(), identifier + '.pyireport' ) return ProfilerSession.load(path)
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.
def save_report(session): ''' 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. ''' # prune this folder to contain the last 10 sessions previous_reports = glob.glob(os.path.join(report_dir(), '*.pyireport')) pr...
The first frame when using the command line is always the __main__ function. I want to remove that from the output.
def remove_first_pyinstrument_frame_processor(frame, options): ''' The first frame when using the command line is always the __main__ function. I want to remove that from the output. ''' if frame is None: return None if 'pyinstrument' in frame.file_path and len(frame.children) == 1: ...
Parses the internal frame records and returns a tree of Frame objects
def root_frame(self, trim_stem=True): ''' Parses the internal frame records and returns a tree of Frame objects ''' root_frame = None frame_stack = [] for frame_tuple in self.frame_records: identifier_stack = frame_tuple[0] time = frame_tuple[1]...
Removes this frame from its parent, and nulls the parent link
def remove_from_parent(self): ''' Removes this frame from its parent, and nulls the parent link ''' if self.parent: self.parent._children.remove(self) self.parent._invalidate_time_caches() self.parent = None
The total amount of self time in this frame (including self time recorded by SelfTimeFrame children)
def total_self_time(self): ''' The total amount of self time in this frame (including self time recorded by SelfTimeFrame children) ''' self_time = self.self_time for child in self.children: if isinstance(child, SelfTimeFrame): self_time += chi...
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.
def add_child(self, frame, after=None): ''' 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. ''' frame.remove_from_parent() frame.parent = self if after is None...
Convenience method to add multiple frames at once.
def add_children(self, frames, after=None): ''' Convenience method to add multiple frames at once. ''' if after is not None: # if there's an 'after' parameter, add the frames in reverse so the order is # preserved. for frame in reversed(frames): ...
Return the path resolved against the closest entry in sys.path
def file_path_short(self): """ Return the path resolved against the closest entry in sys.path """ if not hasattr(self, '_file_path_short'): if self.file_path: result = None for path in sys.path: # On Windows, if self.file_path and path are...
Returns a list of frames whose children include a frame outside of the group
def exit_frames(self): ''' Returns a list of frames whose children include a frame outside of the group ''' if self._exit_frames is None: exit_frames = [] for frame in self.frames: if any(c.group != self for c in frame.children): ...
Traverse down the frame hierarchy until a frame is found with more than one child
def first_interesting_frame(self): """ Traverse down the frame hierarchy until a frame is found with more than one child """ root_frame = self.root_frame() frame = root_frame while len(frame.children) <= 1: if frame.children: frame = frame.chi...
Converts a timeline into a time-aggregate summary. Adds together calls along the same call stack, so that repeated calls appear as the same frame. Removes time-linearity - frames are sorted according to total time spent. Useful for outputs that display a summary of execution (e.g. text and html outputs)
def aggregate_repeated_calls(frame, options): ''' Converts a timeline into a time-aggregate summary. Adds together calls along the same call stack, so that repeated calls appear as the same frame. Removes time-linearity - frames are sorted according to total time spent. Useful for outputs that dis...
Combines consecutive 'self time' frames
def merge_consecutive_self_time(frame, options): ''' Combines consecutive 'self time' frames ''' 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: ...
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.
def remove_unnecessary_self_time_nodes(frame, options): ''' 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. ''' if frame is None: return None if len(frame.children) ==...
Remove nodes that represent less than e.g. 1% of the output
def remove_irrelevant_nodes(frame, options, total_time=None): ''' Remove nodes that represent less than e.g. 1% of the output ''' if frame is None: return None if total_time is None: total_time = frame.time() filter_threshold = options.get('filter_threshold', 0.01) for...
decorate(func, caller) decorates a function using a caller.
def decorate(func, caller, extras=()): """ decorate(func, caller) decorates a function using a caller. """ evaldict = dict(_call_=caller, _func_=func) es = '' for i, extra in enumerate(extras): ex = '_e%d_' % i evaldict[ex] = extra es += ex + ', ' fun = FunctionMaker....
Factory of decorators turning a function into a generic function dispatching on the given arguments.
def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on the given arguments. """ assert dispatch_args, 'No dispatch args passed' dispatch_str = '(%s,)' % ', '.join(dispatch_args) def check(arguments, wrong=operator.ne, msg=''): ...
Open the rendered HTML in a webbrowser. If output_filename=None (the default), a tempfile is used. The filename of the HTML file is returned.
def open_in_browser(self, session, output_filename=None): """ Open the rendered HTML in a webbrowser. If output_filename=None (the default), a tempfile is used. The filename of the HTML file is returned. """ if output_filename is None: output_file = tempfil...
compile the JS, then run superclass implementation
def run(self): '''compile the JS, then run superclass implementation''' 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',...
Marks a function as deprecated.
def deprecated(func, *args, **kwargs): ''' Marks a function as deprecated. ''' warnings.warn( '{} is deprecated and should no longer be used.'.format(func), DeprecationWarning, stacklevel=3 ) return func(*args, **kwargs)
Marks an option as deprecated.
def deprecated_option(option_name, message=''): ''' Marks an option as deprecated. ''' def caller(func, *args, **kwargs): if option_name in kwargs: warnings.warn( '{} is deprecated. {}'.format(option_name, message), DeprecationWarning, stacklev...
Set the size as a 2-tuple for thumbnailed images after uploading them.
def THUMBNAIL_OPTIONS(self): """ Set the size as a 2-tuple for thumbnailed images after uploading them. """ from django.core.exceptions import ImproperlyConfigured size = self._setting('DJNG_THUMBNAIL_SIZE', (200, 200)) if not (isinstance(size, (list, tuple)) and len(siz...
Some widgets require a modified rendering context, if they contain angular directives.
def get_context(self, name, value, attrs): """ Some widgets require a modified rendering context, if they contain angular directives. """ context = super(NgWidgetMixin, self).get_context(name, value, attrs) if callable(getattr(self._field, 'update_widget_rendering_context', None)...
Returns a TupleErrorList for this field. This overloaded method adds additional error lists to the errors as detected by the form validator.
def errors(self): """ Returns a TupleErrorList for this field. This overloaded method adds additional error lists to the errors as detected by the form validator. """ if not hasattr(self, '_errors_cache'): self._errors_cache = self.form.get_field_errors(self) ...
Returns a string of space-separated CSS classes for the wrapping element of this input field.
def css_classes(self, extra_classes=None): """ Returns a string of space-separated CSS classes for the wrapping element of this input field. """ if hasattr(extra_classes, 'split'): extra_classes = extra_classes.split() extra_classes = set(extra_classes or []) ...
Renders the field.
def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field. """ if not widget: widget = self.field.widget if DJANGO_VERSION > (1, 10): # so that we can refer to the field when building the rendering context widget....
Return server side errors. Shall be overridden by derived forms to add their extra errors for AngularJS.
def get_field_errors(self, field): """ Return server side errors. Shall be overridden by derived forms to add their extra errors for AngularJS. """ identifier = format_html('{0}[\'{1}\']', self.form_name, field.name) errors = self.errors.get(field.html_name, []) r...
Updated the widget attributes which shall be added to the widget when rendering this field.
def update_widget_attrs(self, bound_field, attrs): """ Updated the widget attributes which shall be added to the widget when rendering this field. """ if bound_field.field.has_subwidgets() is False: widget_classes = getattr(self, 'widget_css_classes', None) if wid...
During form initialization, some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way.
def convert_widgets(self): """ During form initialization, some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way. """ warnings.warn("Will be removed after dropping support for Django-1.10", PendingDeprecationWarning) widgets_module = ...
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
def rectify_multipart_form_data(self, 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 """ for name, field in self.base_fields.items(): try: ...
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
def rectify_ajax_form_data(self, 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 """ for name, field in self.base_fields.items(): try: ...
Determine the kind of input field and create a list of potential errors which may occur during validation of that field. This list is returned to be displayed in '$dirty' state if the field does not validate for that criteria.
def get_field_errors(self, bound_field): """ Determine the kind of input field and create a list of potential errors which may occur during validation of that field. This list is returned to be displayed in '$dirty' state if the field does not validate for that criteria. """ ...
Returns this form rendered as HTML with <div class="form-group">s for each form field.
def as_div(self): """ Returns this form rendered as HTML with <div class="form-group">s for each form field. """ # wrap non-field-errors into <div>-element to prevent re-boxing error_row = '<div class="djng-line-spreader">%s</div>' div_element = self._html_output( ...
Conditionally switch between AngularJS and Django variable expansion for ``{{`` and ``}}`` keeping Django's expansion for ``{%`` and ``%}`` Usage:: {% angularjs 1 %} or simply {% angularjs %} {% process variables through the AngularJS template engine %} {% endangularjs %} ...
def angularjs(parser, token): """ Conditionally switch between AngularJS and Django variable expansion for ``{{`` and ``}}`` keeping Django's expansion for ``{%`` and ``%}`` Usage:: {% angularjs 1 %} or simply {% angularjs %} {% process variables through the AngularJS template engi...
Returns a script tag for including the proper locale script in any HTML page. This tag determines the current language with its locale. Usage: <script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script %}"></script> or, if used with a default language: <script src="{% stati...
def djng_locale_script(context, default_language='en'): """ Returns a script tag for including the proper locale script in any HTML page. This tag determines the current language with its locale. Usage: <script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script %}"></script> ...
Update the dictionary of attributes used while rendering the input widget
def update_widget_attrs(self, bound_field, attrs): """ Update the dictionary of attributes used while rendering the input widget """ bound_field.form.update_widget_attrs(bound_field, attrs) widget_classes = self.widget.attrs.get('class', None) if widget_classes: ...
Return a regex pattern matching valid email addresses. Uses the same logic as the django validator, with the folowing exceptions: - Internationalized domain names not supported - IP addresses not supported - Strips lookbehinds (not supported in javascript regular expressions)
def get_email_regex(self): """ Return a regex pattern matching valid email addresses. Uses the same logic as the django validator, with the folowing exceptions: - Internationalized domain names not supported - IP addresses not supported - Strips lookbehinds (not supporte...
Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked".
def get_multiple_choices_required(self): """ Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked". """ errors = [] if self.required: msg = _("A...
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.
def implode_multi_values(self, name, data): """ 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. """ mkeys = [k for...
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.
def convert_ajax_data(self, field_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. """ data = [key for key, va...
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...
def process_request(self, request): """ 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 middle...
Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the Angular API to the client, offering him to call remote methods.
def get_all_remote_methods(resolver=None, ns_prefix=''): """ Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the Angular API to the client, offering him to call remote methods. """ if not resolver: resolver = get_resolver(get_urlconf()) result...
Override dispatch to call appropriate methods: * $query - ng_query * $get - ng_get * $save - ng_save * $delete and $remove - ng_delete
def dispatch(self, request, *args, **kwargs): """ Override dispatch to call appropriate methods: * $query - ng_query * $get - ng_get * $save - ng_save * $delete and $remove - ng_delete """ allowed_methods = self.get_allowed_methods() try: ...
Return serialized queryset or single object as python dictionary serialize() only works on iterables, so to serialize a single object we put it in a list
def serialize_queryset(self, queryset): """ Return serialized queryset or single object as python dictionary serialize() only works on iterables, so to serialize a single object we put it in a list """ object_data = [] is_queryset = False query_fields = self.get_f...
Called on $save() Use modelform to save new object or modify an existing one
def ng_save(self, request, *args, **kwargs): """ Called on $save() Use modelform to save new object or modify an existing one """ form = self.get_form(self.get_form_class()) if form.is_valid(): obj = form.save() return self.build_json_response(obj)...
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
def ng_delete(self, request, *args, **kwargs): """ 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 """ if 'pk...
Outputs a <div ng-form="name"> for this set of choice fields to nest an ngForm.
def render(self): """ Outputs a <div ng-form="name"> for this set of choice fields to nest an ngForm. """ start_tag = format_html('<div {}>', mark_safe(' '.join(self.field_attrs))) output = [start_tag] for widget in self: output.append(force_text(widget)) ...
Rewrite the error dictionary, so that its keys correspond to the model fields.
def _post_clean(self): """ Rewrite the error dictionary, so that its keys correspond to the model fields. """ super(NgModelFormMixin, self)._post_clean() if self._errors and self.prefix: self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._...
Return a dictionary specifying the defaults for this form. This dictionary can be used to inject the initial values for an Angular controller using the directive: ``ng-init={{ thisform.get_initial_data|js|safe }}``.
def get_initial_data(self): """ Return a dictionary specifying the defaults for this form. This dictionary can be used to inject the initial values for an Angular controller using the directive: ``ng-init={{ thisform.get_initial_data|js|safe }}``. """ data = {} ng...
Tries to catch resize signals sent from the terminal.
def _handle_resize(self, signum=None, frame=None): 'Tries to catch resize signals sent from the terminal.' w, h = utils.get_terminal_size() self.term_width = w
(re)initialize values to original state so the progressbar can be used (again)
def init(self): ''' (re)initialize values to original state so the progressbar can be used (again) ''' self.previous_value = None self.last_update_time = None self.start_time = None self.updates = 0 self.end_time = None self.extra = dict() ...
Return current percentage, returns None if no max_value is given >>> progress = ProgressBar() >>> progress.max_value = 10 >>> progress.min_value = 0 >>> progress.value = 0 >>> progress.percentage 0.0 >>> >>> progress.value = 1 >>> progress.percent...
def percentage(self): '''Return current percentage, returns None if no max_value is given >>> progress = ProgressBar() >>> progress.max_value = 10 >>> progress.min_value = 0 >>> progress.value = 0 >>> progress.percentage 0.0 >>> >>> progress.value...
Returns whether the ProgressBar should redraw the line.
def _needs_update(self): 'Returns whether the ProgressBar should redraw the line.' if self.poll_interval: delta = timeit.default_timer() - self._last_update_timer poll_status = delta > self.poll_interval.total_seconds() else: delta = 0 poll_status...
Updates the ProgressBar to a new value.
def update(self, value=None, force=False, **kwargs): 'Updates the ProgressBar to a new value.' if self.start_time is None: self.start() return self.update(value, force=force, **kwargs) if value is not None and value is not base.UnknownLength: if self.max_valu...
Starts measuring time, and prints the bar at 0%. It returns self so you can use it like this: Args: max_value (int): The maximum value of the progressbar reinit (bool): Initialize the progressbar, this is useful if you wish to reuse the same progressbar but can ...
def start(self, max_value=None, init=True): '''Starts measuring time, and prints the bar at 0%. It returns self so you can use it like this: Args: max_value (int): The maximum value of the progressbar reinit (bool): Initialize the progressbar, this is useful if you ...
Puts the ProgressBar bar in the finished state. Also flushes and disables output buffering if this was the last progressbar running. Args: end (str): The string to end the progressbar with, defaults to a newline dirty (bool): When True the progressbar ke...
def finish(self, end='\n', dirty=False): ''' Puts the ProgressBar bar in the finished state. Also flushes and disables output buffering if this was the last progressbar running. Args: end (str): The string to end the progressbar with, defaults to a n...
Wrap the examples so they generate readable output
def example(fn): '''Wrap the examples so they generate readable output''' @functools.wraps(fn) def wrapped(): try: sys.stdout.write('Running: %s\n' % fn.__name__) fn() sys.stdout.write('\n') except KeyboardInterrupt: sys.stdout.write('\nSkippi...
Updates the widget to show the ETA or total time when finished.
def _calculate_eta(self, progress, data, value, elapsed): '''Updates the widget to show the ETA or total time when finished.''' if elapsed: # The max() prevents zero division errors per_item = elapsed.total_seconds() / max(value, 1e-6) remaining = progress.max_value -...
Load standard graph validation sets For each size (from 6 to 32 graph nodes) the dataset consists of 100 graphs drawn from the Erdős-Rényi ensemble with edge probability 50%.
def load_stdgraphs(size: int) -> List[nx.Graph]: """Load standard graph validation sets For each size (from 6 to 32 graph nodes) the dataset consists of 100 graphs drawn from the Erdős-Rényi ensemble with edge probability 50%. """ from pkg_resources import resource_stream if size < 6 or si...
Download and rescale the MNIST database of handwritten digits MNIST is a dataset of 60,000 28x28 grayscale images handwritten digits, along with a test set of 10,000 images. We use Keras to download and access the dataset. The first invocation of this method may take a while as the dataset has to be do...
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]: """Download and rescale the MNIST database of handwritten digits MNIST is a dataset...
Covert numpy array to tensorflow tensor
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
Return the inner product between two states
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor: """Return the inner product between two states""" # Note: Relying on fact that vdot flattens arrays N = rank(tensor0) axes = list(range(N)) return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes))
A QAOA circuit for the Quadratic Unconstrained Binary Optimization problem (i.e. an Ising model). Args: graph : a networkx graph instance with optional edge and node weights steps : number of QAOA steps beta : driver parameters (One per step) gamma : cost parameters (One per st...
def qubo_circuit( graph: nx.Graph, steps: int, beta: Sequence, gamma: Sequence) -> Circuit: """ A QAOA circuit for the Quadratic Unconstrained Binary Optimization problem (i.e. an Ising model). Args: graph : a networkx graph instance with optional edge and node w...
For the given graph, return the cut value for all binary assignments of the graph.
def graph_cuts(graph: nx.Graph) -> np.ndarray: """For the given graph, return the cut value for all binary assignments of the graph. """ 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_hamiltonia...
Return the circuit depth. Args: local: If True include local one-qubit gates in depth calculation. Else return the multi-qubit gate depth.
def depth(self, local: bool = True) -> int: """Return the circuit depth. Args: local: If True include local one-qubit gates in depth calculation. Else return the multi-qubit gate depth. """ G = self.graph if not local: def remove_local(da...
Split DAGCircuit into independent components
def components(self) -> List['DAGCircuit']: """Split DAGCircuit into independent components""" comps = nx.weakly_connected_component_subgraphs(self.graph) return [DAGCircuit(comp) for comp in comps]
Split DAGCircuit into layers, where the operations within each layer operate on different qubits (and therefore commute). Returns: A Circuit of Circuits, one Circuit per layer
def layers(self) -> Circuit: """Split DAGCircuit into layers, where the operations within each layer operate on different qubits (and therefore commute). Returns: A Circuit of Circuits, one Circuit per layer """ node_depth: Dict[Qubit, int] = {} G = self.graph f...
Return the all-zero state on N qubits
def zero_state(qubits: Union[int, Qubits]) -> State: """Return the all-zero state on N qubits""" N, qubits = qubits_count_tuple(qubits) ket = np.zeros(shape=[2] * N) ket[(0,) * N] = 1 return State(ket, qubits)
Return a W state on N qubits
def w_state(qubits: Union[int, Qubits]) -> State: """Return a W state on N qubits""" 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 GHZ state on N qubits
def ghz_state(qubits: Union[int, Qubits]) -> State: """Return a GHZ state on N qubits""" 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 random state from the space of N qubits
def random_state(qubits: Union[int, Qubits]) -> State: """Return a random state from the space of N qubits""" 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()
Join two state vectors into a larger qubit state
def join_states(*states: State) -> State: """Join two state vectors into a larger qubit state""" vectors = [ket.vec for ket in states] vec = reduce(outer_product, vectors) return State(vec.tensor, vec.qubits)
Print a state vector
def print_state(state: State, file: TextIO = None) -> None: """Print a state vector""" state = state.vec.asarray() for index, amplitude in np.ndenumerate(state): ket = "".join([str(n) for n in index]) print(ket, ":", amplitude, file=file)
Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout)
def print_probabilities(state: State, ndigits: int = 4, file: TextIO = None) -> None: """ Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout) """ prob = bk.evaluate(state.probab...
Returns the completely mixed density matrix
def mixed_density(qubits: Union[int, Qubits]) -> Density: """Returns the completely mixed density matrix""" N, qubits = qubits_count_tuple(qubits) matrix = np.eye(2**N) / 2**N return Density(matrix, qubits)
Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) https://arxiv.org/abs/quant-ph/0012101
def random_density(qubits: Union[int, Qubits]) -> Density: """ Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) ...
Return a copy of this state with new qubits
def relabel(self, qubits: Qubits) -> 'State': """Return a copy of this state with new qubits""" return State(self.vec.tensor, qubits, self._memory)
Return a copy of this state with qubit labels permuted
def permute(self, qubits: Qubits) -> 'State': """Return a copy of this state with qubit labels permuted""" vec = self.vec.permute(qubits) return State(vec.tensor, vec.qubits, self._memory)
Normalize the state
def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
Returns: The state probabilities
def probabilities(self) -> bk.BKTensor: """ Returns: The state probabilities """ value = bk.absolute(self.tensor) return value * value
Measure the state in the computational basis the the given number of trials, and return the counts of each output configuration.
def sample(self, trials: int) -> np.ndarray: """Measure the state in the computational basis the the given number of trials, and return the counts of each output configuration. """ # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) r...
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. If the number of trials is specified, we sample the given number of times. Else we return the exact expectation (as if...
def expectation(self, diag_hermitian: bk.TensorLike, trials: int = None) -> bk.BKTensor: """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. If the...
Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1
def measure(self) -> np.ndarray: """Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1 """ # TODO: Can we do this within backend? probs = np.real(bk.evaluate(self.probabilities())) indices = np.asarray(list(...
Convert a pure state to a density matrix
def asdensity(self) -> 'Density': """Convert a pure state to a density matrix""" matrix = bk.outer(self.tensor, bk.conj(self.tensor)) return Density(matrix, self.qubits, self._memory)
Return the partial trace over the specified qubits
def partial_trace(self, qubits: Qubits) -> 'Density': """Return the partial trace over the specified qubits""" vec = self.vec.partial_trace(qubits) return Density(vec.tensor, vec.qubits, self._memory)
Return a copy of this state with new qubits
def relabel(self, qubits: Qubits) -> 'Density': """Return a copy of this state with new qubits""" return Density(self.vec.tensor, qubits, self._memory)
Return a copy of this state with qubit labels permuted
def permute(self, qubits: Qubits) -> 'Density': """Return a copy of this state with qubit labels permuted""" vec = self.vec.permute(qubits) return Density(vec.tensor, vec.qubits, self._memory)
Normalize state
def normalize(self) -> 'Density': """Normalize state""" tensor = self.tensor / self.trace() return Density(tensor, self.qubits, self._memory)
Returns: The state probabilities
def probabilities(self) -> bk.BKTensor: """Returns: The state probabilities """ prob = bk.productdiag(self.tensor) return prob
Create and run a circuit with N qubits and given number of gates
def benchmark(N, gates): """Create and run a circuit with N qubits and given number of 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...
Return benchmark performance in GOPS (Gate operations per second)
def benchmark_gops(N, gates, reps): """Return benchmark performance in GOPS (Gate operations per second)""" t = timeit.timeit(lambda: benchmark(N, gates), number=reps) gops = (GATES*REPS)/t gops = int((gops * 100) + 0.5) / 100.0 return gops
Create composite gates, decompose, and return a list of canonical coordinates
def sandwich_decompositions(coords0, coords1, samples=SAMPLES): """Create composite gates, decompose, and return a list of canonical coordinates""" decomps = [] for _ in range(samples): circ = qf.Circuit() circ += qf.CANONICAL(*coords0, 0, 1) circ += qf.random_gate([0]) c...
Construct and display 3D plot of canonical coordinates
def display_weyl(decomps): """Construct and display 3D plot of canonical coordinates""" tx, ty, tz = list(zip(*decomps)) rcParams['axes.labelsize'] = 24 rcParams['font.family'] = 'serif' rcParams['font.serif'] = ['Computer Modern Roman'] rcParams['text.usetex'] = True fig = pyplot.figure() ...
Return the Pauli sigma_X operator acting on the given qubit
def sX(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_X operator acting on the given qubit""" return Pauli.sigma(qubit, 'X', coefficient)
Return the Pauli sigma_Y operator acting on the given qubit
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_Y operator acting on the given qubit""" return Pauli.sigma(qubit, 'Y', coefficient)
Return the Pauli sigma_Z operator acting on the given qubit
def sZ(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_Z operator acting on the given qubit""" return Pauli.sigma(qubit, 'Z', coefficient)
Return the Pauli sigma_I (identity) operator. The qubit is irrelevant, but kept as an argument for consistency
def sI(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_I (identity) operator. The qubit is irrelevant, but kept as an argument for consistency""" return Pauli.sigma(qubit, 'I', coefficient)
Return the sum of elements of the Pauli algebra
def pauli_sum(*elements: Pauli) -> Pauli: """Return the sum of elements of the Pauli algebra""" 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, c...
Return the product of elements of the Pauli algebra
def pauli_product(*elements: Pauli) -> Pauli: """Return the product of elements of the Pauli algebra""" 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) ...