code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def get_item_attribute(self, item, name):
if name in self.__item_attributes:
return self.__item_attributes[name](item)
elif self.section:
return self.section.get_item_attribute(item, name)
else:
raise AttributeError(name) | Method called by item when an attribute is not found. |
def dispatch_event(self, event_, **kwargs):
if self.settings.hooks_enabled:
result = self.hooks.dispatch_event(event_, **kwargs)
if result is not None:
return result
# Must also dispatch the event in parent section
if self.section:
... | Dispatch section event.
Notes:
You MUST NOT call event.trigger() directly because
it will circumvent the section settings as well
as ignore the section tree.
If hooks are disabled somewhere up in the tree, and enabled
down below, events will still be... |
def configparser(self):
if self._configparser_adapter is None:
self._configparser_adapter = ConfigPersistenceAdapter(
config=self,
reader_writer=ConfigParserReaderWriter(
config_parser_factory=self.settings.configparser_factory,
... | Adapter to dump/load INI format strings and files using standard library's
``ConfigParser`` (or the backported configparser module in Python 2).
Returns:
ConfigPersistenceAdapter |
def json(self):
if self._json_adapter is None:
self._json_adapter = ConfigPersistenceAdapter(
config=self,
reader_writer=JsonReaderWriter(),
)
return self._json_adapter | Adapter to dump/load JSON format strings and files.
Returns:
ConfigPersistenceAdapter |
def yaml(self):
if self._yaml_adapter is None:
self._yaml_adapter = ConfigPersistenceAdapter(
config=self,
reader_writer=YamlReaderWriter(),
)
return self._yaml_adapter | Adapter to dump/load YAML format strings and files.
Returns:
ConfigPersistenceAdapter |
def click(self):
if self._click_extension is None:
from .click_ext import ClickExtension
self._click_extension = ClickExtension(
config=self
)
return self._click_extension | click extension
Returns:
ClickExtension |
def load(self):
# Must reverse because we want the sources assigned to higher-up Config instances
# to overrides sources assigned to lower Config instances.
for section in reversed(list(self.iter_sections(recursive=True, key=None))):
if section.is_config:
se... | Load user configuration based on settings. |
def option(self, *args, **kwargs):
args, kwargs = _config_parameter(args, kwargs)
return self._click.option(*args, **kwargs) | Registers a click.option which falls back to a configmanager Item
if user hasn't provided a value in the command line.
Item must be the last of ``args``.
Examples::
config = Config({'greeting': 'Hello'})
@click.command()
@config.click.option('--greeting', ... |
def argument(self, *args, **kwargs):
if kwargs.get('required', True):
raise TypeError(
'In click framework, arguments are mandatory, unless marked required=False. '
'Attempt to use configmanager as a fallback provider suggests that this is an optional option... | Registers a click.argument which falls back to a configmanager Item
if user hasn't provided a value in the command line.
Item must be the last of ``args``. |
def _get_kwarg(self, name, kwargs):
at_name = '@{}'.format(name)
if name in kwargs:
if at_name in kwargs:
raise ValueError('Both {!r} and {!r} specified in kwargs'.format(name, at_name))
return kwargs[name]
if at_name in kwargs:
retu... | Helper to get value of a named attribute irrespective of whether it is passed
with or without "@" prefix. |
def _get_envvar_value(self):
envvar_name = None
if self.envvar is True:
envvar_name = self.envvar_name
if envvar_name is None:
envvar_name = '_'.join(self.get_path()).upper()
elif self.envvar:
envvar_name = self.envvar
if env... | Internal helper to get item value from an environment variable
if item is controlled by one, and if the variable is set.
Returns not_set otherwise. |
def get(self, fallback=not_set):
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value
if self.has_value:
if self._value is not not_set:
return self._value
else:
return copy.deepc... | Returns config value.
See Also:
:meth:`.set` and :attr:`.value` |
def set(self, value):
old_value = self._value
old_raw_str_value = self.raw_str_value
self.type.set_item_value(self, value)
new_value = self._value
if old_value is not_set and new_value is not_set:
# Nothing to report
return
if self.sec... | Sets config value. |
def reset(self):
old_value = self._value
old_raw_str_value = self.raw_str_value
self._value = not_set
self.raw_str_value = not_set
new_value = self._value
if old_value is not_set:
# Nothing to report
return
if self.section:
... | Resets the value of config item to its default value. |
def is_default(self):
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value == self.default
else:
return self._value is not_set or self._value == self.default | ``True`` if the item's value is its default value or if no value and no default value are set.
If the item is backed by an environment variable, this will be ``True`` only
if the environment variable is set and is different to the
default value of the item. |
def has_value(self):
if self._get_envvar_value() is not not_set:
return True
else:
return self.default is not not_set or self._value is not not_set | ``True`` if item has a default value or custom value set. |
def get_path(self):
if self.section:
return self.section.get_path() + (self.name,)
else:
return self.name, | Calculate item's path in configuration tree.
Use this sparingly -- path is calculated by going up the configuration tree.
For a large number of items, it is more efficient to use iterators that return paths
as keys.
Path value is stable only once the configuration tree is completely ini... |
def validate(self):
if self.required and not self.has_value:
raise RequiredValueMissing(name=self.name, item=self) | Validate item. |
def translate(self, type_):
if isinstance(type_, six.string_types):
for t in self.all_types:
if type_ in t.aliases:
return t
raise ValueError('Failed to recognise type by name {!r}'.format(type_))
for t in self.all_types:
... | Given a built-in, an otherwise known type, or a name of known type, return its corresponding wrapper type::
>>> Types.translate(int)
<_IntType ('int', 'integer')>
>>> Types.translate('string')
<_StrType ('str', 'string', 'unicode')> |
def filebrowser(request, file_type):
template = 'filebrowser.html'
upload_form = FileUploadForm()
uploaded_file = None
upload_tab_active = False
is_images_dialog = (file_type == 'img')
is_documents_dialog = (file_type == 'doc')
files = FileBrowserFile.objects.filter(file_type=file_... | Trigger view for filebrowser |
def filebrowser_remove_file(request, item_id, file_type):
fobj = get_object_or_404(FileBrowserFile, file_type=file_type, id=item_id)
fobj.delete()
if file_type == 'doc':
return HttpResponseRedirect(reverse('mce-filebrowser-documents'))
return HttpResponseRedirect(reverse('mce-file... | Remove file |
def available_domains(self):
if not hasattr(self, '_available_domains'):
url = 'http://{0}/request/domains/format/json/'.format(
self.api_domain)
req = requests.get(url)
domains = req.json()
setattr(self, '_available_domains', domains)
... | Return list of available domains for use in email address. |
def generate_login(self, min_length=6, max_length=10, digits=True):
chars = string.ascii_lowercase
if digits:
chars += string.digits
length = random.randint(min_length, max_length)
return ''.join(random.choice(chars) for x in range(length)) | Generate string for email address login with defined length and
alphabet.
:param min_length: (optional) min login length.
Default value is ``6``.
:param max_length: (optional) max login length.
Default value is ``10``.
:param digits: (optional) use digits in login genera... |
def get_email_address(self):
if self.login is None:
self.login = self.generate_login()
available_domains = self.available_domains
if self.domain is None:
self.domain = random.choice(available_domains)
elif self.domain not in available_domains:
... | Return full email address from login and domain from params in class
initialization or generate new. |
def get_mailbox(self, email=None, email_hash=None):
if email is None:
email = self.get_email_address()
if email_hash is None:
email_hash = self.get_hash(email)
url = 'http://{0}/request/mail/id/{1}/format/json/'.format(
self.api_domain, email_hash)
... | Return list of emails in given email address
or dict with `error` key if mail box is empty.
:param email: (optional) email address.
:param email_hash: (optional) md5 hash from email address. |
def _connect(self):
'''
Connect
Setup a socket connection to the specified telegram-cli socket
--
@return None
'''
if self.connection_type.lower() == 'tcp':
self.connection = sockets.setup_tcp_socket(self.location, self.port)
... | Connect
Setup a socket connection to the specified telegram-cli socket
--
@return None |
def _send(self, payload):
'''
Send
Send a payload to a telegram-cli socket.
--
@param payload:str The Payload to send over a socket connection.
@return bool
'''
if not self.connection:
self._connect()
# Sen... | Send
Send a payload to a telegram-cli socket.
--
@param payload:str The Payload to send over a socket connection.
@return bool |
def setup_domain_socket(location):
'''
Setup Domain Socket
Setup a connection to a Unix Domain Socket
--
@param location:str The path to the Unix Domain Socket to connect to.
@return <class 'socket._socketobject'>
'''
clientsocket = socket.socket(socket.AF_UNI... | Setup Domain Socket
Setup a connection to a Unix Domain Socket
--
@param location:str The path to the Unix Domain Socket to connect to.
@return <class 'socket._socketobject'> |
def setup_tcp_socket(location, port):
'''
Setup TCP Socket
Setup a connection to a TCP Socket
--
@param location:str The Hostname / IP Address of the remote TCP Socket.
@param port:int The TCP Port the remote Socket is listening on.
@return <class 'sock... | Setup TCP Socket
Setup a connection to a TCP Socket
--
@param location:str The Hostname / IP Address of the remote TCP Socket.
@param port:int The TCP Port the remote Socket is listening on.
@return <class 'socket._socketobject'> |
def create_primary_zone(self, account_name, zone_name):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
primary_zone_info = {"forceImport": True, "createType": "NEW"}
zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info... | Creates a new primary zone.
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique. |
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
primary_zone_info = {"forceImport": True, "createType": "UPLOAD"}
zone_data = {"properties": zone_properties, "primaryCreate... | Creates a new primary zone by uploading a bind file
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
bind_file -- The file to upload. |
def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
if tsig_key is not None and key_value is not None:
name_server_info = {"ip": master, "tsigKey"... | Creates a new primary zone by zone transferring off a master.
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
master -- Primary name server IP address.
Keyword Arguments:
tsig_key -- ... |
def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"}
if tsig_key is not None and key_value is not None:
name_server_info = {"ip": master, "tsigKey": ts... | Creates a new secondary zone.
Arguments:
account_name -- The name of the account.
zone_name -- The name of the zone.
master -- Primary name server IP address.
Keyword Arguments:
tsig_key -- For TSIG-enabled zones: The transaction signature key.
NOTE:... |
def get_zones_of_account(self, account_name, q=None, **kwargs):
uri = "/v1/accounts/" + account_name + "/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns a list of zones for the specified account.
Arguments:
account_name -- The name of the account.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMAR... |
def get_zones(self, q=None, **kwargs):
uri = "/v1/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns a list of zones across all of the user's accounts.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sor... |
def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None):
name_server_info = {}
if primary is not None:
name_server_info['nameServerIp1'] = {'ip':primary}
if backup is not None:
name_server_info['nameServerIp2'] = {'ip':backu... | Edit the axfr name servers of a secondary zone.
Arguments:
zone_name -- The name of the secondary zone being edited.
primary -- The primary name server value.
Keyword Arguments:
backup -- The backup name server if any.
second_backup -- The second backup name server. |
def get_rrsets(self, zone_name, q=None, **kwargs):
uri = "/v1/zones/" + zone_name + "/rrsets"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns the list of RRSets in the specified zone.
Arguments:
zone_name -- The name of the zone.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
ttl - must match the TTL for the rrset
owner - substring match of the owner name
... |
def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs):
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
Keyword Argument... |
def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs):
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The... |
def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata):
if type(rdata) is not list:
rdata = [rdata]
rrset = {"ttl": ttl, "rdata": rdata}
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) | Creates a new RRSet in the specified zone.
Arguments:
zone_name -- The zone that will contain the new RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... |
def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None):
if type(rdata) is not list:
rdata = [rdata]
rrset = {"ttl": ttl, "rdata": rdata}
if profile:
rrset["profile"] = profile
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/"... | Updates an existing RRSet in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... |
def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None):
if type(rdata) is not list:
rdata = [rdata]
rrset = {"rdata": rdata}
method = "patch"
if profile:
rrset["profile"] = profile
method = "put"
uri = "/v1/zones... | Updates an existing RRSet's Rdata in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead... |
def delete_rrset(self, zone_name, rtype, owner_name):
return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) | Deletes an RRSet.
Arguments:
zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The ... |
def create_web_forward(self, zone_name, request_to, redirect_to, forward_type):
web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type}
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) | Create a web forward record.
Arguments:
zone_name -- The zone in which the web forward is to be created.
request_to -- The URL to be redirected. You may use http:// and ftp://.
forward_type -- The type of forward. Valid options include:
Framed
... |
def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list):
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl)
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Creates a new SB Pool.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
owner_name -- The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
If a trailing d... |
def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list):
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl)
return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Updates an existing SB Pool in the specified zone.
:param zone_name: The zone that contains the RRSet. The trailing dot is optional.
:param owner_name: The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
... |
def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record):
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Creates a new TC Pool.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
owner_name -- The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
If a trailing d... |
def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record):
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)
return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Updates an existing TC Pool in the specified zone.
:param zone_name: The zone that contains the RRSet. The trailing dot is optional.
:param owner_name: The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
... |
def dumpf(obj, path, encoding=None):
path = str(path)
if path.endswith('.gz'):
with gzip.open(path, mode='wt', encoding=encoding) as f:
return dump(obj, f)
else:
with open(path, mode='wt', encoding=encoding) as f:
dump(obj, f) | Serialize obj to path in ARPA format (.arpa, .gz). |
def load(fp, model=None, parser=None):
if not model:
model = 'simple'
if not parser:
parser = 'quick'
if model not in ['simple']:
raise ValueError
if parser not in ['quick']:
raise ValueError
if model == 'simple' and parser == 'quick':
return ARPAParser... | Deserialize fp (a file-like object) to a Python object. |
def loadf(path, encoding=None, model=None, parser=None):
path = str(path)
if path.endswith('.gz'):
with gzip.open(path, mode='rt', encoding=encoding) as f:
return load(f, model=model, parser=parser)
else:
with open(path, mode='rt', encoding=encoding) as f:
return... | Deserialize path (.arpa, .gz) to a Python object. |
def loads(s, model=None, parser=None):
with StringIO(s) as f:
return load(f, model=model, parser=parser) | Deserialize s (a str) to a Python object. |
def send_message(self, recipient, message):
'''
Send Message
Sends a message to a Telegram Recipient.
From telegram-cli:
msg <peer> <text> Sends text message to peer
--
@param recipient:str The telegram recipient the message... | Send Message
Sends a message to a Telegram Recipient.
From telegram-cli:
msg <peer> <text> Sends text message to peer
--
@param recipient:str The telegram recipient the message is intended
for. Can be either a... |
def send_image(self, recipient, path):
'''
Send Image
Sends a an image to a Telegram Recipient. The image needs
to be readable to the telegram-cli instance where the
socket is created.
From telegram-cli:
send_photo <peer> <file> ... | Send Image
Sends a an image to a Telegram Recipient. The image needs
to be readable to the telegram-cli instance where the
socket is created.
From telegram-cli:
send_photo <peer> <file> Sends photo to peer
--
@param recipi... |
def isdisjoint(self, other):
if other == FullSpace:
return False
else:
for ls in self.local_factors:
if isinstance(ls.label, StrLabel):
return False
for ls in other.local_factors:
if isinstance(ls.label, Str... | Check whether two Hilbert spaces are disjoint (do not have any
common local factors). Note that `FullSpace` is *not* disjoint with any
other Hilbert space, while `TrivialSpace` *is* disjoint with any other
HilbertSpace (even itself) |
def _check_basis_label_type(cls, label_or_index):
if not isinstance(label_or_index, cls._basis_label_types):
raise TypeError(
"label_or_index must be an instance of one of %s; not %s" % (
", ".join([t.__name__ for t in cls._basis_label_types]),
... | Every object (BasisKet, LocalSigma) that contains a label or index
for an eigenstate of some LocalSpace should call this routine to check
the type of that label or index (or, use
:meth:`_unpack_basis_label_or_index` |
def basis_states(self):
from qnet.algebra.core.state_algebra import BasisKet # avoid circ. import
for label in self.basis_labels:
yield BasisKet(label, hs=self) | Yield an iterator over the states (:class:`.BasisKet` instances)
that form the canonical basis of the Hilbert space
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis |
def basis_state(self, index_or_label):
from qnet.algebra.core.state_algebra import BasisKet # avoid circ. import
try:
return BasisKet(index_or_label, hs=self)
except ValueError as exc_info:
if isinstance(index_or_label, int):
raise IndexError(str... | Return the basis state with the given index or label.
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis
IndexError: if there is no basis state with the given index
KeyError: if there is not basis state with the given label |
def next_basis_label_or_index(self, label_or_index, n=1):
if isinstance(label_or_index, int):
new_index = label_or_index + n
if new_index < 0:
raise IndexError("index %d < 0" % new_index)
if self.has_basis:
if new_index >= self.dimensi... | Given the label or index of a basis state, return the label/index of
the next basis state.
More generally, if `n` is given, return the `n`'th next basis state
label/index; `n` may also be negative to obtain previous basis state
labels/indices.
The return type is the same as the... |
def basis_states(self):
from qnet.algebra.core.state_algebra import BasisKet, TensorKet
# importing locally avoids circular import
ls_bases = [ls.basis_labels for ls in self.local_factors]
for label_tuple in cartesian_product(*ls_bases):
yield TensorKet(
... | Yield an iterator over the states (:class:`.TensorKet` instances)
that form the canonical basis of the Hilbert space
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis |
def basis_state(self, index_or_label):
from qnet.algebra.core.state_algebra import BasisKet, TensorKet
if isinstance(index_or_label, int): # index
ls_bases = [ls.basis_labels for ls in self.local_factors]
label_tuple = list(cartesian_product(*ls_bases))[index_or_label]
... | Return the basis state with the given index or label.
Raises:
.BasisNotSetError: if the Hilbert space has no defined basis
IndexError: if there is no basis state with the given index
KeyError: if there is not basis state with the given label |
def remove(self, other):
if other is FullSpace:
return TrivialSpace
if other is TrivialSpace:
return self
if isinstance(other, ProductSpace):
oops = set(other.operands)
else:
oops = {other}
return ProductSpace.create(
... | Remove a particular factor from a tensor product space. |
def intersect(self, other):
if other is FullSpace:
return self
if other is TrivialSpace:
return TrivialSpace
if isinstance(other, ProductSpace):
other_ops = set(other.operands)
else:
other_ops = {other}
return ProductSpace.... | Find the mutual tensor factors of two Hilbert spaces. |
def identifier(self):
identifier = self._hs._local_identifiers.get(
self.__class__.__name__, self._hs._local_identifiers.get(
'Create', self._identifier))
if not self._rx_identifier.match(identifier):
raise ValueError(
"identifier '%s' doe... | The identifier (symbol) that is used when printing the annihilation
operator. This is identical to the identifier of :class:`Create`. A
custom identifier for both :class:`Destroy` and :class:`Create` can be
set through the `local_identifiers` parameter of the associated Hilbert
space::
... |
def _isinstance(expr, classname):
for cls in type(expr).__mro__:
if cls.__name__ == classname:
return True
return False | Check whether `expr` is an instance of the class with name
`classname`
This is like the builtin `isinstance`, but it take the `classname` a
string, instead of the class directly. Useful for when we don't want to
import the class for which we want to check (also, remember that
pr... |
def _get_from_cache(self, expr):
# The reason method this is separated out from `doprint` is that
# printers that use identation, e.g. IndentedSReprPrinter, need to
# override how caching is handled, applying variable indentation even
# for cached results
try:
... | Get the result of :meth:`doprint` from the internal cache |
def _print_SCALAR_TYPES(self, expr, *args, **kwargs):
adjoint = kwargs.get('adjoint', False)
if adjoint:
expr = expr.conjugate()
if isinstance(expr, SympyBasic):
self._sympy_printer._print_level = self._print_level + 1
res = self._sympy_printer.doprin... | Render scalars |
def doprint(self, expr, *args, **kwargs):
allow_caching = self._allow_caching
is_cached = False
if len(args) > 0 or len(kwargs) > 0:
# we don't want to cache "custom" rendering, such as the adjoint of
# the actual expression (kwargs['adjoint'] is True). Otherwise... | Returns printer's representation for expr (as a string)
The representation is obtained by the following methods:
1. from the :attr:`cache`
2. If `expr` is a Sympy object, delegate to the
:meth:`~sympy.printing.printer.Printer.doprint` method of
:attr:`_sympy_printer`
... |
def decompose_space(H, A):
return OperatorTrace.create(
OperatorTrace.create(A, over_space=H.operands[-1]),
over_space=ProductSpace.create(*H.operands[:-1])) | Simplifies OperatorTrace expressions over tensor-product spaces by
turning it into iterated partial traces.
Args:
H (ProductSpace): The full space.
A (Operator):
Returns:
Operator: Iterative partial trace expression |
def get_coeffs(expr, expand=False, epsilon=0.):
if expand:
expr = expr.expand()
ret = defaultdict(int)
operands = expr.operands if isinstance(expr, OperatorPlus) else [expr]
for e in operands:
c, t = _coeff_term(e)
try:
if abs(complex(c)) < epsilon:
... | Create a dictionary with all Operator terms of the expression
(understood as a sum) as keys and their coefficients as values.
The returned object is a defaultdict that return 0. if a term/key
doesn't exist.
Args:
expr: The operator expression to get all coefficients from.
expand: Wheth... |
def factor_coeff(cls, ops, kwargs):
coeffs, nops = zip(*map(_coeff_term, ops))
coeff = 1
for c in coeffs:
coeff *= c
if coeff == 1:
return nops, coeffs
else:
return coeff * cls.create(*nops, **kwargs) | Factor out coefficients of all factors. |
def rewrite_with_operator_pm_cc(expr):
# TODO: move this to the toolbox
from qnet.algebra.toolbox.core import temporary_rules
def _combine_operator_p_cc(A, B):
if B.adjoint() == A:
return OperatorPlusMinusCC(A, sign=+1)
else:
raise CannotSimplify
def _combi... | Try to rewrite expr using :class:`OperatorPlusMinusCC`
Example:
>>> A = OperatorSymbol('A', hs=1)
>>> sum = A + A.dag()
>>> sum2 = rewrite_with_operator_pm_cc(sum)
>>> print(ascii(sum2))
A^(1) + c.c. |
def doit(self, classes=None, recursive=True, **kwargs):
return super().doit(classes, recursive, **kwargs) | Write out commutator
Write out the commutator according to its definition
$[\Op{A}, \Op{B}] = \Op{A}\Op{B} - \Op{A}\Op{B}$.
See :meth:`.Expression.doit`. |
def _attrprint(d, delimiter=', '):
return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items())) | Print a dictionary of attributes in the DOT format |
def _styleof(expr, styles):
style = dict()
for expr_filter, sty in styles:
if expr_filter(expr):
style.update(sty)
return style | Merge style dictionaries in order |
def expr_labelfunc(leaf_renderer=str, fallback=str):
def _labelfunc(expr, is_leaf):
if is_leaf:
label = leaf_renderer(expr)
elif isinstance(expr, Expression):
if len(expr.kwargs) == 0:
label = expr.__class__.__name__
else:
lab... | Factory for function ``labelfunc(expr, is_leaf)``
It has the following behavior:
* If ``is_leaf`` is True, return ``leaf_renderer(expr)``.
* Otherwise,
- if `expr` is an Expression, return a custom string similar to
:func:`~qnet.printing.srepr`, but with an ellipsis for ``args``
- ot... |
def _git_version():
import subprocess
import os
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
... | If installed with 'pip installe -e .' from inside a git repo, the
current git revision as a string |
def FB(circuit, *, out_port=None, in_port=None):
if out_port is None:
out_port = circuit.cdim - 1
if in_port is None:
in_port = circuit.cdim - 1
return Feedback.create(circuit, out_port=out_port, in_port=in_port) | Wrapper for :class:`.Feedback`, defaulting to last channel
Args:
circuit (Circuit): The circuit that undergoes self-feedback
out_port (int): The output port index, default = None --> last port
in_port (int): The input port index, default = None --> last port
Returns:
Circuit: T... |
def extract_channel(k, cdim):
n = cdim
perm = tuple(list(range(k)) + [n - 1] + list(range(k, n - 1)))
return CPermutation.create(perm) | Create a :class:`CPermutation` that extracts channel `k`
Return a permutation circuit that maps the k-th (zero-based)
input to the last output, while preserving the relative order of all other
channels.
Args:
k (int): Extracted channel index
cdim (int): The circuit dimension (number of... |
def map_channels(mapping, cdim):
n = cdim
free_values = list(range(n))
for v in mapping.values():
if v >= n:
raise ValueError('the mapping cannot take on values larger than '
'cdim - 1')
free_values.remove(v)
for k in mapping:
if k >... | Create a :class:`CPermuation` based on a dict of channel mappings
For a given mapping in form of a dictionary, generate the channel
permutating circuit that achieves the specified mapping while leaving the
relative order of all non-specified channels intact.
Args:
mapping (dict): Input-output ... |
def pad_with_identity(circuit, k, n):
circuit_n = circuit.cdim
combined_circuit = circuit + circuit_identity(n)
permutation = (list(range(k)) + list(range(circuit_n, circuit_n + n)) +
list(range(k, circuit_n)))
return (CPermutation.create(invert_permutation(permutation)) <<
... | Pad a circuit by adding a `n`-channel identity circuit at index `k`
That is, a circuit of channel dimension $N$ is extended to one of channel
dimension $N+n$, where the channels $k$, $k+1$, ...$k+n-1$, just pass
through the system unaffected. E.g. let ``A``, ``B`` be two single channel
systems::
... |
def prepare_adiabatic_limit(slh, k=None):
if k is None:
k = symbols('k', positive=True)
Ld = slh.L.dag()
LdL = (Ld * slh.L)[0, 0]
K = (-LdL / 2 + I * slh.H).expand().simplify_scalar()
N = slh.S.dag()
B, A, Y = K.series_expand(k, 0, 2)
G, F = Ld.series_expand(k, 0, 1)
return... | Prepare the adiabatic elimination on an SLH object
Args:
slh: The SLH object to take the limit for
k: The scaling parameter $k \rightarrow \infty$. The default is a
positive symbol 'k'
Returns:
tuple: The objects ``Y, A, B, F, G, N``
necessary to compute the limitin... |
def eval_adiabatic_limit(YABFGN, Ytilde, P0):
Y, A, B, F, G, N = YABFGN
Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar()
Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar()
Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar()
dN = identity_matrix(N.sh... | Compute the limiting SLH model for the adiabatic approximation
Args:
YABFGN: The tuple (Y, A, B, F, G, N)
as returned by prepare_adiabatic_limit.
Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0.
P0: The projector onto the null-space of Y.
Returns:
SLH: L... |
def index_in_block(self, channel_index: int) -> int:
if channel_index < 0 or channel_index >= self.cdim:
raise ValueError()
struct = self.block_structure
if len(struct) == 1:
return channel_index, 0
i = 1
while sum(struct[:i]) <= channel_index a... | Return the index a channel has within the subblock it belongs to
I.e., only for reducible circuits, this gives a result different from
the argument itself.
Args:
channel_index (int): The index of the external channel
Raises:
ValueError: for an invalid `channel_... |
def get_blocks(self, block_structure=None):
if block_structure is None:
block_structure = self.block_structure
try:
return self._get_blocks(block_structure)
except IncompatibleBlockStructures as e:
raise e | For a reducible circuit, get a sequence of subblocks that when
concatenated again yield the original circuit. The block structure
given has to be compatible with the circuits actual block structure,
i.e. it can only be more coarse-grained.
Args:
block_structure (tuple): The... |
def feedback(self, *, out_port=None, in_port=None):
if out_port is None:
out_port = self.cdim - 1
if in_port is None:
in_port = self.cdim - 1
return self._feedback(out_port=out_port, in_port=in_port) | Return a circuit with self-feedback from the output port
(zero-based) ``out_port`` to the input port ``in_port``.
Args:
out_port (int or None): The output port from which the feedback
connection leaves (zero-based, default ``None`` corresponds
to the *last* p... |
def show(self):
# noinspection PyPackageRequirements
from IPython.display import Image, display
fname = self.render()
display(Image(filename=fname)) | Show the circuit expression in an IPython notebook. |
def render(self, fname=''):
import qnet.visualization.circuit_pyx as circuit_visualization
from tempfile import gettempdir
from time import time, sleep
if not fname:
tmp_dir = gettempdir()
fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time)))
... | Render the circuit expression and store the result in a file
Args:
fname (str): Path to an image file to store the result in.
Returns:
str: The path to the image file |
def space(self):
args_spaces = (self.S.space, self.L.space, self.H.space)
return ProductSpace.create(*args_spaces) | Total Hilbert space |
def free_symbols(self):
return set.union(
self.S.free_symbols, self.L.free_symbols, self.H.free_symbols) | Set of all symbols occcuring in S, L, or H |
def series_with_slh(self, other):
new_S = self.S * other.S
new_L = self.S * other.L + self.L
def ImAdjoint(m):
return (m.H - m) * (I / 2)
delta = ImAdjoint(self.L.adjoint() * self.S * other.L)
if isinstance(delta, Matrix):
new_H = self.H + othe... | Series product with another :class:`SLH` object
Args:
other (SLH): An upstream SLH circuit.
Returns:
SLH: The combined system. |
def concatenate_slh(self, other):
selfS = self.S
otherS = other.S
new_S = block_matrix(
selfS, zerosm((selfS.shape[0], otherS.shape[1]), dtype=int),
zerosm((otherS.shape[0], selfS.shape[1]), dtype=int), otherS)
new_L = vstackm((self.L, other.L))
... | Concatenation with another :class:`SLH` object |
def expand(self):
return SLH(self.S.expand(), self.L.expand(), self.H.expand()) | Expand out all operator expressions within S, L and H
Return a new :class:`SLH` object with these expanded expressions. |
def simplify_scalar(self, func=sympy.simplify):
return SLH(
self.S.simplify_scalar(func=func),
self.L.simplify_scalar(func=func),
self.H.simplify_scalar(func=func)) | Simplify all scalar expressions within S, L and H
Return a new :class:`SLH` object with the simplified expressions.
See also: :meth:`.QuantumExpression.simplify_scalar` |
def symbolic_master_equation(self, rho=None):
L, H = self.L, self.H
if rho is None:
rho = OperatorSymbol('rho', hs=self.space)
return (-I * (H * rho - rho * H) +
sum(Lk * rho * adjoint(Lk) -
(adjoint(Lk) * Lk * rho + rho * adjoint(Lk) * Lk... | Compute the symbolic Liouvillian acting on a state rho
If no rho is given, an OperatorSymbol is created in its place.
This correspnds to the RHS of the master equation
in which an average is taken over the external noise degrees of
freedom.
Args:
rho (Operator): A s... |
def symbolic_heisenberg_eom(
self, X=None, noises=None, expand_simplify=True):
L, H = self.L, self.H
if X is None:
X = OperatorSymbol('X', hs=(L.space | H.space))
summands = [I * (H * X - X * H), ]
for Lk in L.matrix.ravel():
summands.append... | Compute the symbolic Heisenberg equations of motion of a system
operator X. If no X is given, an OperatorSymbol is created in its
place. If no noises are given, this correspnds to the
ensemble-averaged Heisenberg equation of motion.
Args:
X (Operator): A system operator
... |
def block_perms(self):
if not self._block_perms:
self._block_perms = permutation_to_block_permutations(
self.permutation)
return self._block_perms | If the circuit is reducible into permutations within subranges of
the full range of channels, this yields a tuple with the internal
permutations for each such block.
:type: tuple |
def series_with_permutation(self, other):
combined_permutation = tuple([self.permutation[p]
for p in other.permutation])
return CPermutation.create(combined_permutation) | Compute the series product with another channel permutation circuit
Args:
other (CPermutation):
Returns:
Circuit: The composite permutation circuit (could also be the
identity circuit for n channels) |
def _factorize_for_rhs(self, rhs):
block_structure = rhs.block_structure
block_perm, perms_within_blocks \
= block_perm_and_perms_within_blocks(self.permutation,
block_structure)
fblockp = full_block_perm(block_perm, block_st... | Factorize a channel permutation circuit according the block
structure of the upstream circuit. This allows to move as much of the
permutation as possible *around* a reducible circuit upstream. It
basically decomposes
``permutation << rhs --> permutation' << rhs' << residual'``
... |
def _factor_rhs(self, in_port):
n = self.cdim
if not (0 <= in_port < n):
raise Exception
in_im = self.permutation[in_port]
# (I) is equivalent to
# m_{in_im -> (n-1)} << self << m_{(n-1) -> in_port}
# == (red_self + cid(1)) (I')
... | With::
n := self.cdim
in_im := self.permutation[in_port]
m_{k->l} := map_signals_circuit({k:l}, n)
solve the equation (I) containing ``self``::
self << m_{(n-1) -> in_port}
== m_{(n-1) -> in_im} << (red_self + cid(1)) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.