repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
bulkan/robotframework-requests
src/RequestsLibrary/RequestsKeywords.py
RequestsKeywords.delete_request
def delete_request( self, alias, uri, data=None, json=None, params=None, headers=None, allow_redirects=None, timeout=None): """ Send a DELETE request on the session object found using the given `a...
python
def delete_request( self, alias, uri, data=None, json=None, params=None, headers=None, allow_redirects=None, timeout=None): """ Send a DELETE request on the session object found using the given `a...
[ "def", "delete_request", "(", "self", ",", "alias", ",", "uri", ",", "data", "=", "None", ",", "json", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "allow_redirects", "=", "None", ",", "timeout", "=", "None", ")", ":", ...
Send a DELETE request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object in the cache ``uri`` to send the DELETE request to ``json`` a value that will be json encoded and sent as request data if data is not spe...
[ "Send", "a", "DELETE", "request", "on", "the", "session", "object", "found", "using", "the", "given", "alias" ]
11baa3277f1cb728712e26d996200703c15254a8
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L864-L902
train
bulkan/robotframework-requests
src/RequestsLibrary/RequestsKeywords.py
RequestsKeywords.head_request
def head_request( self, alias, uri, headers=None, allow_redirects=None, timeout=None): """ Send a HEAD request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object i...
python
def head_request( self, alias, uri, headers=None, allow_redirects=None, timeout=None): """ Send a HEAD request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object i...
[ "def", "head_request", "(", "self", ",", "alias", ",", "uri", ",", "headers", "=", "None", ",", "allow_redirects", "=", "None", ",", "timeout", "=", "None", ")", ":", "session", "=", "self", ".", "_cache", ".", "switch", "(", "alias", ")", "redir", "...
Send a HEAD request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object in the cache ``uri`` to send the HEAD request to ``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. ``hea...
[ "Send", "a", "HEAD", "request", "on", "the", "session", "object", "found", "using", "the", "given", "alias" ]
11baa3277f1cb728712e26d996200703c15254a8
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L937-L961
train
bulkan/robotframework-requests
src/RequestsLibrary/RequestsKeywords.py
RequestsKeywords.options_request
def options_request( self, alias, uri, headers=None, allow_redirects=None, timeout=None): """ Send an OPTIONS request on the session object found using the given `alias` ``alias`` that will be used to identify the Session o...
python
def options_request( self, alias, uri, headers=None, allow_redirects=None, timeout=None): """ Send an OPTIONS request on the session object found using the given `alias` ``alias`` that will be used to identify the Session o...
[ "def", "options_request", "(", "self", ",", "alias", ",", "uri", ",", "headers", "=", "None", ",", "allow_redirects", "=", "None", ",", "timeout", "=", "None", ")", ":", "session", "=", "self", ".", "_cache", ".", "switch", "(", "alias", ")", "redir", ...
Send an OPTIONS request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object in the cache ``uri`` to send the OPTIONS request to ``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. ...
[ "Send", "an", "OPTIONS", "request", "on", "the", "session", "object", "found", "using", "the", "given", "alias" ]
11baa3277f1cb728712e26d996200703c15254a8
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L990-L1015
train
bulkan/robotframework-requests
src/RequestsLibrary/RequestsKeywords.py
RequestsKeywords._get_url
def _get_url(self, session, uri): """ Helper method to get the full url """ url = session.url if uri: slash = '' if uri.startswith('/') else '/' url = "%s%s%s" % (session.url, slash, uri) return url
python
def _get_url(self, session, uri): """ Helper method to get the full url """ url = session.url if uri: slash = '' if uri.startswith('/') else '/' url = "%s%s%s" % (session.url, slash, uri) return url
[ "def", "_get_url", "(", "self", ",", "session", ",", "uri", ")", ":", "url", "=", "session", ".", "url", "if", "uri", ":", "slash", "=", "''", "if", "uri", ".", "startswith", "(", "'/'", ")", "else", "'/'", "url", "=", "\"%s%s%s\"", "%", "(", "se...
Helper method to get the full url
[ "Helper", "method", "to", "get", "the", "full", "url" ]
11baa3277f1cb728712e26d996200703c15254a8
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1174-L1182
train
bulkan/robotframework-requests
src/RequestsLibrary/RequestsKeywords.py
RequestsKeywords._json_pretty_print
def _json_pretty_print(self, content): """ Pretty print a JSON object ``content`` JSON object to pretty print """ temp = json.loads(content) return json.dumps( temp, sort_keys=True, indent=4, separators=( '...
python
def _json_pretty_print(self, content): """ Pretty print a JSON object ``content`` JSON object to pretty print """ temp = json.loads(content) return json.dumps( temp, sort_keys=True, indent=4, separators=( '...
[ "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 ``content`` JSON object to pretty print
[ "Pretty", "print", "a", "JSON", "object" ]
11baa3277f1cb728712e26d996200703c15254a8
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1215-L1228
train
coddingtonbear/python-myfitnesspal
myfitnesspal/client.py
Client.get_measurements
def get_measurements( self, measurement='Weight', lower_bound=None, upper_bound=None ): """ Returns measurements of a given name between two dates.""" if upper_bound is None: upper_bound = datetime.date.today() if lower_bound is None: lower_bound = upper_bound...
python
def get_measurements( self, measurement='Weight', lower_bound=None, upper_bound=None ): """ Returns measurements of a given name between two dates.""" if upper_bound is None: upper_bound = datetime.date.today() if lower_bound is None: lower_bound = upper_bound...
[ "def", "get_measurements", "(", "self", ",", "measurement", "=", "'Weight'", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ")", ":", "if", "upper_bound", "is", "None", ":", "upper_bound", "=", "datetime", ".", "date", ".", "today", "(",...
Returns measurements of a given name between two dates.
[ "Returns", "measurements", "of", "a", "given", "name", "between", "two", "dates", "." ]
29aad88d31adc025eacaddd3390cb521b6012b73
https://github.com/coddingtonbear/python-myfitnesspal/blob/29aad88d31adc025eacaddd3390cb521b6012b73/myfitnesspal/client.py#L524-L586
train
coddingtonbear/python-myfitnesspal
myfitnesspal/client.py
Client.set_measurements
def set_measurements( self, measurement='Weight', value=None ): """ Sets measurement for today's date.""" if value is None: raise ValueError( "Cannot update blank value." ) # get the URL for the main check in page # this is left in bec...
python
def set_measurements( self, measurement='Weight', value=None ): """ Sets measurement for today's date.""" if value is None: raise ValueError( "Cannot update blank value." ) # get the URL for the main check in page # this is left in bec...
[ "def", "set_measurements", "(", "self", ",", "measurement", "=", "'Weight'", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot update blank value.\"", ")", "document", "=", "self", ".", "_get_document_...
Sets measurement for today's date.
[ "Sets", "measurement", "for", "today", "s", "date", "." ]
29aad88d31adc025eacaddd3390cb521b6012b73
https://github.com/coddingtonbear/python-myfitnesspal/blob/29aad88d31adc025eacaddd3390cb521b6012b73/myfitnesspal/client.py#L588-L667
train
coddingtonbear/python-myfitnesspal
myfitnesspal/client.py
Client.get_measurement_id_options
def get_measurement_id_options(self): """ Returns list of measurement choices.""" # get the URL for the main check in page document = self._get_document_for_url( self._get_url_for_measurements() ) # gather the IDs for all measurement types measurement_ids = s...
python
def get_measurement_id_options(self): """ Returns list of measurement choices.""" # get the URL for the main check in page document = self._get_document_for_url( self._get_url_for_measurements() ) # gather the IDs for all measurement types measurement_ids = s...
[ "def", "get_measurement_id_options", "(", "self", ")", ":", "document", "=", "self", ".", "_get_document_for_url", "(", "self", ".", "_get_url_for_measurements", "(", ")", ")", "measurement_ids", "=", "self", ".", "_get_measurement_ids", "(", "document", ")", "ret...
Returns list of measurement choices.
[ "Returns", "list", "of", "measurement", "choices", "." ]
29aad88d31adc025eacaddd3390cb521b6012b73
https://github.com/coddingtonbear/python-myfitnesspal/blob/29aad88d31adc025eacaddd3390cb521b6012b73/myfitnesspal/client.py#L709-L718
train
joerick/pyinstrument
pyinstrument/__main__.py
file_supports_color
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 ...
python
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 ...
[ "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", "=", ...
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
[ "Returns", "True", "if", "the", "running", "system", "s", "terminal", "supports", "color", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/__main__.py#L198-L211
train
joerick/pyinstrument
pyinstrument/__main__.py
load_report
def load_report(identifier=None): ''' Returns the session referred to by identifier ''' path = os.path.join( report_dir(), identifier + '.pyireport' ) return ProfilerSession.load(path)
python
def load_report(identifier=None): ''' Returns the session referred to by identifier ''' path = os.path.join( report_dir(), identifier + '.pyireport' ) return ProfilerSession.load(path)
[ "def", "load_report", "(", "identifier", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "report_dir", "(", ")", ",", "identifier", "+", "'.pyireport'", ")", "return", "ProfilerSession", ".", "load", "(", "path", ")" ]
Returns the session referred to by identifier
[ "Returns", "the", "session", "referred", "to", "by", "identifier" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/__main__.py#L245-L253
train
joerick/pyinstrument
pyinstrument/__main__.py
save_report
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...
python
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...
[ "def", "save_report", "(", "session", ")", ":", "previous_reports", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "report_dir", "(", ")", ",", "'*.pyireport'", ")", ")", "previous_reports", ".", "sort", "(", "reverse", "=", "True", ...
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.
[ "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", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/__main__.py#L255-L274
train
joerick/pyinstrument
pyinstrument/session.py
ProfilerSession.root_frame
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]...
python
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]...
[ "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"...
Parses the internal frame records and returns a tree of Frame objects
[ "Parses", "the", "internal", "frame", "records", "and", "returns", "a", "tree", "of", "Frame", "objects" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/session.py#L52-L95
train
joerick/pyinstrument
pyinstrument/frame.py
BaseFrame.remove_from_parent
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
python
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
[ "def", "remove_from_parent", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "self", ".", "parent", ".", "_children", ".", "remove", "(", "self", ")", "self", ".", "parent", ".", "_invalidate_time_caches", "(", ")", "self", ".", "parent", "=", ...
Removes this frame from its parent, and nulls the parent link
[ "Removes", "this", "frame", "from", "its", "parent", "and", "nulls", "the", "parent", "link" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/frame.py#L11-L18
train
joerick/pyinstrument
pyinstrument/frame.py
Frame.add_child
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...
python
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...
[ "def", "add_child", "(", "self", ",", "frame", ",", "after", "=", "None", ")", ":", "frame", ".", "remove_from_parent", "(", ")", "frame", ".", "parent", "=", "self", "if", "after", "is", "None", ":", "self", ".", "_children", ".", "append", "(", "fr...
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.
[ "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", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/frame.py#L99-L113
train
joerick/pyinstrument
pyinstrument/frame.py
Frame.add_children
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): ...
python
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): ...
[ "def", "add_children", "(", "self", ",", "frames", ",", "after", "=", "None", ")", ":", "if", "after", "is", "not", "None", ":", "for", "frame", "in", "reversed", "(", "frames", ")", ":", "self", ".", "add_child", "(", "frame", ",", "after", "=", "...
Convenience method to add multiple frames at once.
[ "Convenience", "method", "to", "add", "multiple", "frames", "at", "once", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/frame.py#L115-L126
train
joerick/pyinstrument
pyinstrument/frame.py
Frame.file_path_short
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...
python
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...
[ "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"...
Return the path resolved against the closest entry in sys.path
[ "Return", "the", "path", "resolved", "against", "the", "closest", "entry", "in", "sys", ".", "path" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/frame.py#L151-L173
train
joerick/pyinstrument
pyinstrument/frame.py
FrameGroup.exit_frames
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): ...
python
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): ...
[ "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", ...
Returns a list of frames whose children include a frame outside of the group
[ "Returns", "a", "list", "of", "frames", "whose", "children", "include", "a", "frame", "outside", "of", "the", "group" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/frame.py#L286-L297
train
joerick/pyinstrument
pyinstrument/profiler.py
Profiler.first_interesting_frame
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...
python
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...
[ "def", "first_interesting_frame", "(", "self", ")", ":", "root_frame", "=", "self", ".", "root_frame", "(", ")", "frame", "=", "root_frame", "while", "len", "(", "frame", ".", "children", ")", "<=", "1", ":", "if", "frame", ".", "children", ":", "frame",...
Traverse down the frame hierarchy until a frame is found with more than one child
[ "Traverse", "down", "the", "frame", "hierarchy", "until", "a", "frame", "is", "found", "with", "more", "than", "one", "child" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/profiler.py#L119-L133
train
joerick/pyinstrument
pyinstrument/processors.py
aggregate_repeated_calls
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...
python
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...
[ "def", "aggregate_repeated_calls", "(", "frame", ",", "options", ")", ":", "if", "frame", "is", "None", ":", "return", "None", "children_by_identifier", "=", "{", "}", "for", "child", "in", "frame", ".", "children", ":", "if", "child", ".", "identifier", "...
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)
[ "Converts", "a", "timeline", "into", "a", "time", "-", "aggregate", "summary", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/processors.py#L31-L70
train
joerick/pyinstrument
pyinstrument/processors.py
merge_consecutive_self_time
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: ...
python
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: ...
[ "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", ...
Combines consecutive 'self time' frames
[ "Combines", "consecutive", "self", "time", "frames" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/processors.py#L101-L125
train
joerick/pyinstrument
pyinstrument/processors.py
remove_unnecessary_self_time_nodes
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) ==...
python
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) ==...
[ "def", "remove_unnecessary_self_time_nodes", "(", "frame", ",", "options", ")", ":", "if", "frame", "is", "None", ":", "return", "None", "if", "len", "(", "frame", ".", "children", ")", "==", "1", "and", "isinstance", "(", "frame", ".", "children", "[", ...
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.
[ "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", "inform...
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/processors.py#L128-L144
train
joerick/pyinstrument
pyinstrument/renderers/html.py
HTMLRenderer.open_in_browser
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...
python
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...
[ "def", "open_in_browser", "(", "self", ",", "session", ",", "output_filename", "=", "None", ")", ":", "if", "output_filename", "is", "None", ":", "output_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.html'", ",", "delete", "=", "F...
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.
[ "Open", "the", "rendered", "HTML", "in", "a", "webbrowser", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/renderers/html.py#L43-L64
train
joerick/pyinstrument
setup.py
BuildPyCommand.run
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',...
python
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',...
[ "def", "run", "(", "self", ")", ":", "if", "subprocess", ".", "call", "(", "[", "'npm'", ",", "'--version'", "]", ")", "!=", "0", ":", "raise", "RuntimeError", "(", "'npm is required to build the HTML renderer.'", ")", "self", ".", "check_call", "(", "[", ...
compile the JS, then run superclass implementation
[ "compile", "the", "JS", "then", "run", "superclass", "implementation" ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/setup.py#L19-L30
train
joerick/pyinstrument
pyinstrument/util.py
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)
python
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)
[ "def", "deprecated", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'{} is deprecated and should no longer be used.'", ".", "format", "(", "func", ")", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", ...
Marks a function as deprecated.
[ "Marks", "a", "function", "as", "deprecated", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/util.py#L18-L25
train
joerick/pyinstrument
pyinstrument/util.py
deprecated_option
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...
python
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...
[ "def", "deprecated_option", "(", "option_name", ",", "message", "=", "''", ")", ":", "def", "caller", "(", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "option_name", "in", "kwargs", ":", "warnings", ".", "warn", "(", "'{} is deprecated...
Marks an option as deprecated.
[ "Marks", "an", "option", "as", "deprecated", "." ]
cc4f3f6fc1b493d7cd058ecf41ad012e0030a512
https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/util.py#L27-L38
train
jrief/django-angular
djng/app_settings.py
AppSettings.THUMBNAIL_OPTIONS
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...
python
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...
[ "def", "THUMBNAIL_OPTIONS", "(", "self", ")", ":", "from", "django", ".", "core", ".", "exceptions", "import", "ImproperlyConfigured", "size", "=", "self", ".", "_setting", "(", "'DJNG_THUMBNAIL_SIZE'", ",", "(", "200", ",", "200", ")", ")", "if", "not", "...
Set the size as a 2-tuple for thumbnailed images after uploading them.
[ "Set", "the", "size", "as", "a", "2", "-", "tuple", "for", "thumbnailed", "images", "after", "uploading", "them", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/app_settings.py#L20-L29
train
jrief/django-angular
djng/forms/angular_base.py
NgWidgetMixin.get_context
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)...
python
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)...
[ "def", "get_context", "(", "self", ",", "name", ",", "value", ",", "attrs", ")", ":", "context", "=", "super", "(", "NgWidgetMixin", ",", "self", ")", ".", "get_context", "(", "name", ",", "value", ",", "attrs", ")", "if", "callable", "(", "getattr", ...
Some widgets require a modified rendering context, if they contain angular directives.
[ "Some", "widgets", "require", "a", "modified", "rendering", "context", "if", "they", "contain", "angular", "directives", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L156-L163
train
jrief/django-angular
djng/forms/angular_base.py
NgBoundField.errors
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) ...
python
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) ...
[ "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.
[ "Returns", "a", "TupleErrorList", "for", "this", "field", ".", "This", "overloaded", "method", "adds", "additional", "error", "lists", "to", "the", "errors", "as", "detected", "by", "the", "form", "validator", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L168-L175
train
jrief/django-angular
djng/forms/angular_base.py
NgBoundField.css_classes
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 []) ...
python
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 []) ...
[ "def", "css_classes", "(", "self", ",", "extra_classes", "=", "None", ")", ":", "if", "hasattr", "(", "extra_classes", ",", "'split'", ")", ":", "extra_classes", "=", "extra_classes", ".", "split", "(", ")", "extra_classes", "=", "set", "(", "extra_classes",...
Returns a string of space-separated CSS classes for the wrapping element of this input field.
[ "Returns", "a", "string", "of", "space", "-", "separated", "CSS", "classes", "for", "the", "wrapping", "element", "of", "this", "input", "field", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L177-L203
train
jrief/django-angular
djng/forms/angular_base.py
NgFormBaseMixin.get_field_errors
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...
python
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...
[ "def", "get_field_errors", "(", "self", ",", "field", ")", ":", "identifier", "=", "format_html", "(", "'{0}[\\'{1}\\']'", ",", "self", ".", "form_name", ",", "field", ".", "name", ")", "errors", "=", "self", ".", "errors", ".", "get", "(", "field", ".",...
Return server side errors. Shall be overridden by derived forms to add their extra errors for AngularJS.
[ "Return", "server", "side", "errors", ".", "Shall", "be", "overridden", "by", "derived", "forms", "to", "add", "their", "extra", "errors", "for", "AngularJS", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L330-L338
train
jrief/django-angular
djng/forms/angular_base.py
NgFormBaseMixin.update_widget_attrs
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...
python
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...
[ "def", "update_widget_attrs", "(", "self", ",", "bound_field", ",", "attrs", ")", ":", "if", "bound_field", ".", "field", ".", "has_subwidgets", "(", ")", "is", "False", ":", "widget_classes", "=", "getattr", "(", "self", ",", "'widget_css_classes'", ",", "N...
Updated the widget attributes which shall be added to the widget when rendering this field.
[ "Updated", "the", "widget", "attributes", "which", "shall", "be", "added", "to", "the", "widget", "when", "rendering", "this", "field", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L354-L365
train
jrief/django-angular
djng/forms/angular_base.py
NgFormBaseMixin.rectify_multipart_form_data
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: ...
python
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: ...
[ "def", "rectify_multipart_form_data", "(", "self", ",", "data", ")", ":", "for", "name", ",", "field", "in", "self", ".", "base_fields", ".", "items", "(", ")", ":", "try", ":", "field", ".", "implode_multi_values", "(", "name", ",", "data", ")", "except...
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
[ "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" ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L380-L390
train
jrief/django-angular
djng/forms/angular_base.py
NgFormBaseMixin.rectify_ajax_form_data
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: ...
python
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: ...
[ "def", "rectify_ajax_form_data", "(", "self", ",", "data", ")", ":", "for", "name", ",", "field", "in", "self", ".", "base_fields", ".", "items", "(", ")", ":", "try", ":", "data", "[", "name", "]", "=", "field", ".", "convert_ajax_data", "(", "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
[ "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" ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L392-L402
train
jrief/django-angular
djng/templatetags/djng_tags.py
djng_locale_script
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> ...
python
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> ...
[ "def", "djng_locale_script", "(", "context", ",", "default_language", "=", "'en'", ")", ":", "language", "=", "get_language_from_request", "(", "context", "[", "'request'", "]", ")", "if", "not", "language", ":", "language", "=", "default_language", "return", "f...
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...
[ "Returns", "a", "script", "tag", "for", "including", "the", "proper", "locale", "script", "in", "any", "HTML", "page", ".", "This", "tag", "determines", "the", "current", "language", "with", "its", "locale", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/templatetags/djng_tags.py#L101-L114
train
jrief/django-angular
djng/forms/fields.py
DefaultFieldMixin.update_widget_attrs
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: ...
python
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: ...
[ "def", "update_widget_attrs", "(", "self", ",", "bound_field", ",", "attrs", ")", ":", "bound_field", ".", "form", ".", "update_widget_attrs", "(", "bound_field", ",", "attrs", ")", "widget_classes", "=", "self", ".", "widget", ".", "attrs", ".", "get", "(",...
Update the dictionary of attributes used while rendering the input widget
[ "Update", "the", "dictionary", "of", "attributes", "used", "while", "rendering", "the", "input", "widget" ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/fields.py#L100-L111
train
jrief/django-angular
djng/forms/fields.py
MultipleChoiceField.implode_multi_values
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...
python
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...
[ "def", "implode_multi_values", "(", "self", ",", "name", ",", "data", ")", ":", "mkeys", "=", "[", "k", "for", "k", "in", "data", ".", "keys", "(", ")", "if", "k", ".", "startswith", "(", "name", "+", "'.'", ")", "]", "mvls", "=", "[", "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.
[ "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", ...
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/fields.py#L355-L364
train
jrief/django-angular
djng/forms/fields.py
MultipleChoiceField.convert_ajax_data
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...
python
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...
[ "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.
[ "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", ...
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/fields.py#L366-L373
train
jrief/django-angular
djng/middleware.py
AngularUrlMiddleware.process_request
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...
python
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...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "if", "request", ".", "path", "==", "self", ".", "ANGULAR_REVERSE", ":", "url_name", "=", "request", ".", "GET", ".", "get", "(", "'djng_url_name'", ")", "url_args", "=", "request", ".", "G...
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...
[ "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", "Si...
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/middleware.py#L21-L73
train
jrief/django-angular
djng/views/crud.py
NgCRUDView.ng_delete
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...
python
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...
[ "def", "ng_delete", "(", "self", ",", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "'pk'", "not", "in", "request", ".", "GET", ":", "raise", "NgMissingParameterError", "(", "\"Object id is required to delete.\"", ")", "obj", "=", "self",...
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
[ "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", "...
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/views/crud.py#L170-L183
train
jrief/django-angular
djng/forms/angular_model.py
NgModelFormMixin._post_clean
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._...
python
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._...
[ "def", "_post_clean", "(", "self", ")", ":", "super", "(", "NgModelFormMixin", ",", "self", ")", ".", "_post_clean", "(", ")", "if", "self", ".", "_errors", "and", "self", ".", "prefix", ":", "self", ".", "_errors", "=", "ErrorDict", "(", "(", "self", ...
Rewrite the error dictionary, so that its keys correspond to the model fields.
[ "Rewrite", "the", "error", "dictionary", "so", "that", "its", "keys", "correspond", "to", "the", "model", "fields", "." ]
9f2f8247027173e3b3ad3b245ca299a9c9f31b40
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_model.py#L42-L48
train
WoLpH/python-progressbar
progressbar/bar.py
ProgressBar.percentage
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...
python
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...
[ "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...
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...
[ "Return", "current", "percentage", "returns", "None", "if", "no", "max_value", "is", "given" ]
963617a1bb9d81624ecf31f3457185992cd97bfa
https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/progressbar/bar.py#L297-L337
train
WoLpH/python-progressbar
examples.py
example
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...
python
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...
[ "def", "example", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped", "(", ")", ":", "try", ":", "sys", ".", "stdout", ".", "write", "(", "'Running: %s\\n'", "%", "fn", ".", "__name__", ")", "fn", "(", ")", "sys...
Wrap the examples so they generate readable output
[ "Wrap", "the", "examples", "so", "they", "generate", "readable", "output" ]
963617a1bb9d81624ecf31f3457185992cd97bfa
https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/examples.py#L16-L31
train
rigetti/quantumflow
quantumflow/datasets/__init__.py
load_stdgraphs
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...
python
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...
[ "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 ...
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%.
[ "Load", "standard", "graph", "validation", "sets" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/datasets/__init__.py#L23-L37
train
rigetti/quantumflow
quantumflow/datasets/__init__.py
load_mnist
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...
python
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...
[ "def", "load_mnist", "(", "size", ":", "int", "=", "None", ",", "border", ":", "int", "=", "_MNIST_BORDER", ",", "blank_corners", ":", "bool", "=", "False", ",", "nums", ":", "List", "[", "int", "]", "=", "None", ")", "->", "Tuple", "[", "np", ".",...
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...
[ "Download", "and", "rescale", "the", "MNIST", "database", "of", "handwritten", "digits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/datasets/__init__.py#L43-L127
train
rigetti/quantumflow
quantumflow/backend/tensorflow2bk.py
astensor
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
python
def astensor(array: TensorLike) -> BKTensor: """Covert numpy array to tensorflow tensor""" tensor = tf.convert_to_tensor(value=array, dtype=CTYPE) return tensor
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "tensor", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "array", ",", "dtype", "=", "CTYPE", ")", "return", "tensor" ]
Covert numpy array to tensorflow tensor
[ "Covert", "numpy", "array", "to", "tensorflow", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/tensorflow2bk.py#L74-L77
train
rigetti/quantumflow
quantumflow/backend/tensorflow2bk.py
inner
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))
python
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))
[ "def", "inner", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ")", "->", "BKTensor", ":", "N", "=", "rank", "(", "tensor0", ")", "axes", "=", "list", "(", "range", "(", "N", ")", ")", "return", "tf", ".", "tensordot", "(", "tf",...
Return the inner product between two states
[ "Return", "the", "inner", "product", "between", "two", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/tensorflow2bk.py#L92-L97
train
rigetti/quantumflow
quantumflow/qaoa.py
graph_cuts
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...
python
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...
[ "def", "graph_cuts", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "np", ".", "ndarray", ":", "N", "=", "len", "(", "graph", ")", "diag_hamiltonian", "=", "np", ".", "zeros", "(", "shape", "=", "(", "[", "2", "]", "*", "N", ")", ",", "dtype...
For the given graph, return the cut value for all binary assignments of the graph.
[ "For", "the", "given", "graph", "return", "the", "cut", "value", "for", "all", "binary", "assignments", "of", "the", "graph", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/qaoa.py#L68-L81
train
rigetti/quantumflow
quantumflow/dagcircuit.py
DAGCircuit.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...
python
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...
[ "def", "depth", "(", "self", ",", "local", ":", "bool", "=", "True", ")", "->", "int", ":", "G", "=", "self", ".", "graph", "if", "not", "local", ":", "def", "remove_local", "(", "dagc", ":", "DAGCircuit", ")", "->", "Generator", "[", "Operation", ...
Return the circuit depth. Args: local: If True include local one-qubit gates in depth calculation. Else return the multi-qubit gate depth.
[ "Return", "the", "circuit", "depth", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/dagcircuit.py#L97-L113
train
rigetti/quantumflow
quantumflow/dagcircuit.py
DAGCircuit.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]
python
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]
[ "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
[ "Split", "DAGCircuit", "into", "independent", "components" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/dagcircuit.py#L124-L127
train
rigetti/quantumflow
quantumflow/states.py
zero_state
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)
python
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)
[ "def", "zero_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "...
Return the all-zero state on N qubits
[ "Return", "the", "all", "-", "zero", "state", "on", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L186-L191
train
rigetti/quantumflow
quantumflow/states.py
w_state
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)
python
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)
[ "def", "w_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "N",...
Return a W state on N qubits
[ "Return", "a", "W", "state", "on", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L194-L202
train
rigetti/quantumflow
quantumflow/states.py
ghz_state
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)
python
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)
[ "def", "ghz_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "zeros", "(", "shape", "=", "[", "2", "]", "*", "N...
Return a GHZ state on N qubits
[ "Return", "a", "GHZ", "state", "on", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L205-L211
train
rigetti/quantumflow
quantumflow/states.py
random_state
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()
python
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()
[ "def", "random_state", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "State", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "ket", "=", "np", ".", "random", ".", "normal", "(", "size", "=", "(", "...
Return a random state from the space of N qubits
[ "Return", "a", "random", "state", "from", "the", "space", "of", "N", "qubits" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L214-L219
train
rigetti/quantumflow
quantumflow/states.py
join_states
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)
python
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)
[ "def", "join_states", "(", "*", "states", ":", "State", ")", "->", "State", ":", "vectors", "=", "[", "ket", ".", "vec", "for", "ket", "in", "states", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "State", "(", "vec"...
Join two state vectors into a larger qubit state
[ "Join", "two", "state", "vectors", "into", "a", "larger", "qubit", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L225-L229
train
rigetti/quantumflow
quantumflow/states.py
print_state
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)
python
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)
[ "def", "print_state", "(", "state", ":", "State", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "state", "=", "state", ".", "vec", ".", "asarray", "(", ")", "for", "index", ",", "amplitude", "in", "np", ".", "ndenumerate", "(", "...
Print a state vector
[ "Print", "a", "state", "vector" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L234-L239
train
rigetti/quantumflow
quantumflow/states.py
print_probabilities
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...
python
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...
[ "def", "print_probabilities", "(", "state", ":", "State", ",", "ndigits", ":", "int", "=", "4", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "prob", "=", "bk", ".", "evaluate", "(", "state", ".", "probabilities", "(", ")", ")", ...
Pretty print state probabilities. Args: state: ndigits: Number of digits of accuracy file: Output stream (Defaults to stdout)
[ "Pretty", "print", "state", "probabilities", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L243-L259
train
rigetti/quantumflow
quantumflow/states.py
mixed_density
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)
python
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)
[ "def", "mixed_density", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Density", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "matrix", "=", "np", ".", "eye", "(", "2", "**", "N", ")", "/", "2", ...
Returns the completely mixed density matrix
[ "Returns", "the", "completely", "mixed", "density", "matrix" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L322-L326
train
rigetti/quantumflow
quantumflow/states.py
join_densities
def join_densities(*densities: Density) -> Density: """Join two mixed states into a larger qubit state""" vectors = [rho.vec for rho in densities] vec = reduce(outer_product, vectors) memory = dict(ChainMap(*[rho.memory for rho in densities])) # TESTME return Density(vec.tensor, vec.qubits, memory...
python
def join_densities(*densities: Density) -> Density: """Join two mixed states into a larger qubit state""" vectors = [rho.vec for rho in densities] vec = reduce(outer_product, vectors) memory = dict(ChainMap(*[rho.memory for rho in densities])) # TESTME return Density(vec.tensor, vec.qubits, memory...
[ "def", "join_densities", "(", "*", "densities", ":", "Density", ")", "->", "Density", ":", "vectors", "=", "[", "rho", ".", "vec", "for", "rho", "in", "densities", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "memory", "=", "di...
Join two mixed states into a larger qubit state
[ "Join", "two", "mixed", "states", "into", "a", "larger", "qubit", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L349-L355
train
rigetti/quantumflow
quantumflow/states.py
State.normalize
def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
python
def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
[ "def", "normalize", "(", "self", ")", "->", "'State'", ":", "tensor", "=", "self", ".", "tensor", "/", "bk", ".", "ccast", "(", "bk", ".", "sqrt", "(", "self", ".", "norm", "(", ")", ")", ")", "return", "State", "(", "tensor", ",", "self", ".", ...
Normalize the state
[ "Normalize", "the", "state" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L108-L111
train
rigetti/quantumflow
quantumflow/states.py
State.sample
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...
python
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...
[ "def", "sample", "(", "self", ",", "trials", ":", "int", ")", "->", "np", ".", "ndarray", ":", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "res", "=", "np", ".", "random", ...
Measure the state in the computational basis the the given number of trials, and return the counts of each output configuration.
[ "Measure", "the", "state", "in", "the", "computational", "basis", "the", "the", "given", "number", "of", "trials", "and", "return", "the", "counts", "of", "each", "output", "configuration", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L121-L129
train
rigetti/quantumflow
quantumflow/states.py
State.expectation
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...
python
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...
[ "def", "expectation", "(", "self", ",", "diag_hermitian", ":", "bk", ".", "TensorLike", ",", "trials", ":", "int", "=", "None", ")", "->", "bk", ".", "BKTensor", ":", "if", "trials", "is", "None", ":", "probs", "=", "self", ".", "probabilities", "(", ...
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...
[ "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", "."...
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L131-L147
train
rigetti/quantumflow
quantumflow/states.py
State.measure
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(...
python
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(...
[ "def", "measure", "(", "self", ")", "->", "np", ".", "ndarray", ":", "probs", "=", "np", ".", "real", "(", "bk", ".", "evaluate", "(", "self", ".", "probabilities", "(", ")", ")", ")", "indices", "=", "np", ".", "asarray", "(", "list", "(", "np",...
Measure the state in the computational basis. Returns: A [2]*bits array of qubit states, either 0 or 1
[ "Measure", "the", "state", "in", "the", "computational", "basis", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L149-L160
train
rigetti/quantumflow
quantumflow/states.py
State.asdensity
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)
python
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)
[ "def", "asdensity", "(", "self", ")", "->", "'Density'", ":", "matrix", "=", "bk", ".", "outer", "(", "self", ".", "tensor", ",", "bk", ".", "conj", "(", "self", ".", "tensor", ")", ")", "return", "Density", "(", "matrix", ",", "self", ".", "qubits...
Convert a pure state to a density matrix
[ "Convert", "a", "pure", "state", "to", "a", "density", "matrix" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L162-L165
train
rigetti/quantumflow
tools/benchmark.py
benchmark
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...
python
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...
[ "def", "benchmark", "(", "N", ",", "gates", ")", ":", "qubits", "=", "list", "(", "range", "(", "0", ",", "N", ")", ")", "ket", "=", "qf", ".", "zero_state", "(", "N", ")", "for", "n", "in", "range", "(", "0", ",", "N", ")", ":", "ket", "="...
Create and run a circuit with N qubits and given number of gates
[ "Create", "and", "run", "a", "circuit", "with", "N", "qubits", "and", "given", "number", "of", "gates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/tools/benchmark.py#L31-L45
train
rigetti/quantumflow
examples/weyl.py
sandwich_decompositions
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...
python
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...
[ "def", "sandwich_decompositions", "(", "coords0", ",", "coords1", ",", "samples", "=", "SAMPLES", ")", ":", "decomps", "=", "[", "]", "for", "_", "in", "range", "(", "samples", ")", ":", "circ", "=", "qf", ".", "Circuit", "(", ")", "circ", "+=", "qf"...
Create composite gates, decompose, and return a list of canonical coordinates
[ "Create", "composite", "gates", "decompose", "and", "return", "a", "list", "of", "canonical", "coordinates" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/weyl.py#L82-L97
train
rigetti/quantumflow
quantumflow/paulialgebra.py
sX
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)
python
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)
[ "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
[ "Return", "the", "Pauli", "sigma_X", "operator", "acting", "on", "the", "given", "qubit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L224-L226
train
rigetti/quantumflow
quantumflow/paulialgebra.py
sY
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)
python
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)
[ "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
[ "Return", "the", "Pauli", "sigma_Y", "operator", "acting", "on", "the", "given", "qubit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L229-L231
train
rigetti/quantumflow
quantumflow/paulialgebra.py
sZ
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)
python
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)
[ "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
[ "Return", "the", "Pauli", "sigma_Z", "operator", "acting", "on", "the", "given", "qubit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L234-L236
train
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_sum
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...
python
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...
[ "def", "pauli_sum", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "terms", "=", "[", "]", "key", "=", "itemgetter", "(", "0", ")", "for", "term", ",", "grp", "in", "groupby", "(", "heapq", ".", "merge", "(", "*", "elements", ",", "...
Return the sum of elements of the Pauli algebra
[ "Return", "the", "sum", "of", "elements", "of", "the", "Pauli", "algebra" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L245-L255
train
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_product
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) ...
python
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) ...
[ "def", "pauli_product", "(", "*", "elements", ":", "Pauli", ")", "->", "Pauli", ":", "result_terms", "=", "[", "]", "for", "terms", "in", "product", "(", "*", "elements", ")", ":", "coeff", "=", "reduce", "(", "mul", ",", "[", "term", "[", "1", "]"...
Return the product of elements of the Pauli algebra
[ "Return", "the", "product", "of", "elements", "of", "the", "Pauli", "algebra" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L258-L279
train
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_pow
def pauli_pow(pauli: Pauli, exponent: int) -> Pauli: """ Raise an element of the Pauli algebra to a non-negative integer power. """ if not isinstance(exponent, int) or exponent < 0: raise ValueError("The exponent must be a non-negative integer.") if exponent == 0: return Pauli.iden...
python
def pauli_pow(pauli: Pauli, exponent: int) -> Pauli: """ Raise an element of the Pauli algebra to a non-negative integer power. """ if not isinstance(exponent, int) or exponent < 0: raise ValueError("The exponent must be a non-negative integer.") if exponent == 0: return Pauli.iden...
[ "def", "pauli_pow", "(", "pauli", ":", "Pauli", ",", "exponent", ":", "int", ")", "->", "Pauli", ":", "if", "not", "isinstance", "(", "exponent", ",", "int", ")", "or", "exponent", "<", "0", ":", "raise", "ValueError", "(", "\"The exponent must be a non-ne...
Raise an element of the Pauli algebra to a non-negative integer power.
[ "Raise", "an", "element", "of", "the", "Pauli", "algebra", "to", "a", "non", "-", "negative", "integer", "power", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L282-L308
train
rigetti/quantumflow
quantumflow/paulialgebra.py
pauli_commuting_sets
def pauli_commuting_sets(element: Pauli) -> Tuple[Pauli, ...]: """Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2 """ if len(ele...
python
def pauli_commuting_sets(element: Pauli) -> Tuple[Pauli, ...]: """Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2 """ if len(ele...
[ "def", "pauli_commuting_sets", "(", "element", ":", "Pauli", ")", "->", "Tuple", "[", "Pauli", ",", "...", "]", ":", "if", "len", "(", "element", ")", "<", "2", ":", "return", "(", "element", ",", ")", "groups", ":", "List", "[", "Pauli", "]", "=",...
Gather the terms of a Pauli polynomial into commuting sets. Uses the algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2
[ "Gather", "the", "terms", "of", "a", "Pauli", "polynomial", "into", "commuting", "sets", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L348-L372
train
rigetti/quantumflow
quantumflow/backend/numpybk.py
astensor
def astensor(array: TensorLike) -> BKTensor: """Converts a numpy array to the backend's tensor object """ array = np.asarray(array, dtype=CTYPE) return array
python
def astensor(array: TensorLike) -> BKTensor: """Converts a numpy array to the backend's tensor object """ array = np.asarray(array, dtype=CTYPE) return array
[ "def", "astensor", "(", "array", ":", "TensorLike", ")", "->", "BKTensor", ":", "array", "=", "np", ".", "asarray", "(", "array", ",", "dtype", "=", "CTYPE", ")", "return", "array" ]
Converts a numpy array to the backend's tensor object
[ "Converts", "a", "numpy", "array", "to", "the", "backend", "s", "tensor", "object" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L98-L102
train
rigetti/quantumflow
quantumflow/backend/numpybk.py
productdiag
def productdiag(tensor: BKTensor) -> BKTensor: """Returns the matrix diagonal of the product tensor""" # DOCME: Explain N = rank(tensor) tensor = reshape(tensor, [2**(N//2), 2**(N//2)]) tensor = np.diag(tensor) tensor = reshape(tensor, [2]*(N//2)) return tensor
python
def productdiag(tensor: BKTensor) -> BKTensor: """Returns the matrix diagonal of the product tensor""" # DOCME: Explain N = rank(tensor) tensor = reshape(tensor, [2**(N//2), 2**(N//2)]) tensor = np.diag(tensor) tensor = reshape(tensor, [2]*(N//2)) return tensor
[ "def", "productdiag", "(", "tensor", ":", "BKTensor", ")", "->", "BKTensor", ":", "N", "=", "rank", "(", "tensor", ")", "tensor", "=", "reshape", "(", "tensor", ",", "[", "2", "**", "(", "N", "//", "2", ")", ",", "2", "**", "(", "N", "//", "2",...
Returns the matrix diagonal of the product tensor
[ "Returns", "the", "matrix", "diagonal", "of", "the", "product", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L150-L156
train
rigetti/quantumflow
quantumflow/backend/numpybk.py
tensormul
def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor: r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math...
python
def tensormul(tensor0: BKTensor, tensor1: BKTensor, indices: typing.List[int]) -> BKTensor: r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math...
[ "def", "tensormul", "(", "tensor0", ":", "BKTensor", ",", "tensor1", ":", "BKTensor", ",", "indices", ":", "typing", ".", "List", "[", "int", "]", ")", "->", "BKTensor", ":", "r", "N", "=", "rank", "(", "tensor1", ")", "K", "=", "rank", "(", "tenso...
r""" Generalization of matrix multiplication to product tensors. A state vector in product tensor representation has N dimension, one for each contravariant index, e.g. for 3-qubit states :math:`B^{b_0,b_1,b_2}`. An operator has K dimensions, K/2 for contravariant indices (e.g. ket components) and ...
[ "r", "Generalization", "of", "matrix", "multiplication", "to", "product", "tensors", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/numpybk.py#L159-L214
train
rigetti/quantumflow
quantumflow/utils.py
invert_map
def invert_map(mapping: dict, one_to_one: bool = True) -> dict: """Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values. """ if one_to_one: inv_map = {value: key for key, value in mapping.items()} else: inv_map = {} for key,...
python
def invert_map(mapping: dict, one_to_one: bool = True) -> dict: """Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values. """ if one_to_one: inv_map = {value: key for key, value in mapping.items()} else: inv_map = {} for key,...
[ "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", "(", ...
Invert a dictionary. If not one_to_one then the inverted map will contain lists of former keys as values.
[ "Invert", "a", "dictionary", ".", "If", "not", "one_to_one", "then", "the", "inverted", "map", "will", "contain", "lists", "of", "former", "keys", "as", "values", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L38-L49
train
rigetti/quantumflow
quantumflow/utils.py
bitlist_to_int
def bitlist_to_int(bitlist: Sequence[int]) -> int: """Converts a sequence of bits to an integer. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4 """ return int(''.join([str(d) for d in bitlist]), 2)
python
def bitlist_to_int(bitlist: Sequence[int]) -> int: """Converts a sequence of bits to an integer. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4 """ return int(''.join([str(d) for d in bitlist]), 2)
[ "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. >>> from quantumflow.utils import bitlist_to_int >>> bitlist_to_int([1, 0, 0]) 4
[ "Converts", "a", "sequence", "of", "bits", "to", "an", "integer", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L52-L59
train
rigetti/quantumflow
quantumflow/utils.py
int_to_bitlist
def int_to_bitlist(x: int, pad: int = None) -> Sequence[int]: """Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) ...
python
def int_to_bitlist(x: int, pad: int = None) -> Sequence[int]: """Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) ...
[ "def", "int_to_bitlist", "(", "x", ":", "int", ",", "pad", ":", "int", "=", "None", ")", "->", "Sequence", "[", "int", "]", ":", "if", "pad", "is", "None", ":", "form", "=", "'{:0b}'", "else", ":", "form", "=", "'{:0'", "+", "str", "(", "pad", ...
Converts an integer to a binary sequence of bits. Pad prepends with sufficient zeros to ensures that the returned list contains at least this number of bits. >>> from quantumflow.utils import int_to_bitlist >>> int_to_bitlist(4, 4)) [0, 1, 0, 0]
[ "Converts", "an", "integer", "to", "a", "binary", "sequence", "of", "bits", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L62-L77
train
rigetti/quantumflow
quantumflow/utils.py
spanning_tree_count
def spanning_tree_count(graph: nx.Graph) -> int: """Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem. """ laplacian = nx.laplacian_matrix(graph).toarray() comatrix = laplacian[:-1, :-1] det = np.linalg.det(comatrix) count = int(round(det)) retu...
python
def spanning_tree_count(graph: nx.Graph) -> int: """Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem. """ laplacian = nx.laplacian_matrix(graph).toarray() comatrix = laplacian[:-1, :-1] det = np.linalg.det(comatrix) count = int(round(det)) retu...
[ "def", "spanning_tree_count", "(", "graph", ":", "nx", ".", "Graph", ")", "->", "int", ":", "laplacian", "=", "nx", ".", "laplacian_matrix", "(", "graph", ")", ".", "toarray", "(", ")", "comatrix", "=", "laplacian", "[", ":", "-", "1", ",", ":", "-",...
Return the number of unique spanning trees of a graph, using Kirchhoff's matrix tree theorem.
[ "Return", "the", "number", "of", "unique", "spanning", "trees", "of", "a", "graph", "using", "Kirchhoff", "s", "matrix", "tree", "theorem", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L108-L116
train
rigetti/quantumflow
quantumflow/utils.py
rationalize
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: """Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8...
python
def rationalize(flt: float, denominators: Set[int] = None) -> Fraction: """Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8...
[ "def", "rationalize", "(", "flt", ":", "float", ",", "denominators", ":", "Set", "[", "int", "]", "=", "None", ")", "->", "Fraction", ":", "if", "denominators", "is", "None", ":", "denominators", "=", "_DENOMINATORS", "frac", "=", "Fraction", ".", "from_...
Convert a floating point number to a Fraction with a small denominator. Args: flt: A floating point number denominators: Collection of standard denominators. Default is 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 ...
[ "Convert", "a", "floating", "point", "number", "to", "a", "Fraction", "with", "a", "small", "denominator", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L171-L189
train
rigetti/quantumflow
quantumflow/utils.py
symbolize
def symbolize(flt: float) -> sympy.Symbol: """Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float """ try...
python
def symbolize(flt: float) -> sympy.Symbol: """Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float """ try...
[ "def", "symbolize", "(", "flt", ":", "float", ")", "->", "sympy", ".", "Symbol", ":", "try", ":", "ratio", "=", "rationalize", "(", "flt", ")", "res", "=", "sympy", ".", "simplify", "(", "ratio", ")", "except", "ValueError", ":", "ratio", "=", "ratio...
Attempt to convert a real number into a simpler symbolic representation. Returns: A sympy Symbol. (Convert to string with str(sym) or to latex with sympy.latex(sym) Raises: ValueError: If cannot simplify float
[ "Attempt", "to", "convert", "a", "real", "number", "into", "a", "simpler", "symbolic", "representation", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/utils.py#L192-L208
train
rigetti/quantumflow
quantumflow/forest/__init__.py
pyquil_to_image
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover """Returns an image of a pyquil circuit. See circuit_to_latex() for more details. """ circ = pyquil_to_circuit(program) latex = circuit_to_latex(circ) img = render_latex(latex) return img
python
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover """Returns an image of a pyquil circuit. See circuit_to_latex() for more details. """ circ = pyquil_to_circuit(program) latex = circuit_to_latex(circ) img = render_latex(latex) return img
[ "def", "pyquil_to_image", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "PIL", ".", "Image", ":", "circ", "=", "pyquil_to_circuit", "(", "program", ")", "latex", "=", "circuit_to_latex", "(", "circ", ")", "img", "=", "render_latex", "(", "latex...
Returns an image of a pyquil circuit. See circuit_to_latex() for more details.
[ "Returns", "an", "image", "of", "a", "pyquil", "circuit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L160-L168
train
rigetti/quantumflow
quantumflow/forest/__init__.py
circuit_to_pyquil
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: """Convert a QuantumFlow circuit to a 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 [] ...
python
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: """Convert a QuantumFlow circuit to a 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 [] ...
[ "def", "circuit_to_pyquil", "(", "circuit", ":", "Circuit", ")", "->", "pyquil", ".", "Program", ":", "prog", "=", "pyquil", ".", "Program", "(", ")", "for", "elem", "in", "circuit", ".", "elements", ":", "if", "isinstance", "(", "elem", ",", "Gate", "...
Convert a QuantumFlow circuit to a pyQuil program
[ "Convert", "a", "QuantumFlow", "circuit", "to", "a", "pyQuil", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L171-L185
train
rigetti/quantumflow
quantumflow/forest/__init__.py
pyquil_to_circuit
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinst...
python
def pyquil_to_circuit(program: pyquil.Program) -> Circuit: """Convert a protoquil pyQuil program to a QuantumFlow Circuit""" circ = Circuit() for inst in program.instructions: # print(type(inst)) if isinstance(inst, pyquil.Declare): # Ignore continue if isinst...
[ "def", "pyquil_to_circuit", "(", "program", ":", "pyquil", ".", "Program", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "for", "inst", "in", "program", ".", "instructions", ":", "if", "isinstance", "(", "inst", ",", "pyquil", ".", "Declar...
Convert a protoquil pyQuil program to a QuantumFlow Circuit
[ "Convert", "a", "protoquil", "pyQuil", "program", "to", "a", "QuantumFlow", "Circuit" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L188-L213
train
rigetti/quantumflow
quantumflow/forest/__init__.py
quil_to_program
def quil_to_program(quil: str) -> Program: """Parse a quil program and return a Program object""" pyquil_instructions = pyquil.parser.parse(quil) return pyquil_to_program(pyquil_instructions)
python
def quil_to_program(quil: str) -> Program: """Parse a quil program and return a Program object""" pyquil_instructions = pyquil.parser.parse(quil) return pyquil_to_program(pyquil_instructions)
[ "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
[ "Parse", "a", "quil", "program", "and", "return", "a", "Program", "object" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L216-L219
train
rigetti/quantumflow
quantumflow/forest/__init__.py
state_to_wavefunction
def state_to_wavefunction(state: State) -> pyquil.Wavefunction: """Convert a QuantumFlow state to a pyQuil Wavefunction""" # TODO: qubits? amplitudes = state.vec.asarray() # pyQuil labels states backwards. amplitudes = amplitudes.transpose() amplitudes = amplitudes.reshape([amplitudes.size]) ...
python
def state_to_wavefunction(state: State) -> pyquil.Wavefunction: """Convert a QuantumFlow state to a pyQuil Wavefunction""" # TODO: qubits? amplitudes = state.vec.asarray() # pyQuil labels states backwards. amplitudes = amplitudes.transpose() amplitudes = amplitudes.reshape([amplitudes.size]) ...
[ "def", "state_to_wavefunction", "(", "state", ":", "State", ")", "->", "pyquil", ".", "Wavefunction", ":", "amplitudes", "=", "state", ".", "vec", ".", "asarray", "(", ")", "amplitudes", "=", "amplitudes", ".", "transpose", "(", ")", "amplitudes", "=", "am...
Convert a QuantumFlow state to a pyQuil Wavefunction
[ "Convert", "a", "QuantumFlow", "state", "to", "a", "pyQuil", "Wavefunction" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L350-L358
train
rigetti/quantumflow
quantumflow/forest/__init__.py
QuantumFlowQVM.load
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM': """ Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program """ assert self.status in ['connected', 'done'] prog = quil_to_program(str(binary)) self._pr...
python
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM': """ Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program """ assert self.status in ['connected', 'done'] prog = quil_to_program(str(binary)) self._pr...
[ "def", "load", "(", "self", ",", "binary", ":", "pyquil", ".", "Program", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'connected'", ",", "'done'", "]", "prog", "=", "quil_to_program", "(", "str", "(", "binary", ")", ...
Load a pyQuil program, and initialize QVM into a fresh state. Args: binary: A pyQuil program
[ "Load", "a", "pyQuil", "program", "and", "initialize", "QVM", "into", "a", "fresh", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L379-L394
train
rigetti/quantumflow
quantumflow/forest/__init__.py
QuantumFlowQVM.run
def run(self) -> 'QuantumFlowQVM': """Run a previously loaded program""" assert self.status in ['loaded'] self.status = 'running' self._ket = self._prog.run() # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's ...
python
def run(self) -> 'QuantumFlowQVM': """Run a previously loaded program""" assert self.status in ['loaded'] self.status = 'running' self._ket = self._prog.run() # Should set state to 'done' after run complete. # Makes no sense to keep status at running. But pyQuil's ...
[ "def", "run", "(", "self", ")", "->", "'QuantumFlowQVM'", ":", "assert", "self", ".", "status", "in", "[", "'loaded'", "]", "self", ".", "status", "=", "'running'", "self", ".", "_ket", "=", "self", ".", "_prog", ".", "run", "(", ")", "return", "self...
Run a previously loaded program
[ "Run", "a", "previously", "loaded", "program" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L401-L410
train
rigetti/quantumflow
quantumflow/forest/__init__.py
QuantumFlowQVM.wavefunction
def wavefunction(self) -> pyquil.Wavefunction: """ Return the wavefunction of a completed program. """ assert self.status == 'done' assert self._ket is not None wavefn = state_to_wavefunction(self._ket) return wavefn
python
def wavefunction(self) -> pyquil.Wavefunction: """ Return the wavefunction of a completed program. """ assert self.status == 'done' assert self._ket is not None wavefn = state_to_wavefunction(self._ket) return wavefn
[ "def", "wavefunction", "(", "self", ")", "->", "pyquil", ".", "Wavefunction", ":", "assert", "self", ".", "status", "==", "'done'", "assert", "self", ".", "_ket", "is", "not", "None", "wavefn", "=", "state_to_wavefunction", "(", "self", ".", "_ket", ")", ...
Return the wavefunction of a completed program.
[ "Return", "the", "wavefunction", "of", "a", "completed", "program", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/forest/__init__.py#L437-L444
train
rigetti/quantumflow
quantumflow/backend/torchbk.py
evaluate
def evaluate(tensor: BKTensor) -> TensorLike: """Return the value of a tensor""" 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...
python
def evaluate(tensor: BKTensor) -> TensorLike: """Return the value of a tensor""" 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...
[ "def", "evaluate", "(", "tensor", ":", "BKTensor", ")", "->", "TensorLike", ":", "if", "isinstance", "(", "tensor", ",", "_DTYPE", ")", ":", "if", "torch", ".", "numel", "(", "tensor", ")", "==", "1", ":", "return", "tensor", ".", "item", "(", ")", ...
Return the value of a tensor
[ "Return", "the", "value", "of", "a", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/torchbk.py#L91-L100
train
rigetti/quantumflow
quantumflow/backend/torchbk.py
rank
def rank(tensor: BKTensor) -> int: """Return the number of dimensions of a tensor""" if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
python
def rank(tensor: BKTensor) -> int: """Return the number of dimensions of a tensor""" if isinstance(tensor, np.ndarray): return len(tensor.shape) return len(tensor[0].size())
[ "def", "rank", "(", "tensor", ":", "BKTensor", ")", "->", "int", ":", "if", "isinstance", "(", "tensor", ",", "np", ".", "ndarray", ")", ":", "return", "len", "(", "tensor", ".", "shape", ")", "return", "len", "(", "tensor", "[", "0", "]", ".", "...
Return the number of dimensions of a tensor
[ "Return", "the", "number", "of", "dimensions", "of", "a", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/backend/torchbk.py#L136-L141
train
rigetti/quantumflow
quantumflow/measures.py
state_fidelity
def state_fidelity(state0: State, state1: State) -> bk.BKTensor: """Return the quantum fidelity between pure states.""" assert state0.qubits == state1.qubits # FIXME tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2) return tensor
python
def state_fidelity(state0: State, state1: State) -> bk.BKTensor: """Return the quantum fidelity between pure states.""" assert state0.qubits == state1.qubits # FIXME tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2) return tensor
[ "def", "state_fidelity", "(", "state0", ":", "State", ",", "state1", ":", "State", ")", "->", "bk", ".", "BKTensor", ":", "assert", "state0", ".", "qubits", "==", "state1", ".", "qubits", "tensor", "=", "bk", ".", "absolute", "(", "bk", ".", "inner", ...
Return the quantum fidelity between pure states.
[ "Return", "the", "quantum", "fidelity", "between", "pure", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L32-L36
train
rigetti/quantumflow
quantumflow/measures.py
state_angle
def state_angle(ket0: State, ket1: State) -> bk.BKTensor: """The Fubini-Study angle between states. Equal to the Burrs angle for pure states. """ return fubini_study_angle(ket0.vec, ket1.vec)
python
def state_angle(ket0: State, ket1: State) -> bk.BKTensor: """The Fubini-Study angle between states. Equal to the Burrs angle for pure states. """ return fubini_study_angle(ket0.vec, ket1.vec)
[ "def", "state_angle", "(", "ket0", ":", "State", ",", "ket1", ":", "State", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "ket0", ".", "vec", ",", "ket1", ".", "vec", ")" ]
The Fubini-Study angle between states. Equal to the Burrs angle for pure states.
[ "The", "Fubini", "-", "Study", "angle", "between", "states", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L39-L44
train
rigetti/quantumflow
quantumflow/measures.py
states_close
def states_close(state0: State, state1: State, tolerance: float = TOLERANCE) -> bool: """Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(state0.vec, state1.vec, tolerance)
python
def states_close(state0: State, state1: State, tolerance: float = TOLERANCE) -> bool: """Returns True if states are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(state0.vec, state1.vec, tolerance)
[ "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. Closeness is measured with the metric Fubini-Study angle.
[ "Returns", "True", "if", "states", "are", "almost", "identical", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L47-L53
train
rigetti/quantumflow
quantumflow/measures.py
purity
def purity(rho: Density) -> bk.BKTensor: """ Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are ...
python
def purity(rho: Density) -> bk.BKTensor: """ Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are ...
[ "def", "purity", "(", "rho", ":", "Density", ")", "->", "bk", ".", "BKTensor", ":", "tensor", "=", "rho", ".", "tensor", "N", "=", "rho", ".", "qubit_nb", "matrix", "=", "bk", ".", "reshape", "(", "tensor", ",", "[", "2", "**", "N", ",", "2", "...
Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are the linear entropy, 1- purity, and the participat...
[ "Calculate", "the", "purity", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L59-L73
train
rigetti/quantumflow
quantumflow/measures.py
bures_distance
def bures_distance(rho0: Density, rho1: Density) -> float: """Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend. """ fid = fidelity(rho0, rho1) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) tr0 = np...
python
def bures_distance(rho0: Density, rho1: Density) -> float: """Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend. """ fid = fidelity(rho0, rho1) op0 = asarray(rho0.asoperator()) op1 = asarray(rho1.asoperator()) tr0 = np...
[ "def", "bures_distance", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "float", ":", "fid", "=", "fidelity", "(", "rho0", ",", "rho1", ")", "op0", "=", "asarray", "(", "rho0", ".", "asoperator", "(", ")", ")", "op1", "=", "as...
Return the Bures distance between mixed quantum states Note: Bures distance cannot be calculated within the tensor backend.
[ "Return", "the", "Bures", "distance", "between", "mixed", "quantum", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L95-L106
train
rigetti/quantumflow
quantumflow/measures.py
bures_angle
def bures_angle(rho0: Density, rho1: Density) -> float: """Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend. """ return np.arccos(np.sqrt(fidelity(rho0, rho1)))
python
def bures_angle(rho0: Density, rho1: Density) -> float: """Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend. """ return np.arccos(np.sqrt(fidelity(rho0, rho1)))
[ "def", "bures_angle", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "float", ":", "return", "np", ".", "arccos", "(", "np", ".", "sqrt", "(", "fidelity", "(", "rho0", ",", "rho1", ")", ")", ")" ]
Return the Bures angle between mixed quantum states Note: Bures angle cannot be calculated within the tensor backend.
[ "Return", "the", "Bures", "angle", "between", "mixed", "quantum", "states" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L110-L115
train
rigetti/quantumflow
quantumflow/measures.py
density_angle
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor: """The Fubini-Study angle between density matrices""" return fubini_study_angle(rho0.vec, rho1.vec)
python
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor: """The Fubini-Study angle between density matrices""" return fubini_study_angle(rho0.vec, rho1.vec)
[ "def", "density_angle", "(", "rho0", ":", "Density", ",", "rho1", ":", "Density", ")", "->", "bk", ".", "BKTensor", ":", "return", "fubini_study_angle", "(", "rho0", ".", "vec", ",", "rho1", ".", "vec", ")" ]
The Fubini-Study angle between density matrices
[ "The", "Fubini", "-", "Study", "angle", "between", "density", "matrices" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L118-L120
train
rigetti/quantumflow
quantumflow/measures.py
densities_close
def densities_close(rho0: Density, rho1: Density, tolerance: float = TOLERANCE) -> bool: """Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(rho0.vec, rho1.vec, tolerance)
python
def densities_close(rho0: Density, rho1: Density, tolerance: float = TOLERANCE) -> bool: """Returns True if densities are almost identical. Closeness is measured with the metric Fubini-Study angle. """ return vectors_close(rho0.vec, rho1.vec, tolerance)
[ "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. Closeness is measured with the metric Fubini-Study angle.
[ "Returns", "True", "if", "densities", "are", "almost", "identical", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L123-L129
train
rigetti/quantumflow
quantumflow/measures.py
entropy
def entropy(rho: Density, base: float = None) -> float: """ Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: ...
python
def entropy(rho: Density, base: float = None) -> float: """ Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: ...
[ "def", "entropy", "(", "rho", ":", "Density", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "op", "=", "asarray", "(", "rho", ".", "asoperator", "(", ")", ")", "probs", "=", "np", ".", "linalg", ".", "eigvalsh", "(", "op", ")",...
Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: The von-Neumann entropy of rho
[ "Returns", "the", "von", "-", "Neumann", "entropy", "of", "a", "mixed", "quantum", "state", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/measures.py#L133-L148
train