code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def parseString(self, string): """Parse a document from a string, returning the document node.""" parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
Parse a document from a string, returning the document node.
parseString
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def _setup_subset(self, buffer): """Load the internal subset if there might be one.""" if self.document.doctype: extractor = InternalSubsetExtractor() extractor.parseString(buffer) subset = extractor.getSubset() self.document.doctype.internalSubset = subset
Load the internal subset if there might be one.
_setup_subset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def parseString(self, string): """Parse a document fragment from a string, returning the fragment node.""" self._source = string parser = self.getParser() doctype = self.originalDocument.doctype ident = "" if doctype: subset = doctype.internalSubset or self._getDeclarations() if doctype.publicId: ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId)) elif doctype.systemId: ident = 'SYSTEM "%s"' % doctype.systemId else: subset = "" nsattrs = self._getNSattrs() # get ns decls from node's ancestors document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs) try: parser.Parse(document, 1) except: self.reset() raise fragment = self.fragment self.reset() ## self._parser = None return fragment
Parse a document fragment from a string, returning the fragment node.
parseString
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def _getDeclarations(self): """Re-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string. """ doctype = self.context.ownerDocument.doctype s = "" if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = s + "\n " s = "%s<!NOTATION %s" % (s, notation.nodeName) if notation.publicId: s = '%s PUBLIC "%s"\n "%s">' \ % (s, notation.publicId, notation.systemId) else: s = '%s SYSTEM "%s">' % (s, notation.systemId) for i in range(doctype.entities.length): entity = doctype.entities.item(i) if s: s = s + "\n " s = "%s<!ENTITY %s" % (s, entity.nodeName) if entity.publicId: s = '%s PUBLIC "%s"\n "%s"' \ % (s, entity.publicId, entity.systemId) elif entity.systemId: s = '%s SYSTEM "%s"' % (s, entity.systemId) else: s = '%s "%s"' % (s, entity.firstChild.data) if entity.notationName: s = "%s NOTATION %s" % (s, entity.notationName) s = s + ">" return s
Re-create the internal subset from the DocumentType node. This is only needed if we don't already have the internalSubset as a string.
_getDeclarations
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def install(self, parser): """Insert the namespace-handlers onto the parser.""" ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = ( self.start_namespace_decl_handler)
Insert the namespace-handlers onto the parser.
install
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def _getNSattrs(self): """Return string of namespace attributes from this element and ancestors.""" # XXX This needs to be re-written to walk the ancestors of the # context to build up the namespace information from # declarations, elements, and attributes found in context. # Otherwise we have to store a bunch more data on the DOM # (though that *might* be more reliable -- not clear). attrs = "" context = self.context L = [] while context: if hasattr(context, '_ns_prefix_uri'): for prefix, uri in context._ns_prefix_uri.items(): # add every new NS decl from context to L and attrs string if prefix in L: continue L.append(prefix) if prefix: declname = "xmlns:" + prefix else: declname = "xmlns" if attrs: attrs = "%s\n %s='%s'" % (attrs, declname, uri) else: attrs = " %s='%s'" % (declname, uri) context = context.parentNode return attrs
Return string of namespace attributes from this element and ancestors.
_getNSattrs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def parse(file, namespaces=True): """Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() if isinstance(file, StringTypes): fp = open(file, 'rb') try: result = builder.parseFile(fp) finally: fp.close() else: result = builder.parseFile(file) return result
Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object.
parse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def parseString(string, namespaces=True): """Parse a document from a string, returning the resulting Document node. """ if namespaces: builder = ExpatBuilderNS() else: builder = ExpatBuilder() return builder.parseString(string)
Parse a document from a string, returning the resulting Document node.
parseString
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def parseFragment(file, context, namespaces=True): """Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) if isinstance(file, StringTypes): fp = open(file, 'rb') try: result = builder.parseFile(fp) finally: fp.close() else: result = builder.parseFile(file) return result
Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object.
parseFragment
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def parseFragmentString(string, context, namespaces=True): """Parse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) return builder.parseString(string)
Parse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment.
parseFragmentString
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def makeBuilder(options): """Create a builder based on an Options object.""" if options.namespaces: return ExpatBuilderNS(options) else: return ExpatBuilder(options)
Create a builder based on an Options object.
makeBuilder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/expatbuilder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/expatbuilder.py
MIT
def _clone_node(node, deep, newOwnerDocument): """ Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode """ if node.ownerDocument.isSameNode(newOwnerDocument): operation = xml.dom.UserDataHandler.NODE_CLONED else: operation = xml.dom.UserDataHandler.NODE_IMPORTED if node.nodeType == Node.ELEMENT_NODE: clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName) for attr in node.attributes.values(): clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) a.specified = attr.specified if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: clone = newOwnerDocument.createDocumentFragment() if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.TEXT_NODE: clone = newOwnerDocument.createTextNode(node.data) elif node.nodeType == Node.CDATA_SECTION_NODE: clone = newOwnerDocument.createCDATASection(node.data) elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: clone = newOwnerDocument.createProcessingInstruction(node.target, node.data) elif node.nodeType == Node.COMMENT_NODE: clone = newOwnerDocument.createComment(node.data) elif node.nodeType == Node.ATTRIBUTE_NODE: clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName) clone.specified = True clone.value = node.value elif node.nodeType == Node.DOCUMENT_TYPE_NODE: assert node.ownerDocument is not newOwnerDocument operation = xml.dom.UserDataHandler.NODE_IMPORTED clone = newOwnerDocument.implementation.createDocumentType( node.name, node.publicId, node.systemId) clone.ownerDocument = newOwnerDocument if deep: clone.entities._seq = [] clone.notations._seq = [] for n in node.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) notation.ownerDocument = newOwnerDocument clone.notations._seq.append(notation) if hasattr(n, '_call_user_data_handler'): n._call_user_data_handler(operation, n, notation) for e in node.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version entity.ownerDocument = newOwnerDocument clone.entities._seq.append(entity) if hasattr(e, '_call_user_data_handler'): e._call_user_data_handler(operation, n, entity) else: # Note the cloning of Document and DocumentType nodes is # implementation specific. minidom handles those cases # directly in the cloneNode() methods. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node)) # Check for _call_user_data_handler() since this could conceivably # used with other DOM implementations (one of the FourThought # DOMs, perhaps?). if hasattr(node, '_call_user_data_handler'): node._call_user_data_handler(operation, node, clone) return clone
Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode
_clone_node
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/minidom.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/minidom.py
MIT
def parse(file, parser=None, bufsize=None): """Parse a file into a DOM by filename or file object.""" if parser is None and not bufsize: from xml.dom import expatbuilder return expatbuilder.parse(file) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parse, (file,), {'parser': parser, 'bufsize': bufsize})
Parse a file into a DOM by filename or file object.
parse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/minidom.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/minidom.py
MIT
def parseString(string, parser=None): """Parse a file into a DOM from a string.""" if parser is None: from xml.dom import expatbuilder return expatbuilder.parseString(string) else: from xml.dom import pulldom return _do_pulldom_parse(pulldom.parseString, (string,), {'parser': parser})
Parse a file into a DOM from a string.
parseString
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/minidom.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/minidom.py
MIT
def _slurp(self): """ Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers). """ self.parser.parse(self.stream) self.getEvent = self._emit return self._emit()
Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers).
_slurp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/dom/pulldom.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/dom/pulldom.py
MIT
def doctype(self, name, pubid, system): """This method of XMLParser is deprecated.""" warnings.warn( "This method of XMLParser is deprecated. Define doctype() " "method on the TreeBuilder target.", DeprecationWarning, )
This method of XMLParser is deprecated.
doctype
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/etree/ElementTree.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/etree/ElementTree.py
MIT
def parse(self, source): "Parse an XML document from a URL or an InputSource." source = saxutils.prepare_input_source(source) self._source = source self.reset() self._cont_handler.setDocumentLocator(ExpatLocator(self)) xmlreader.IncrementalParser.parse(self, source)
Parse an XML document from a URL or an InputSource.
parse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/expatreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/expatreader.py
MIT
def startDocument(self): """Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator)."""
Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).
startDocument
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def endDocument(self): """Receive notification of the end of a document. The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input."""
Receive notification of the end of a document. The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input.
endDocument
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def startPrefixMapping(self, prefix, uri): """Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary. Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed."""
Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary. Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed.
startPrefixMapping
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def endPrefixMapping(self, prefix): """End the scope of a prefix-URI mapping. See startPrefixMapping for details. This event will always occur after the corresponding endElement event, but the order of endPrefixMapping events is not otherwise guaranteed."""
End the scope of a prefix-URI mapping. See startPrefixMapping for details. This event will always occur after the corresponding endElement event, but the order of endPrefixMapping events is not otherwise guaranteed.
endPrefixMapping
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def startElement(self, name, attrs): """Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an instance of the Attributes class containing the attributes of the element."""
Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an instance of the Attributes class containing the attributes of the element.
startElement
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def endElement(self, name): """Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement event."""
Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement event.
endElement
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def startElementNS(self, name, qname, attrs): """Signals the start of an element in namespace mode. The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter the raw XML 1.0 name used in the source document, and the attrs parameter holds an instance of the Attributes class containing the attributes of the element. The uri part of the name tuple is None for elements which have no namespace."""
Signals the start of an element in namespace mode. The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter the raw XML 1.0 name used in the source document, and the attrs parameter holds an instance of the Attributes class containing the attributes of the element. The uri part of the name tuple is None for elements which have no namespace.
startElementNS
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def endElementNS(self, name, qname): """Signals the end of an element in namespace mode. The name parameter contains the name of the element type, just as with the startElementNS event."""
Signals the end of an element in namespace mode. The name parameter contains the name of the element type, just as with the startElementNS event.
endElementNS
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def characters(self, content): """Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information."""
Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.
characters
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def ignorableWhitespace(self, whitespace): """Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information."""
Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.
ignorableWhitespace
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def processingInstruction(self, target, data): """Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method."""
Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.
processingInstruction
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def skippedEntity(self, name): """Receive notification of a skipped entity. The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the http://xml.org/sax/features/external-general-entities and the http://xml.org/sax/features/external-parameter-entities properties."""
Receive notification of a skipped entity. The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the http://xml.org/sax/features/external-general-entities and the http://xml.org/sax/features/external-parameter-entities properties.
skippedEntity
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/handler.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/handler.py
MIT
def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s
Replace substrings of a string using a dictionary.
__dict_replace
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/saxutils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/saxutils.py
MIT
def escape(data, entities={}): """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ # must do ampersand first data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") if entities: data = __dict_replace(data, entities) return data
Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value.
escape
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/saxutils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/saxutils.py
MIT
def unescape(data, entities={}): """Unescape &amp;, &lt;, and &gt; in a string of data. You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ data = data.replace("&lt;", "<") data = data.replace("&gt;", ">") if entities: data = __dict_replace(data, entities) # must do ampersand last return data.replace("&amp;", "&")
Unescape &amp;, &lt;, and &gt; in a string of data. You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value.
unescape
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/saxutils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/saxutils.py
MIT
def quoteattr(data, entities={}): """Escape and quote an attribute value. Escape &, <, and > in a string of data, then quote it for use as an attribute value. The \" character will be escaped as well, if necessary. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ entities = entities.copy() entities.update({'\n': '&#10;', '\r': '&#13;', '\t':'&#9;'}) data = escape(data, entities) if '"' in data: if "'" in data: data = '"%s"' % data.replace('"', "&quot;") else: data = "'%s'" % data else: data = '"%s"' % data return data
Escape and quote an attribute value. Escape &, <, and > in a string of data, then quote it for use as an attribute value. The " character will be escaped as well, if necessary. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value.
quoteattr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/saxutils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/saxutils.py
MIT
def _qname(self, name): """Builds a qualified name from a (ns_url, localname) pair""" if name[0]: # Per http://www.w3.org/XML/1998/namespace, The 'xml' prefix is # bound by definition to http://www.w3.org/XML/1998/namespace. It # does not need to be declared and will not usually be found in # self._current_context. if 'http://www.w3.org/XML/1998/namespace' == name[0]: return 'xml:' + name[1] # The name is in a non-empty namespace prefix = self._current_context[name[0]] if prefix: # If it is not the default namespace, prepend the prefix return prefix + ":" + name[1] # Return the unqualified name return name[1]
Builds a qualified name from a (ns_url, localname) pair
_qname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/saxutils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/saxutils.py
MIT
def prepare_input_source(source, base = ""): """This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.""" if type(source) in _StringTypes: source = xmlreader.InputSource(source) elif hasattr(source, "read"): f = source source = xmlreader.InputSource() source.setByteStream(f) if hasattr(f, "name"): source.setSystemId(f.name) if source.getByteStream() is None: try: sysid = source.getSystemId() basehead = os.path.dirname(os.path.normpath(base)) encoding = sys.getfilesystemencoding() if isinstance(sysid, unicode): if not isinstance(basehead, unicode): try: basehead = basehead.decode(encoding) except UnicodeDecodeError: sysid = sysid.encode(encoding) else: if isinstance(basehead, unicode): try: sysid = sysid.decode(encoding) except UnicodeDecodeError: basehead = basehead.encode(encoding) sysidfilename = os.path.join(basehead, sysid) isfile = os.path.isfile(sysidfilename) except UnicodeError: isfile = False if isfile: source.setSystemId(sysidfilename) f = open(sysidfilename, "rb") else: source.setSystemId(urlparse.urljoin(base, source.getSystemId())) f = urllib.urlopen(source.getSystemId()) source.setByteStream(f) return source
This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.
prepare_input_source
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/saxutils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/saxutils.py
MIT
def parse(self, source): "Parse an XML document from a system identifier or an InputSource." raise NotImplementedError("This method must be implemented!")
Parse an XML document from a system identifier or an InputSource.
parse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def setContentHandler(self, handler): "Registers a new object to receive document content events." self._cont_handler = handler
Registers a new object to receive document content events.
setContentHandler
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def setDTDHandler(self, handler): "Register an object to receive basic DTD-related events." self._dtd_handler = handler
Register an object to receive basic DTD-related events.
setDTDHandler
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def setEntityResolver(self, resolver): "Register an object to resolve external entities." self._ent_handler = resolver
Register an object to resolve external entities.
setEntityResolver
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def setErrorHandler(self, handler): "Register an object to receive error-message events." self._err_handler = handler
Register an object to receive error-message events.
setErrorHandler
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def getFeature(self, name): "Looks up and returns the state of a SAX2 feature." raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
Looks up and returns the state of a SAX2 feature.
getFeature
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def getProperty(self, name): "Looks up and returns the value of a SAX2 property." raise SAXNotRecognizedException("Property '%s' not recognized" % name)
Looks up and returns the value of a SAX2 property.
getProperty
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def setPublicId(self, public_id): "Sets the public identifier of this InputSource." self.__public_id = public_id
Sets the public identifier of this InputSource.
setPublicId
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def setSystemId(self, system_id): "Sets the system identifier of this InputSource." self.__system_id = system_id
Sets the system identifier of this InputSource.
setSystemId
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def __init__(self, attrs, qnames): """NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.""" self._attrs = attrs self._qnames = qnames
NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/xmlreader.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/xmlreader.py
MIT
def __init__(self, msg, exception=None): """Creates an exception. The message is required, but the exception is optional.""" self._msg = msg self._exception = exception Exception.__init__(self, msg)
Creates an exception. The message is required, but the exception is optional.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/_exceptions.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/_exceptions.py
MIT
def __init__(self, msg, exception, locator): "Creates the exception. The exception parameter is allowed to be None." SAXException.__init__(self, msg, exception) self._locator = locator # We need to cache this stuff at construction time. # If this exception is raised, the objects through which we must # traverse to get this information may be deleted by the time # it gets caught. self._systemId = self._locator.getSystemId() self._colnum = self._locator.getColumnNumber() self._linenum = self._locator.getLineNumber()
Creates the exception. The exception parameter is allowed to be None.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/_exceptions.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/_exceptions.py
MIT
def __str__(self): "Create a string representation of the exception." sysid = self.getSystemId() if sysid is None: sysid = "<unknown>" linenum = self.getLineNumber() if linenum is None: linenum = "?" colnum = self.getColumnNumber() if colnum is None: colnum = "?" return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg)
Create a string representation of the exception.
__str__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/_exceptions.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/_exceptions.py
MIT
def make_parser(parser_list = []): """Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the list created by doing parser_list + default_parser_list. The lists must contain the names of Python modules containing both a SAX parser and a create_parser function.""" for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) except ImportError,e: import sys if parser_name in sys.modules: # The parser module was found, but importing it # failed unexpectedly, pass this exception through raise except SAXReaderNotAvailable: # The parser module detected that it won't work properly, # so try the next one pass raise SAXReaderNotAvailable("No parsers found", None)
Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the list created by doing parser_list + default_parser_list. The lists must contain the names of Python modules containing both a SAX parser and a create_parser function.
make_parser
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/xml/sax/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/xml/sax/__init__.py
MIT
def _find_toml_section_end(lines, start): """Find the index of the start of the next section.""" return ( next(filter(itemgetter(1), enumerate(line.startswith('[') for line in lines[start + 1 :])))[0] + start + 1 )
Find the index of the start of the next section.
_find_toml_section_end
python
ProjectQ-Framework/ProjectQ
setup.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py
Apache-2.0
def _parse_list(lines): """Parse a TOML list into a Python list.""" # NB: This function expects the TOML list to be formatted like so (ignoring leading and trailing spaces): # name = [ # '...', # ] # Any other format is not supported. name = None elements = [] for idx, line in enumerate(lines): if name is None and not line.startswith("'"): name = line.split('=')[0].strip() continue if line.startswith("]"): return (name, elements, idx + 1) elements.append(line.rstrip(',').strip("'").strip('"')) raise RuntimeError(f'Failed to locate closing "]" for {name}')
Parse a TOML list into a Python list.
_parse_list
python
ProjectQ-Framework/ProjectQ
setup.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py
Apache-2.0
def parse_toml(filename): """Very simple parser routine for pyproject.toml.""" result = {'project': {'optional-dependencies': {}}} with open(filename) as toml_file: lines = [line.strip() for line in toml_file.readlines()] lines = [line for line in lines if line and not line.startswith('#')] start = lines.index('[project]') project_data = lines[start : _find_toml_section_end(lines, start)] start = lines.index('[project.optional-dependencies]') optional_dependencies = lines[start + 1 : _find_toml_section_end(lines, start)] idx = 0 N = len(project_data) while idx < N: line = project_data[idx] shift = 1 if line.startswith('name'): result['project']['name'] = line.split('=')[1].strip().strip("'") elif line.startswith('dependencies'): (name, pkgs, shift) = _parse_list(project_data[idx:]) result['project'][name] = pkgs idx += shift idx = 0 N = len(optional_dependencies) while idx < N: (opt_name, opt_pkgs, shift) = _parse_list(optional_dependencies[idx:]) result['project']['optional-dependencies'][opt_name] = opt_pkgs idx += shift return result
Very simple parser routine for pyproject.toml.
parse_toml
python
ProjectQ-Framework/ProjectQ
setup.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py
Apache-2.0
def compiler_test( compiler, flagname=None, link_executable=False, link_shared_lib=False, include='', body='', compile_postargs=None, link_postargs=None, ): # pylint: disable=too-many-arguments,too-many-branches """Return a boolean indicating whether a flag name is supported on the specified compiler.""" fname = None with tempfile.NamedTemporaryFile('w', suffix='.cpp', delete=False) as temp: temp.write(f'{include}\nint main (int argc, char **argv) {{ {body} return 0; }}') fname = temp.name if compile_postargs is None: compile_postargs = [flagname] if flagname is not None else None elif flagname is not None: compile_postargs.append(flagname) try: if compiler.compiler_type == 'msvc': olderr = os.dup(sys.stderr.fileno()) err = open('err.txt', 'w') # pylint: disable=consider-using-with os.dup2(err.fileno(), sys.stderr.fileno()) obj_file = compiler.compile([fname], extra_postargs=compile_postargs) if not os.path.exists(obj_file[0]): raise RuntimeError('') if link_executable: compiler.link_executable(obj_file, os.path.join(tempfile.mkdtemp(), 'test'), extra_postargs=link_postargs) elif link_shared_lib: if sys.platform == 'win32': lib_name = os.path.join(tempfile.mkdtemp(), 'test.dll') else: lib_name = os.path.join(tempfile.mkdtemp(), 'test.so') compiler.link_shared_lib(obj_file, lib_name, extra_postargs=link_postargs) if compiler.compiler_type == 'msvc': err.close() os.dup2(olderr, sys.stderr.fileno()) with open('err.txt') as err_file: if err_file.readlines(): raise RuntimeError('') except Exception: # pylint: disable=broad-except return False else: return True finally: os.unlink(fname)
Return a boolean indicating whether a flag name is supported on the specified compiler.
compiler_test
python
ProjectQ-Framework/ProjectQ
setup.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py
Apache-2.0
def has_ext_modules(self): """Return whether this distribution has some external modules.""" # We want to always claim that we have ext_modules. This will be fine # if we don't actually have them (such as on PyPy) because nothing # will get built, however we don't want to provide an overally broad # Wheel package when building a wheel without C support. This will # ensure that Wheel knows to treat us as if the build output is # platform specific. return True
Return whether this distribution has some external modules.
has_ext_modules
python
ProjectQ-Framework/ProjectQ
setup.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/setup.py
Apache-2.0
def recursive_getattr(obj, attr, *args): """Recursively get the attributes of a Python object.""" def _getattr(obj, attr): return getattr(obj, attr, *args) return functools.reduce(_getattr, [obj] + attr.split('.'))
Recursively get the attributes of a Python object.
recursive_getattr
python
ProjectQ-Framework/ProjectQ
docs/conf.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/docs/conf.py
Apache-2.0
def linkcode_resolve(domain, info): """Change URLs in documentation on the fly.""" # Copyright 2018 ProjectQ (www.projectq.ch), all rights reserved. on_rtd = os.environ.get('READTHEDOCS') == 'True' github_url = "https://github.com/ProjectQ-Framework/ProjectQ/tree/" github_tag = 'v' + version if on_rtd: rtd_tag = os.environ.get('READTHEDOCS_VERSION') if rtd_tag == 'latest': github_tag = 'develop' elif rtd_tag == 'stable': github_tag = 'master' else: # RTD changes "/" in branch name to "-" # As we use branches like fix/cool-feature, this is a # problem -> as a fix we require that all branch names # which contain a '-' must first contain one '/': if list(rtd_tag).count('-'): github_tag = list(rtd_tag) github_tag[github_tag.index('-')] = '/' github_tag = ''.join(github_tag) else: github_tag = rtd_tag if domain != 'py': return None try: module = importlib.import_module(info['module']) obj = recursive_getattr(module, info['fullname']) except (AttributeError, ValueError): # AttributeError: # Object might be a non-static attribute of a class, e.g., self.num_qubits, which would only exist after init # was called. # For the moment we don't need a link for that as there is a link for the class already # # ValueError: # info['module'] is empty return None try: filepath = inspect.getsourcefile(obj) line_number = inspect.getsourcelines(obj)[1] except TypeError: # obj might be a property or a static class variable, e.g., # loop_tag_id in which case obj is an int and inspect will fail try: # load obj one hierarchy higher (either class or module) new_higher_name = info['fullname'].split('.') module = importlib.import_module(info['module']) if len(new_higher_name) > 1: obj = module else: obj = recursive_getattr(module, '.' + '.'.join(new_higher_name[:-1])) filepath = inspect.getsourcefile(obj) line_number = inspect.getsourcelines(obj)[1] except AttributeError: return None # Calculate the relative path of the object with respect to the root directory (ie. projectq/some/path/to/a/file.py) projectq_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) + os.path.sep idx = len(projectq_path) relative_path = filepath[idx:] url = github_url + github_tag + "/" + relative_path + "#L" + str(line_number) return url
Change URLs in documentation on the fly.
linkcode_resolve
python
ProjectQ-Framework/ProjectQ
docs/conf.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/docs/conf.py
Apache-2.0
def __init__( # pylint: disable=too-many-arguments self, pkg_name, desc='', module_special_members='__init__', submodule_special_members='', submodules_desc='', helper_submodules=None, ): """ Initialize a PackageDescription object. Args: name (str): Name of ProjectQ module desc (str): (optional) Description of module module_special_members (str): (optional) Special members to include in the documentation of the module submodule_special_members (str): (optional) Special members to include in the documentation of submodules submodules_desc (str): (optional) Description to print out before the list of submodules helper_submodules (list): (optional) List of tuples for helper sub-modules to include in the documentation. Tuples are (section_title, submodukle_name, automodule_properties) """ self.name = pkg_name self.desc = desc if pkg_name not in PackageDescription.package_list: PackageDescription.package_list.append(pkg_name) self.module = importlib.import_module(f'projectq.{self.name}') self.module_special_members = module_special_members self.submodule_special_members = submodule_special_members self.submodules_desc = submodules_desc self.helper_submodules = helper_submodules sub = [] for _, module_name, _ in pkgutil.iter_modules(self.module.__path__, self.module.__name__ + '.'): if not module_name.endswith('_test'): try: idx = len(self.module.__name__) + 1 sub.append((module_name[idx:], importlib.import_module(module_name))) except ImportError: pass self.subpackages = [] self.submodules = [] for name, obj in sub: if f'{self.name}.{name}' in PackageDescription.package_list: self.subpackages.append((name, obj)) else: self.submodules.append((name, obj)) self.subpackages.sort(key=lambda x: x[0].lower()) self.submodules.sort(key=lambda x: x[0].lower()) self.members = [ (name, obj) for name, obj in inspect.getmembers( self.module, lambda obj: ( inspect.isclass(obj) or inspect.isfunction(obj) or isinstance(obj, (int, float, tuple, list, dict, set, frozenset, str)) ), ) if name[0] != '_' ] self.members.sort(key=lambda x: x[0].lower())
Initialize a PackageDescription object. Args: name (str): Name of ProjectQ module desc (str): (optional) Description of module module_special_members (str): (optional) Special members to include in the documentation of the module submodule_special_members (str): (optional) Special members to include in the documentation of submodules submodules_desc (str): (optional) Description to print out before the list of submodules helper_submodules (list): (optional) List of tuples for helper sub-modules to include in the documentation. Tuples are (section_title, submodukle_name, automodule_properties)
__init__
python
ProjectQ-Framework/ProjectQ
docs/package_description.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/docs/package_description.py
Apache-2.0
def run_entangle(eng, num_qubits=3): """ Run an entangling operation on the provided compiler engine. Args: eng (MainEngine): Main compiler engine to use. num_qubits (int): Number of qubits to entangle. Returns: measurement (list<int>): List of measurement outcomes. """ # allocate the quantum register to entangle qureg = eng.allocate_qureg(num_qubits) # entangle the qureg Entangle | qureg # measure; should be all-0 or all-1 All(Measure) | qureg # run the circuit eng.flush() # access the probabilities via the back-end: # results = eng.backend.get_probabilities(qureg) # for state in results: # print(f"Measured {state} with p = {results[state]}.") # or plot them directly: histogram(eng.backend, qureg) plt.show() # return one (random) measurement outcome. return [int(q) for q in qureg]
Run an entangling operation on the provided compiler engine. Args: eng (MainEngine): Main compiler engine to use. num_qubits (int): Number of qubits to entangle. Returns: measurement (list<int>): List of measurement outcomes.
run_entangle
python
ProjectQ-Framework/ProjectQ
examples/aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/aqt.py
Apache-2.0
def zoo_profile(): """Generate and display the zoo of quantum gates.""" # create a main compiler engine with a drawing backend drawing_engine = CircuitDrawer() locations = {0: 1, 1: 2, 2: 0, 3: 3} drawing_engine.set_qubit_locations(locations) main_eng = MainEngine(drawing_engine) qureg = main_eng.allocate_qureg(4) # define a zoo of gates te_gate = TimeEvolution(0.5, 0.1 * QubitOperator('X0 Y2')) def add(x, y): return x, y + 1 zoo = [ (X, 3), (Y, 2), (Z, 0), (Rx(0.5), 2), (Ry(0.5), 1), (Rz(0.5), 1), (Ph(0.5), 0), (S, 3), (T, 2), (H, 1), (Toffoli, (0, 1, 2)), (Barrier, None), (Swap, (0, 3)), (SqrtSwap, (0, 1)), (get_inverse(SqrtSwap), (2, 3)), (SqrtX, 2), (C(get_inverse(SqrtX)), (0, 2)), (C(Ry(0.5)), (2, 3)), (CNOT, (2, 1)), (Entangle, None), (te_gate, None), (QFT, None), (Tensor(H), None), (BasicMathGate(add), (2, 3)), (All(Measure), None), ] # apply them for gate, pos in zoo: if pos is None: gate | qureg elif isinstance(pos, tuple): gate | tuple(qureg[i] for i in pos) else: gate | qureg[pos] main_eng.flush() # generate latex code to draw the circuit s = drawing_engine.get_latex() prefix = 'zoo' with open(f'{prefix}.tex', 'w') as f: f.write(s) # compile latex source code and open pdf file os.system(f'pdflatex {prefix}.tex') openfile(f'{prefix}.pdf')
Generate and display the zoo of quantum gates.
zoo_profile
python
ProjectQ-Framework/ProjectQ
examples/gate_zoo.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/gate_zoo.py
Apache-2.0
def openfile(filename): """ Open a file. Args: filename (str): the target file. Return: bool: succeed if True. """ platform = sys.platform if platform == "linux" or platform == "linux2": os.system('xdg-open %s' % filename) elif platform == "darwin": os.system('open %s' % filename) elif platform == "win32": os.startfile(filename) else: print('Can not open file, platform %s not handled!' % platform) return False return True
Open a file. Args: filename (str): the target file. Return: bool: succeed if True.
openfile
python
ProjectQ-Framework/ProjectQ
examples/gate_zoo.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/gate_zoo.py
Apache-2.0
def run_grover(eng, n, oracle): """ Run Grover's algorithm on n qubit using the provided quantum oracle. Args: eng (MainEngine): Main compiler engine to run Grover on. n (int): Number of bits in the solution. oracle (function): Function accepting the engine, an n-qubit register, and an output qubit which is flipped by the oracle for the correct bit string. Returns: solution (list<int>): Solution bit-string. """ x = eng.allocate_qureg(n) # start in uniform superposition All(H) | x # number of iterations we have to run: num_it = int(math.pi / 4.0 * math.sqrt(1 << n)) # prepare the oracle output qubit (the one that is flipped to indicate the # solution. start in state 1/sqrt(2) * (|0> - |1>) s.t. a bit-flip turns # into a (-1)-phase. oracle_out = eng.allocate_qubit() X | oracle_out H | oracle_out # run num_it iterations with Loop(eng, num_it): # oracle adds a (-1)-phase to the solution oracle(eng, x, oracle_out) # reflection across uniform superposition with Compute(eng): All(H) | x All(X) | x with Control(eng, x[0:-1]): Z | x[-1] Uncompute(eng) All(Measure) | x Measure | oracle_out eng.flush() # return result return [int(qubit) for qubit in x]
Run Grover's algorithm on n qubit using the provided quantum oracle. Args: eng (MainEngine): Main compiler engine to run Grover on. n (int): Number of bits in the solution. oracle (function): Function accepting the engine, an n-qubit register, and an output qubit which is flipped by the oracle for the correct bit string. Returns: solution (list<int>): Solution bit-string.
run_grover
python
ProjectQ-Framework/ProjectQ
examples/grover.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/grover.py
Apache-2.0
def alternating_bits_oracle(eng, qubits, output): """ Alternating bit oracle. Mark the solution string 1,0,1,0,...,0,1 by flipping the output qubit, conditioned on qubits being equal to the alternating bit-string. Args: eng (MainEngine): Main compiler engine the algorithm is being run on. qubits (Qureg): n-qubit quantum register Grover search is run on. output (Qubit): Output qubit to flip in order to mark the solution. """ with Compute(eng): All(X) | qubits[1::2] with Control(eng, qubits): X | output Uncompute(eng)
Alternating bit oracle. Mark the solution string 1,0,1,0,...,0,1 by flipping the output qubit, conditioned on qubits being equal to the alternating bit-string. Args: eng (MainEngine): Main compiler engine the algorithm is being run on. qubits (Qureg): n-qubit quantum register Grover search is run on. output (Qubit): Output qubit to flip in order to mark the solution.
alternating_bits_oracle
python
ProjectQ-Framework/ProjectQ
examples/grover.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/grover.py
Apache-2.0
def run_entangle(eng, num_qubits=3): """ Run an entangling operation on the provided compiler engine. Args: eng (MainEngine): Main compiler engine to use. num_qubits (int): Number of qubits to entangle. Returns: measurement (list<int>): List of measurement outcomes. """ # allocate the quantum register to entangle qureg = eng.allocate_qureg(num_qubits) # entangle the qureg Entangle | qureg # measure; should be all-0 or all-1 All(Measure) | qureg # run the circuit eng.flush() # access the probabilities via the back-end: # results = eng.backend.get_probabilities(qureg) # for state in results: # print(f"Measured {state} with p = {results[state]}.") # or plot them directly: histogram(eng.backend, qureg) plt.show() # return one (random) measurement outcome. return [int(q) for q in qureg]
Run an entangling operation on the provided compiler engine. Args: eng (MainEngine): Main compiler engine to use. num_qubits (int): Number of qubits to entangle. Returns: measurement (list<int>): List of measurement outcomes.
run_entangle
python
ProjectQ-Framework/ProjectQ
examples/ibm.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/ibm.py
Apache-2.0
def run_entangle(eng, num_qubits=3): """ Run an entangling operation on the provided compiler engine. Args: eng (MainEngine): Main compiler engine to use. num_qubits (int): Number of qubits to entangle. Returns: measurement (list<int>): List of measurement outcomes. """ # allocate the quantum register to entangle qureg = eng.allocate_qureg(num_qubits) # entangle the qureg Entangle | qureg # measure; should be all-0 or all-1 All(Measure) | qureg # run the circuit eng.flush() # access the probabilities via the back-end: # results = eng.backend.get_probabilities(qureg) # for state in results: # print(f"Measured {state} with p = {results[state]}.") # or plot them directly: histogram(eng.backend, qureg) plt.show() # return one (random) measurement outcome. return [int(q) for q in qureg]
Run an entangling operation on the provided compiler engine. Args: eng (MainEngine): Main compiler engine to use. num_qubits (int): Number of qubits to entangle. Returns: measurement (list<int>): List of measurement outcomes.
run_entangle
python
ProjectQ-Framework/ProjectQ
examples/ionq.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/ionq.py
Apache-2.0
def run_shor(eng, N, a, verbose=False): """ Run the quantum subroutine of Shor's algorithm for factoring. Args: eng (MainEngine): Main compiler engine to use. N (int): Number to factor. a (int): Relative prime to use as a base for a^x mod N. verbose (bool): If True, display intermediate measurement results. Returns: r (float): Potential period of a. """ n = int(math.ceil(math.log(N, 2))) x = eng.allocate_qureg(n) X | x[0] measurements = [0] * (2 * n) # will hold the 2n measurement results ctrl_qubit = eng.allocate_qubit() for k in range(2 * n): current_a = pow(a, 1 << (2 * n - 1 - k), N) # one iteration of 1-qubit QPE H | ctrl_qubit with Control(eng, ctrl_qubit): MultiplyByConstantModN(current_a, N) | x # perform inverse QFT --> Rotations conditioned on previous outcomes for i in range(k): if measurements[i]: R(-math.pi / (1 << (k - i))) | ctrl_qubit H | ctrl_qubit # and measure Measure | ctrl_qubit eng.flush() measurements[k] = int(ctrl_qubit) if measurements[k]: X | ctrl_qubit if verbose: print(f"\033[95m{measurements[k]}\033[0m", end="") sys.stdout.flush() All(Measure) | x # turn the measured values into a number in [0,1) y = sum((measurements[2 * n - 1 - i] * 1.0 / (1 << (i + 1))) for i in range(2 * n)) # continued fraction expansion to get denominator (the period?) r = Fraction(y).limit_denominator(N - 1).denominator # return the (potential) period return r
Run the quantum subroutine of Shor's algorithm for factoring. Args: eng (MainEngine): Main compiler engine to use. N (int): Number to factor. a (int): Relative prime to use as a base for a^x mod N. verbose (bool): If True, display intermediate measurement results. Returns: r (float): Potential period of a.
run_shor
python
ProjectQ-Framework/ProjectQ
examples/shor.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/shor.py
Apache-2.0
def create_bell_pair(eng): r""" Create a Bell pair state with two qubits. Returns a Bell-pair (two qubits in state :math:`|A\rangle \otimes |B \rangle = \frac 1{\sqrt 2} \left( |0\rangle\otimes|0\rangle + |1\rangle \otimes|1\rangle \right)`). Args: eng (MainEngine): MainEngine from which to allocate the qubits. Returns: bell_pair (tuple<Qubits>): The Bell-pair. """ b1 = eng.allocate_qubit() b2 = eng.allocate_qubit() H | b1 CNOT | (b1, b2) return b1, b2
Create a Bell pair state with two qubits. Returns a Bell-pair (two qubits in state :math:`|A\rangle \otimes |B \rangle = \frac 1{\sqrt 2} \left( |0\rangle\otimes|0\rangle + |1\rangle \otimes|1\rangle \right)`). Args: eng (MainEngine): MainEngine from which to allocate the qubits. Returns: bell_pair (tuple<Qubits>): The Bell-pair.
create_bell_pair
python
ProjectQ-Framework/ProjectQ
examples/teleport.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/teleport.py
Apache-2.0
def run_teleport(eng, state_creation_function, verbose=False): """ Run quantum teleportation on the provided main compiler engine. Creates a state from |0> using the state_creation_function, teleports this state to Bob who then tries to uncompute his qubit using the inverse of the state_creation_function. If successful, deleting the qubit won't raise an error in the underlying Simulator back-end (else it will). Args: eng (MainEngine): Main compiler engine to run the circuit on. state_creation_function (function): Function which accepts the main engine and a qubit in state |0>, which it then transforms to the state that Alice would like to send to Bob. verbose (bool): If True, info messages will be printed. """ # make a Bell-pair b1, b2 = create_bell_pair(eng) # Alice creates a nice state to send psi = eng.allocate_qubit() if verbose: print("Alice is creating her state from scratch, i.e., |0>.") state_creation_function(eng, psi) # entangle it with Alice's b1 CNOT | (psi, b1) if verbose: print("Alice entangled her qubit with her share of the Bell-pair.") # measure two values (once in Hadamard basis) and send the bits to Bob H | psi Measure | psi Measure | b1 msg_to_bob = [int(psi), int(b1)] if verbose: print(f"Alice is sending the message {msg_to_bob} to Bob.") # Bob may have to apply up to two operation depending on the message sent # by Alice: with Control(eng, b1): X | b2 with Control(eng, psi): Z | b2 # try to uncompute the psi state if verbose: print("Bob is trying to uncompute the state.") with Dagger(eng): state_creation_function(eng, b2) # check whether the uncompute was successful. The simulator only allows to # delete qubits which are in a computational basis state. del b2 eng.flush() if verbose: print("Bob successfully arrived at |0>")
Run quantum teleportation on the provided main compiler engine. Creates a state from |0> using the state_creation_function, teleports this state to Bob who then tries to uncompute his qubit using the inverse of the state_creation_function. If successful, deleting the qubit won't raise an error in the underlying Simulator back-end (else it will). Args: eng (MainEngine): Main compiler engine to run the circuit on. state_creation_function (function): Function which accepts the main engine and a qubit in state |0>, which it then transforms to the state that Alice would like to send to Bob. verbose (bool): If True, info messages will be printed.
run_teleport
python
ProjectQ-Framework/ProjectQ
examples/teleport.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/teleport.py
Apache-2.0
def run_circuit(eng, n_qubits, circuit_num, gate_after_measure=False): """Run a quantum circuit demonstrating the capabilities of the UnitarySimulator.""" qureg = eng.allocate_qureg(n_qubits) if circuit_num == 1: All(X) | qureg elif circuit_num == 2: X | qureg[0] with Control(eng, qureg[:2]): All(X) | qureg[2:] elif circuit_num == 3: with Control(eng, qureg[:2], ctrl_state=CtrlAll.Zero): All(X) | qureg[2:] elif circuit_num == 4: QFT | qureg eng.flush() All(Measure) | qureg if gate_after_measure: QFT | qureg eng.flush() All(Measure) | qureg
Run a quantum circuit demonstrating the capabilities of the UnitarySimulator.
run_circuit
python
ProjectQ-Framework/ProjectQ
examples/unitary_simulator.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/unitary_simulator.py
Apache-2.0
def main(): """Definition of the main function of this example.""" # Create a MainEngine with a unitary simulator backend eng = MainEngine(backend=UnitarySimulator()) n_qubits = 3 # Run out quantum circuit # 1 - circuit applying X on all qubits # 2 - circuit applying an X gate followed by a controlled-X gate # 3 - circuit applying a off-controlled-X gate # 4 - circuit applying a QFT on all qubits (QFT will get decomposed) run_circuit(eng, n_qubits, 3, gate_after_measure=True) # Output the unitary transformation of the circuit print('The unitary of the circuit is:') print(eng.backend.unitary) # Output the final state of the qubits (assuming they all start in state |0>) print('The final state of the qubits is:') print(eng.backend.unitary @ np.array([1] + ([0] * (2**n_qubits - 1)))) print('\n') # Show the unitaries separated by measurement: for history in eng.backend.history: print('Previous unitary is: \n', history, '\n')
Definition of the main function of this example.
main
python
ProjectQ-Framework/ProjectQ
examples/unitary_simulator.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/examples/unitary_simulator.py
Apache-2.0
def __init__(self, accept_input=True, default_measure=False, in_place=False): """ Initialize a CommandPrinter. Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CommandPrinter is the last engine. Otherwise, all measurements yield default_measure. default_measure (bool): Default measurement result (if accept_input is False). in_place (bool): If in_place is true, all output is written on the same line of the terminal. """ super().__init__() self._accept_input = accept_input self._default_measure = default_measure self._in_place = in_place
Initialize a CommandPrinter. Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CommandPrinter is the last engine. Otherwise, all measurements yield default_measure. default_measure (bool): Default measurement result (if accept_input is False). in_place (bool): If in_place is true, all output is written on the same line of the terminal.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_printer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py
Apache-2.0
def is_available(self, cmd): """ Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the CommandPrinter is the last engine (since it can print any command). Args: cmd (Command): Command of which to check availability (all Commands can be printed). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine). """ try: return BasicEngine.is_available(self, cmd) except LastEngineException: return True
Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the CommandPrinter is the last engine (since it can print any command). Args: cmd (Command): Command of which to check availability (all Commands can be printed). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine).
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_printer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py
Apache-2.0
def _print_cmd(self, cmd): """ Print a command. Print a command or, if the command is a measurement instruction and the CommandPrinter is the last engine in the engine pipeline: Query the user for the measurement result (if accept_input = True) / Set the result to 0 (if it's False). Args: cmd (Command): Command to print. """ if self.is_last_engine and cmd.gate == Measure: if get_control_count(cmd) != 0: raise ValueError('Cannot have control qubits with a measurement gate!') print(cmd) for qureg in cmd.qubits: for qubit in qureg: if self._accept_input: meas = None while meas not in ('0', '1', 1, 0): prompt = f"Input measurement result (0 or 1) for qubit {str(qubit)}: " meas = input(prompt) else: meas = self._default_measure meas = int(meas) # Check there was a mapper and redirect result logical_id_tag = None for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): logical_id_tag = tag if logical_id_tag is not None: qubit = WeakQubitRef(qubit.engine, logical_id_tag.logical_qubit_id) self.main_engine.set_measurement_result(qubit, meas) else: if self._in_place: # pragma: no cover sys.stdout.write(f'\x00\r\t\x1b[K{str(cmd)}\r') else: print(cmd)
Print a command. Print a command or, if the command is a measurement instruction and the CommandPrinter is the last engine in the engine pipeline: Query the user for the measurement result (if accept_input = True) / Set the result to 0 (if it's False). Args: cmd (Command): Command to print.
_print_cmd
python
ProjectQ-Framework/ProjectQ
projectq/backends/_printer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine. Args: command_list (list<Command>): List of Commands to print (and potentially send on to the next engine). """ for cmd in command_list: if not cmd.gate == FlushGate(): self._print_cmd(cmd) # (try to) send on if not self.is_last_engine: self.send([cmd])
Receive a list of commands. Receive a list of commands from the previous engine, print the commands, and then send them on to the next engine. Args: command_list (list<Command>): List of Commands to print (and potentially send on to the next engine).
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_printer.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_printer.py
Apache-2.0
def __init__(self): """ Initialize a resource counter engine. Sets all statistics to zero. """ super().__init__() self.gate_counts = {} self.gate_class_counts = {} self._active_qubits = 0 self.max_width = 0 # key: qubit id, depth of this qubit self._depth_of_qubit = {} self._previous_max_depth = 0
Initialize a resource counter engine. Sets all statistics to zero.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_resource.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py
Apache-2.0
def is_available(self, cmd): """ Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the ResourceCounter is the last engine (since it can count any command). Args: cmd (Command): Command for which to check availability (all Commands can be counted). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine). """ try: return BasicEngine.is_available(self, cmd) except LastEngineException: return True
Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: Returns True if the ResourceCounter is the last engine (since it can count any command). Args: cmd (Command): Command for which to check availability (all Commands can be counted). Returns: availability (bool): True, unless the next engine cannot handle the Command (if there is a next engine).
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_resource.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py
Apache-2.0
def depth_of_dag(self): """Return the depth of the DAG.""" if self._depth_of_qubit: current_max = max(self._depth_of_qubit.values()) return max(current_max, self._previous_max_depth) return self._previous_max_depth
Return the depth of the DAG.
depth_of_dag
python
ProjectQ-Framework/ProjectQ
projectq/backends/_resource.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py
Apache-2.0
def __str__(self): """ Return the string representation of this ResourceCounter. Returns: A summary (string) of resources used, including gates, number of calls, and max. number of qubits that were active at the same time. """ if len(self.gate_counts) > 0: gate_class_list = [] for gate_class_description, num in self.gate_class_counts.items(): gate_class, ctrl_cnt = gate_class_description gate_class_name = ctrl_cnt * "C" + gate_class.__name__ gate_class_list.append(gate_class_name + " : " + str(num)) gate_list = [] for gate_description, num in self.gate_counts.items(): gate, ctrl_cnt = gate_description gate_name = ctrl_cnt * "C" + str(gate) gate_list.append(gate_name + " : " + str(num)) return ( "Gate class counts:\n " + "\n ".join(sorted(gate_class_list)) + "\n\nGate counts:\n " + "\n ".join(sorted(gate_list)) + "\n\nMax. width (number of qubits) : " + str(self.max_width) + "." ) return "(No quantum resources used)"
Return the string representation of this ResourceCounter. Returns: A summary (string) of resources used, including gates, number of calls, and max. number of qubits that were active at the same time.
__str__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_resource.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous engine, increases the counters of the received commands, and then send them on to the next engine. Args: command_list (list<Command>): List of commands to receive (and count). """ for cmd in command_list: if not cmd.gate == FlushGate(): self._add_cmd(cmd) # (try to) send on if not self.is_last_engine: self.send([cmd])
Receive a list of commands. Receive a list of commands from the previous engine, increases the counters of the received commands, and then send them on to the next engine. Args: command_list (list<Command>): List of commands to receive (and count).
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_resource.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_resource.py
Apache-2.0
def _qidmask(target_ids, control_ids, n_qubits): """ Calculate index masks. Args: target_ids (list): list of target qubit indices control_ids (list): list of control qubit indices control_state (list): list of states for the control qubits (0 or 1) n_qubits (int): number of qubits """ mask_list = [] perms = np.array([x[::-1] for x in itertools.product("01", repeat=n_qubits)]).astype(int) all_ids = np.array(range(n_qubits)) irel_ids = np.delete(all_ids, control_ids + target_ids) if len(control_ids) > 0: cmask = np.where(np.all(perms[:, control_ids] == [1] * len(control_ids), axis=1)) else: cmask = np.array(range(perms.shape[0])) if len(irel_ids) > 0: irel_perms = np.array([x[::-1] for x in itertools.product("01", repeat=len(irel_ids))]).astype(int) for i in range(2 ** len(irel_ids)): irel_mask = np.where(np.all(perms[:, irel_ids] == irel_perms[i], axis=1)) common = np.intersect1d(irel_mask, cmask) if len(common) > 0: mask_list.append(common) else: irel_mask = np.array(range(perms.shape[0])) mask_list.append(np.intersect1d(irel_mask, cmask)) return mask_list
Calculate index masks. Args: target_ids (list): list of target qubit indices control_ids (list): list of control qubit indices control_state (list): list of states for the control qubits (0 or 1) n_qubits (int): number of qubits
_qidmask
python
ProjectQ-Framework/ProjectQ
projectq/backends/_unitary.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py
Apache-2.0
def is_available(self, cmd): """ Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: The unitary simulator can deal with all arbitrarily-controlled gates which provide a gate-matrix (via gate.matrix). Args: cmd (Command): Command for which to check availability (single- qubit gate, arbitrary controls) Returns: True if it can be simulated and False otherwise. """ if has_negative_control(cmd): return False if isinstance(cmd.gate, (AllocateQubitGate, DeallocateQubitGate, MeasureGate)): return True try: gate_mat = cmd.gate.matrix if len(gate_mat) > 2**6: warnings.warn(f"Potentially large matrix gate encountered! ({math.log2(len(gate_mat))} qubits)") return True except AttributeError: return False
Test whether a Command is supported by a compiler engine. Specialized implementation of is_available: The unitary simulator can deal with all arbitrarily-controlled gates which provide a gate-matrix (via gate.matrix). Args: cmd (Command): Command for which to check availability (single- qubit gate, arbitrary controls) Returns: True if it can be simulated and False otherwise.
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_unitary.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a list of commands from the previous engine and handle them: * update the unitary of the quantum circuit * update the internal quantum state if a measurement or a qubit deallocation occurs prior to sending them on to the next engine. Args: command_list (list<Command>): List of commands to execute on the simulator. """ for cmd in command_list: self._handle(cmd) if not self.is_last_engine: self.send(command_list)
Receive a list of commands. Receive a list of commands from the previous engine and handle them: * update the unitary of the quantum circuit * update the internal quantum state if a measurement or a qubit deallocation occurs prior to sending them on to the next engine. Args: command_list (list<Command>): List of commands to execute on the simulator.
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_unitary.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py
Apache-2.0
def _handle(self, cmd): """ Handle all commands. Args: cmd (Command): Command to handle. Raises: RuntimeError: If a measurement is performed before flush gate. """ if isinstance(cmd.gate, AllocateQubitGate): self._qubit_map[cmd.qubits[0][0].id] = self._num_qubits self._num_qubits += 1 self._unitary = np.kron(np.identity(2), self._unitary) self._state.extend([0] * len(self._state)) elif isinstance(cmd.gate, DeallocateQubitGate): pos = self._qubit_map[cmd.qubits[0][0].id] self._qubit_map = {key: value - 1 if value > pos else value for key, value in self._qubit_map.items()} self._num_qubits -= 1 self._is_valid = False elif isinstance(cmd.gate, MeasureGate): self._is_valid = False if not self._is_flushed: raise RuntimeError( 'Please make sure all previous gates are flushed before measurement so the state gets updated' ) if get_control_count(cmd) != 0: raise ValueError('Cannot have control qubits with a measurement gate!') all_qubits = [qb for qr in cmd.qubits for qb in qr] measurements = self.measure_qubits([qb.id for qb in all_qubits]) for qb, res in zip(all_qubits, measurements): # Check if a mapper assigned a different logical id for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): qb = WeakQubitRef(qb.engine, tag.logical_qubit_id) break self.main_engine.set_measurement_result(qb, res) elif isinstance(cmd.gate, FlushGate): self._flush() else: if not self._is_valid: self._flush() warnings.warn( "Processing of other gates after a qubit deallocation or measurement will reset the unitary," "previous unitary can be accessed in history" ) self._history.append(self._unitary) self._unitary = np.identity(2**self._num_qubits, dtype=complex) self._state = np.array([1] + ([0] * (2**self._num_qubits - 1)), dtype=complex) self._is_valid = True self._is_flushed = False mask_list = _qidmask( [self._qubit_map[qb.id] for qr in cmd.qubits for qb in qr], [self._qubit_map[qb.id] for qb in cmd.control_qubits], self._num_qubits, ) for mask in mask_list: cache = np.identity(2**self._num_qubits, dtype=complex) cache[np.ix_(mask, mask)] = cmd.gate.matrix self._unitary = cache @ self._unitary
Handle all commands. Args: cmd (Command): Command to handle. Raises: RuntimeError: If a measurement is performed before flush gate.
_handle
python
ProjectQ-Framework/ProjectQ
projectq/backends/_unitary.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py
Apache-2.0
def measure_qubits(self, ids): """ Measure the qubits with IDs ids and return a list of measurement outcomes (True/False). Args: ids (list<int>): List of qubit IDs to measure. Returns: List of measurement results (containing either True or False). """ random_outcome = random.random() val = 0.0 i_picked = 0 while val < random_outcome and i_picked < len(self._state): val += np.abs(self._state[i_picked]) ** 2 i_picked += 1 i_picked -= 1 pos = [self._qubit_map[ID] for ID in ids] res = [False] * len(pos) mask = 0 val = 0 for i, _pos in enumerate(pos): res[i] = ((i_picked >> _pos) & 1) == 1 mask |= 1 << _pos val |= (res[i] & 1) << _pos nrm = 0.0 for i, _state in enumerate(self._state): if (mask & i) != val: self._state[i] = 0.0 else: nrm += np.abs(_state) ** 2 self._state *= 1.0 / np.sqrt(nrm) return res
Measure the qubits with IDs ids and return a list of measurement outcomes (True/False). Args: ids (list<int>): List of qubit IDs to measure. Returns: List of measurement results (containing either True or False).
measure_qubits
python
ProjectQ-Framework/ProjectQ
projectq/backends/_unitary.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_unitary.py
Apache-2.0
def __init__( self, use_hardware=False, num_runs=100, verbose=False, token='', device='simulator', num_retries=3000, interval=1, retrieve_execution=None, ): # pylint: disable=too-many-arguments """ Initialize the Backend object. Args: use_hardware (bool): If True, the code is run on the AQT quantum chip (instead of using the AQT simulator) num_runs (int): Number of runs to collect statistics. (default is 100, max is usually around 200) verbose (bool): If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). token (str): AQT user API token. device (str): name of the AQT device to use. simulator By default num_retries (int): Number of times to retry to obtain results from the AQT API. (default is 3000) interval (float, int): Number of seconds between successive attempts to obtain results from the AQT API. (default is 1) retrieve_execution (int): Job ID to retrieve instead of re- running the circuit (e.g., if previous run timed out). """ super().__init__() self._reset() if use_hardware: self.device = device else: self.device = 'simulator' self._clear = True self._num_runs = num_runs self._verbose = verbose self._token = token self._num_retries = num_retries self._interval = interval self._probabilities = {} self._circuit = [] self._mapper = [] self._measured_ids = [] self._allocated_qubits = set() self._retrieve_execution = retrieve_execution
Initialize the Backend object. Args: use_hardware (bool): If True, the code is run on the AQT quantum chip (instead of using the AQT simulator) num_runs (int): Number of runs to collect statistics. (default is 100, max is usually around 200) verbose (bool): If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). token (str): AQT user API token. device (str): name of the AQT device to use. simulator By default num_retries (int): Number of times to retry to obtain results from the AQT API. (default is 3000) interval (float, int): Number of seconds between successive attempts to obtain results from the AQT API. (default is 1) retrieve_execution (int): Job ID to retrieve instead of re- running the circuit (e.g., if previous run timed out).
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def is_available(self, cmd): """ Return true if the command can be executed. The AQT ion trap can only do Rx,Ry and Rxx. Args: cmd (Command): Command for which to check availability """ if get_control_count(cmd) == 0: if isinstance(cmd.gate, (Rx, Ry, Rxx)): return True if cmd.gate in (Measure, Allocate, Deallocate, Barrier): return True return False
Return true if the command can be executed. The AQT ion trap can only do Rx,Ry and Rxx. Args: cmd (Command): Command for which to check availability
is_available
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def _reset(self): """Reset all temporary variables (after flush gate).""" self._clear = True self._measured_ids = []
Reset all temporary variables (after flush gate).
_reset
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def _store(self, cmd): """ Temporarily store the command cmd. Translates the command and stores it in a local variable (self._cmds). Args: cmd: Command to store """ if self._clear: self._probabilities = {} self._clear = False self._circuit = [] self._allocated_qubits = set() gate = cmd.gate if gate == Allocate: self._allocated_qubits.add(cmd.qubits[0][0].id) return if gate == Deallocate: return if gate == Measure: qb_id = cmd.qubits[0][0].id logical_id = None for tag in cmd.tags: if isinstance(tag, LogicalQubitIDTag): logical_id = tag.logical_qubit_id break if logical_id is None: logical_id = qb_id self._mapper.append(qb_id) self._measured_ids += [logical_id] return if isinstance(gate, (Rx, Ry, Rxx)): qubits = [] qubits.append(cmd.qubits[0][0].id) if len(cmd.qubits) == 2: qubits.append(cmd.qubits[1][0].id) angle = gate.angle / math.pi instruction = [] u_name = {'Rx': "X", 'Ry': "Y", 'Rxx': "MS"} instruction.append(u_name[str(gate)[0 : int(len(cmd.qubits) + 1)]]) # noqa: E203 instruction.append(round(angle, 2)) instruction.append(qubits) self._circuit.append(instruction) return if gate == Barrier: return raise InvalidCommandError(f"Invalid command: {str(cmd)}")
Temporarily store the command cmd. Translates the command and stores it in a local variable (self._cmds). Args: cmd: Command to store
_store
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def _logical_to_physical(self, qb_id): """ Return the physical location of the qubit with the given logical id. If no mapper is present then simply returns the qubit ID. Args: qb_id (int): ID of the logical qubit whose position should be returned. """ try: mapping = self.main_engine.mapper.current_mapping if qb_id not in mapping: raise RuntimeError( f"Unknown qubit id {qb_id}. " "Please make sure eng.flush() was called and that the qubit was eliminated during optimization." ) return mapping[qb_id] except AttributeError as err: if qb_id not in self._mapper: raise RuntimeError( f"Unknown qubit id {qb_id}. Please make sure eng.flush() was called and that the qubit was " "eliminated during optimization." ) from err return qb_id
Return the physical location of the qubit with the given logical id. If no mapper is present then simply returns the qubit ID. Args: qb_id (int): ID of the logical qubit whose position should be returned.
_logical_to_physical
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def get_probabilities(self, qureg): """ Return the probability of the outcome `bit_string` when measuring the quantum register `qureg`. Return the list of basis states with corresponding probabilities. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register. Warning: Only call this function after the circuit has been executed! Args: qureg (list<Qubit>): Quantum register determining the order of the qubits. Returns: probability_dict (dict): Dictionary mapping n-bit strings to probabilities. Raises: RuntimeError: If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away). """ if len(self._probabilities) == 0: raise RuntimeError("Please, run the circuit first!") probability_dict = {} for state, probability in self._probabilities.items(): mapped_state = ['0'] * len(qureg) for i, qubit in enumerate(qureg): mapped_state[i] = state[self._logical_to_physical(qubit.id)] mapped_state = "".join(mapped_state) probability_dict[mapped_state] = probability_dict.get(mapped_state, 0) + probability return probability_dict
Return the probability of the outcome `bit_string` when measuring the quantum register `qureg`. Return the list of basis states with corresponding probabilities. If input qureg is a subset of the register used for the experiment, then returns the projected probabilities over the other states. The measured bits are ordered according to the supplied quantum register, i.e., the left-most bit in the state-string corresponds to the first qubit in the supplied quantum register. Warning: Only call this function after the circuit has been executed! Args: qureg (list<Qubit>): Quantum register determining the order of the qubits. Returns: probability_dict (dict): Dictionary mapping n-bit strings to probabilities. Raises: RuntimeError: If no data is available (i.e., if the circuit has not been executed). Or if a qubit was supplied which was not present in the circuit (might have gotten optimized away).
get_probabilities
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def _run(self): """ Run the circuit. Send the circuit via the AQT API using the provided user token / ask for the user token. """ # finally: measurements # NOTE AQT DOESN'T SEEM TO HAVE MEASUREMENT INSTRUCTIONS (no # intermediate measurements are allowed, so implicit at the end) # return if no operations. if not self._circuit: return n_qubit = max(self._allocated_qubits) + 1 info = {} # Hack: AQT instructions specifically need "GATE" string representation # instead of 'GATE' info['circuit'] = str(self._circuit).replace("'", '"') info['nq'] = n_qubit info['shots'] = self._num_runs info['backend'] = {'name': self.device} if self._num_runs > 200: raise Exception("Number of shots limited to 200") try: if self._retrieve_execution is None: res = send( info, device=self.device, token=self._token, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) else: res = retrieve( device=self.device, token=self._token, jobid=self._retrieve_execution, num_retries=self._num_retries, interval=self._interval, verbose=self._verbose, ) self._num_runs = len(res) counts = _format_counts(res, n_qubit) # Determine random outcome random_outcome = random.random() p_sum = 0.0 measured = "" for state in counts: probability = counts[state] * 1.0 / self._num_runs p_sum += probability star = "" if p_sum >= random_outcome and measured == "": measured = state star = "*" self._probabilities[state] = probability if self._verbose and probability > 0: print(f"{str(state)} with p = {probability}{star}") # register measurement result from AQT for qubit_id in self._measured_ids: location = self._logical_to_physical(qubit_id) result = int(measured[location]) self.main_engine.set_measurement_result(WeakQubitRef(self, qubit_id), result) self._reset() except TypeError as err: raise Exception("Failed to run the circuit. Aborting.") from err
Run the circuit. Send the circuit via the AQT API using the provided user token / ask for the user token.
_run
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def receive(self, command_list): """ Receive a list of commands. Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the AQT API. Args: command_list: List of commands to execute """ for cmd in command_list: if not isinstance(cmd.gate, FlushGate): self._store(cmd) else: self._run() self._reset()
Receive a list of commands. Receive a command list and, for each command, stores it until completion. Upon flush, send the data to the AQT API. Args: command_list: List of commands to execute
receive
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt.py
Apache-2.0
def __init__(self): """Initialize an AQT session with AQT's APIs.""" super().__init__() self.backends = {} self.timeout = 5.0 self.token = None
Initialize an AQT session with AQT's APIs.
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def update_devices_list(self, verbose=False): """ Update the internal device list. Returns: (list): list of available devices Note: Up to my knowledge there is no proper API call for online devices, so we just assume that the list from AQT portal always up to date """ # TODO: update once the API for getting online devices is available self.backends = {} self.backends['aqt_simulator'] = {'nq': 11, 'version': '0.0.1', 'url': 'sim/'} self.backends['aqt_simulator_noise'] = { 'nq': 11, 'version': '0.0.1', 'url': 'sim/noise-model-1', } self.backends['aqt_device'] = {'nq': 4, 'version': '0.0.1', 'url': 'lint/'} if verbose: print('- List of AQT devices available:') print(self.backends)
Update the internal device list. Returns: (list): list of available devices Note: Up to my knowledge there is no proper API call for online devices, so we just assume that the list from AQT portal always up to date
update_devices_list
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def can_run_experiment(self, info, device): """ Check if the device is big enough to run the code. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the aqt device to use Returns: (bool): True if device is big enough, False otherwise """ nb_qubit_max = self.backends[device]['nq'] nb_qubit_needed = info['nq'] return nb_qubit_needed <= nb_qubit_max, nb_qubit_max, nb_qubit_needed
Check if the device is big enough to run the code. Args: info (dict): dictionary sent by the backend containing the code to run device (str): name of the aqt device to use Returns: (bool): True if device is big enough, False otherwise
can_run_experiment
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def authenticate(self, token=None): """ Authenticate with the AQT Web API. Args: token (str): AQT user API token. """ if token is None: token = getpass.getpass(prompt='AQT token > ') self.headers.update({'Ocp-Apim-Subscription-Key': token, 'SDK': 'ProjectQ'}) self.token = token
Authenticate with the AQT Web API. Args: token (str): AQT user API token.
authenticate
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def get_result( # pylint: disable=too-many-arguments self, device, execution_id, num_retries=3000, interval=1, verbose=False ): """Get the result of an execution.""" if verbose: print(f"Waiting for results. [Job ID: {execution_id}]") original_sigint_handler = signal.getsignal(signal.SIGINT) def _handle_sigint_during_get_result(*_): # pragma: no cover raise Exception(f"Interrupted. The ID of your submitted job is {execution_id}.") try: signal.signal(signal.SIGINT, _handle_sigint_during_get_result) for retries in range(num_retries): argument = {'id': execution_id, 'access_token': self.token} req = super().put(urljoin(_API_URL, self.backends[device]['url']), data=argument) req.raise_for_status() r_json = req.json() if r_json['status'] == 'finished' or 'samples' in r_json: return r_json['samples'] if r_json['status'] != 'running': raise Exception(f"Error while running the code: {r_json['status']}.") time.sleep(interval) if self.is_online(device) and retries % 60 == 0: self.update_devices_list() # TODO: update once the API for getting online devices is # available if not self.is_online(device): # pragma: no cover raise DeviceOfflineError( f"Device went offline. The ID of your submitted job is {execution_id}." ) finally: if original_sigint_handler is not None: signal.signal(signal.SIGINT, original_sigint_handler) raise RequestTimeoutError(f"Timeout. The ID of your submitted job is {execution_id}.")
Get the result of an execution.
get_result
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def show_devices(verbose=False): """ Access the list of available devices and their properties (ex: for setup configuration). Args: verbose (bool): If True, additional information is printed Returns: (list) list of available devices and their properties """ aqt_session = AQT() aqt_session.update_devices_list(verbose=verbose) return aqt_session.backends
Access the list of available devices and their properties (ex: for setup configuration). Args: verbose (bool): If True, additional information is printed Returns: (list) list of available devices and their properties
show_devices
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def retrieve(device, token, jobid, num_retries=3000, interval=1, verbose=False): # pylint: disable=too-many-arguments """ Retrieve a previously run job by its ID. Args: device (str): Device on which the code was run / is running. token (str): AQT user API token. jobid (str): Id of the job to retrieve Returns: (list) samples form the AQT server """ aqt_session = AQT() aqt_session.authenticate(token) aqt_session.update_devices_list(verbose) res = aqt_session.get_result(device, jobid, num_retries=num_retries, interval=interval, verbose=verbose) return res
Retrieve a previously run job by its ID. Args: device (str): Device on which the code was run / is running. token (str): AQT user API token. jobid (str): Id of the job to retrieve Returns: (list) samples form the AQT server
retrieve
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def send( info, device='aqt_simulator', token=None, num_retries=100, interval=1, verbose=False, ): # pylint: disable=too-many-arguments """ Send circuit through the AQT API and runs the quantum circuit. Args: info(dict): Contains representation of the circuit to run. device (str): name of the aqt device. Simulator chosen by default token (str): AQT user API token. verbose (bool): If True, additional information is printed, such as measurement statistics. Otherwise, the backend simply registers one measurement result (same behavior as the projectq Simulator). Returns: (list) samples form the AQT server """ try: aqt_session = AQT() if verbose: print("- Authenticating...") if token is not None: print(f"user API token: {token}") aqt_session.authenticate(token) # check if the device is online aqt_session.update_devices_list(verbose) online = aqt_session.is_online(device) # useless for the moment if not online: # pragma: no cover print("The device is offline (for maintenance?). Use the simulator instead or try again later.") raise DeviceOfflineError("Device is offline.") # check if the device has enough qubit to run the code runnable, qmax, qneeded = aqt_session.can_run_experiment(info, device) if not runnable: print( f"The device is too small ({qmax} qubits available) for the code requested({qneeded} qubits needed).", "Try to look for another device with more qubits", ) raise DeviceTooSmall("Device is too small.") if verbose: print(f"- Running code: {info}") execution_id = aqt_session.run(info, device) if verbose: print("- Waiting for results...") res = aqt_session.get_result( device, execution_id, num_retries=num_retries, interval=interval, verbose=verbose, ) if verbose: print("- Done.") return res except requests.exceptions.HTTPError as err: print("- There was an error running your code:") print(err) except requests.exceptions.RequestException as err: print("- Looks like something is wrong with server:") print(err) except KeyError as err: print("- Failed to parse response:") print(err) return None
Send circuit through the AQT API and runs the quantum circuit. Args: info(dict): Contains representation of the circuit to run. device (str): name of the aqt device. Simulator chosen by default token (str): AQT user API token. verbose (bool): If True, additional information is printed, such as measurement statistics. Otherwise, the backend simply registers one measurement result (same behavior as the projectq Simulator). Returns: (list) samples form the AQT server
send
python
ProjectQ-Framework/ProjectQ
projectq/backends/_aqt/_aqt_http_client.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_aqt/_aqt_http_client.py
Apache-2.0
def __init__( self, use_hardware=False, num_runs=1000, verbose=False, credentials=None, s3_folder=None, device='Aspen-8', num_retries=30, interval=1, retrieve_execution=None, ): # pylint: disable=too-many-arguments """ Initialize the Backend object. Args: use_hardware (bool): If True, the code is run on one of the AWS Braket backends, by default on the Rigetti Aspen-8 chip (instead of using the AWS Braket SV1 Simulator) num_runs (int): Number of runs to collect statistics. (default is 1000) verbose (bool): If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). credentials (dict): mapping the AWS key credentials as the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. device (str): name of the device to use. Rigetti Aspen-8 by default. Valid names are "Aspen-8", "IonQ Device" and "SV1" num_retries (int): Number of times to retry to obtain results from AWS Braket. (default is 30) interval (float, int): Number of seconds between successive attempts to obtain results from AWS Braket. (default is 1) retrieve_execution (str): TaskArn to retrieve instead of re-running the circuit (e.g., if previous run timed out). The TaskArns have the form: "arn:aws:braket:us-east-1:123456789012:quantum-task/5766032b-2b47-4bf9-cg00-f11851g4015b" """ super().__init__() self._reset() if use_hardware: self.device = device else: self.device = 'SV1' self._clear = False self._num_runs = num_runs self._verbose = verbose self._credentials = credentials self._s3_folder = s3_folder self._num_retries = num_retries self._interval = interval self._probabilities = {} self._circuit = "" self._measured_ids = [] self._allocated_qubits = set() self._retrieve_execution = retrieve_execution # Dictionary to translate the gates from ProjectQ to AWSBraket self._gationary = { XGate: 'x', YGate: 'y', ZGate: 'z', HGate: 'h', R: 'phaseshift', Rx: 'rx', Ry: 'ry', Rz: 'rz', SGate: 's', # NB: Sdag is 'si' TGate: 't', # NB: Tdag is 'ti' SwapGate: 'swap', SqrtXGate: 'v', } # Static head and tail to be added to the circuit # to build the "action". self._circuithead = '{"braketSchemaHeader": \ {"name": "braket.ir.jaqcd.program", "version": "1"}, \ "results": [], "basis_rotation_instructions": [], \ "instructions": [' self._circuittail = ']}'
Initialize the Backend object. Args: use_hardware (bool): If True, the code is run on one of the AWS Braket backends, by default on the Rigetti Aspen-8 chip (instead of using the AWS Braket SV1 Simulator) num_runs (int): Number of runs to collect statistics. (default is 1000) verbose (bool): If True, statistics are printed, in addition to the measurement result being registered (at the end of the circuit). credentials (dict): mapping the AWS key credentials as the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY. device (str): name of the device to use. Rigetti Aspen-8 by default. Valid names are "Aspen-8", "IonQ Device" and "SV1" num_retries (int): Number of times to retry to obtain results from AWS Braket. (default is 30) interval (float, int): Number of seconds between successive attempts to obtain results from AWS Braket. (default is 1) retrieve_execution (str): TaskArn to retrieve instead of re-running the circuit (e.g., if previous run timed out). The TaskArns have the form: "arn:aws:braket:us-east-1:123456789012:quantum-task/5766032b-2b47-4bf9-cg00-f11851g4015b"
__init__
python
ProjectQ-Framework/ProjectQ
projectq/backends/_awsbraket/_awsbraket.py
https://github.com/ProjectQ-Framework/ProjectQ/blob/master/projectq/backends/_awsbraket/_awsbraket.py
Apache-2.0