code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import urllib.parse
import json
import requests
import threading
from zentuxlog_client.endpoint import EndPoint
from zentuxlog_client.errors import (
RequestError,
ResponseCodeError,
TimeoutCustomError,
AuthMissing
)
class Client:
"""
Un client permet de requêter l'api déployée.
"""
def __init__(self, auth, settings, async_call=False):
"""Constructeur."""
self.id_client = auth['client_id']
self.auth = auth
settings.__dict__.update(self.auth)
self.settings = settings
self.payload = None
self.endpoint = EndPoint(settings=self.settings)
self.async_call = async_call
self.token = None
def send(self, data=None, logfile=None, method="GET", path=None, protected=True, headers=None, daemon=True):
"""
@param data: Data to be sent to API
"""
data_call = {
"method": method,
"path": path,
"protected": protected,
"headers": headers
}
if not data and logfile:
for log in logfile.generate(daemon):
data_call.update({"data": log})
if self.async_call:
t = threading.Thread(target=self.__call_api, kwargs=data_call)
t.start()
else:
self.__call_api(**data_call)
else:
data_call.update({'data': data})
if self.async_call:
t = threading.Thread(target=self.__call_api, kwargs=data_call)
return t.start()
else:
return self.__call_api(**data_call)
def __call_api(self, **kwargs):
timeout = self.settings.timeout
uri = self.endpoint.get_uri()
headers = kwargs['headers']
protected = kwargs['protected']
data = {
"data": kwargs['data'],
"sensor": self.settings.sensor_name
}
path = kwargs['path']
method = kwargs['method']
if not headers:
headers = dict()
if protected:
if not self.token:
self.__fetch_token()
if data and self.token:
bearer = "Bearer {token}".format(token=self.token)
headers.update({
'Authorization': bearer
})
if path:
uri = urllib.parse.urljoin(uri, path)
try:
if method == 'PUT':
raise NotImplementedError
elif method == 'GET':
return self.__get(uri, timeout, headers)
elif method == 'POST':
return self.__post(json.dumps(data), uri, timeout, headers)
elif method == 'DELETE':
raise NotImplementedError
except requests.exceptions.Timeout:
raise TimeoutCustomError("Timeout atteint: {} ms".format(timeout))
except requests.exceptions.RequestException as e:
raise RequestError(e)
def check(self):
"""
Vérification de l'api
"""
return self.send()
def __fetch_token(self):
"""Méthode privée qui permet de récupérer le token."""
data = {
'grant_type': 'password',
'username': self.settings.username,
'password': self.settings.password,
}
response = self.__post(
data=data,
uri=self.endpoint.get_url_token(),
auth=(self.settings.client_id, self.settings.client_secret),
timeout=self.settings.timeout
)
if 'access_token' in response:
self.token = response['access_token']
else:
raise AuthMissing
def _get_http_headers(self, additional_headers=None):
headers = {}
headers = self.settings.headers
if additional_headers:
headers.update(additional_headers)
return headers
def __get(self, uri, timeout, custom_headers):
response = requests.get(uri,
headers=self._get_http_headers(custom_headers),
timeout=timeout)
self.__check_errors(response)
return response.json()
def __post(self, data, uri, timeout, headers=None, auth=None):
if headers:
headers = self._get_http_headers(headers)
response = requests.post(uri, data=data, headers=headers, timeout=timeout, auth=auth)
self.__check_errors(response)
return response.json()
@staticmethod
def __check_errors(response):
status_code = response.status_code
if status_code == 200 or status_code == 201:
return
raise ResponseCodeError(status_code, response.text) | zentuxlog-client | /zentuxlog-client-1.0.3.tar.gz/zentuxlog-client-1.0.3/zentuxlog_client/client.py | client.py |
# zenutils
Collection of simple utils.
## Install
```
pip install zenutils
```
## Extra packages requires
- For python3.2 and python2.x, requires extra package: inspect2~=0.1.2
- For user who is using xxhash methods with hashutils, requires extra package: xxhash
- For user who is using sm3 methods with hashutils, requires extra package: sm3utils.
- If your python installation's hashlib already support sm3 hash method, you don't have to install sm3utils.
- xxhash and sm3utils are not put into this package's requirements, you need to install them by your self.
## Notice
- The hashutils' hash methods are different on different python installations. The list below is based on Python 3.10.6 x86_64 on windows. Mostly md5, sha1, sha224, sha256, sha384, sha512 methods are supported.
- The hashutils' DEFAULT_HASH_METHOD is sm3 and DEFAULT_PASSWORD_HASH_METHOD is ssm3, so if your python installation is not support sm3 hash method, you need to install sm3utils by yourself.
## Utils
1. zenutils.base64utils
1. a85decode
1. a85encode
1. b16decode
1. b16encode
1. b32decode
1. b32encode
1. b32hexdecode
1. b32hexencode
1. b64decode
1. b64encode
1. b85decode
1. b85encode
1. decode
1. decodebytes
1. encode
1. encodebytes
1. standard_b64decode
1. standard_b64encode
1. urlsafe_b64decode
1. urlsafe_b64encode
1. zenutils.baseutils
1. Null
1. zenutils.cacheutils
1. cache
1. get_cached_value
1. zenutils.cipherutils
1. Base64Encoder
1. CipherBase
1. DecryptFailed
1. EncoderBase
1. HexlifyEncoder
1. IvCipher
1. IvfCipher
1. MappingCipher
1. RawDataEncoder
1. S12Cipher
1. S1Cipher
1. S2Cipher
1. SafeBase64Encoder
1. Utf8Encoder
1. zenutils.dictutils
1. HttpHeadersDict
1. Object
1. attrgetorset
1. attrset
1. change
1. changes
1. deep_merge
1. diff
1. fix_object
1. ignore_none_item
1. prefix_key
1. select
1. to_object
1. touch
1. update
1. zenutils.errorutils
1. AccessDenied
1. AccountDisabledError
1. AccountLockedError
1. AccountRemovedError
1. AccountStatusError
1. AccountTemporaryLockedError
1. AnotherServiceError
1. AppAuthFailed
1. AuthError
1. BadParameter
1. BadParameterType
1. BadResponseContent
1. BadUserToken
1. BizError
1. BizErrorBase
1. CacheError
1. CaptchaOnlyAllowedOnce
1. CaptchaRequired
1. CaptchaValidateFailed
1. CastFailedError
1. CastToBooleanFailed
1. CastToFloatFailed
1. CastToIntegerFailed
1. CastToNumbericFailed
1. CastToStringFailed
1. ClientLostError
1. ConfigError
1. DataError
1. DatabaseError
1. EventNotRegistered
1. FormError
1. HttpError
1. InformalRequestError
1. InformalResultPackage
1. InformalResultPackage
1. LogicError
1. LoginRequired
1. MessageQueueError
1. MissingConfigItem
1. MissingField
1. MissingParameter
1. NetworkError
1. NoAccessPermissionError
1. NoDeletePermissionError
1. NoMatchingRouteFound
1. NoPermissionError
1. NoPermissionToCleanCacheError
1. NoReadPermissionError
1. NoUpstreamServerAvailabe
1. NoWritePermissionError
1. NotSupportedHttpMethod
1. NotSupportedTypeToCast
1. OK
1. ParamError
1. ParseJsonError
1. PermissionError
1. RepeatedlySubmitForm
1. ReqeustForbidden
1. ReqidDuplicateError
1. RequestExpired
1. SYSTEM_ERROR_CODE_MAPPING
1. ServiceError
1. StringTooLong
1. StringTooShort
1. SysError
1. TargetNotFound
1. TooLargeRequestError
1. TsExpiredError
1. TypeError
1. UndefinedError
1. UserDoesNotExist
1. UserPasswordError
1. ValueExceedsMaxLimit
1. ValueLessThanMinLimit
1. WrongFieldType
1. WrongParameterType
1. clean_language_name
1. get_error_info
1. get_language
1. set_error_info
1. set_language
1. zenutils.fsutils
1. TemporaryFile
1. copy
1. expand
1. file_content_replace
1. filecopy
1. first_exists_file
1. get_application_config_filepath
1. get_application_config_paths
1. get_safe_filename
1. get_size_deviation
1. get_size_display
1. get_swap_filename
1. get_temp_workspace
1. get_unit_size
1. info
1. mkdir
1. move
1. pathjoin
1. readfile
1. rename
1. rm
1. safe_write
1. size_unit_names
1. size_unit_upper_limit
1. touch
1. treecopy
1. write
1. zenutils.funcutils
1. BunchCallable
1. ChainableProxy
1. call_with_inject
1. chain
1. classproperty
1. get_all_builtin_exceptions
1. get_builtins_dict
1. get_class_name
1. get_default_values
1. get_inject_params
1. inspect
1. is_a_class
1. isclass
1. mcall_with_inject
1. signature
1. try_again_on_error
1. zenutils.hashutils
1. Base64ResultEncoder
1. Blake2BHexlifyPasswordHash
1. Blake2BPbkdf2PasswordHash
1. Blake2BPbkdf2PasswordHashColon
1. Blake2BSimplePasswordHash
1. Blake2BSimpleSaltPasswordHash
1. Blake2SHexlifyPasswordHash
1. Blake2SPbkdf2PasswordHash
1. Blake2SPbkdf2PasswordHashColon
1. Blake2SSimplePasswordHash
1. Blake2SSimpleSaltPasswordHash
1. DigestResultEncoder
1. HexlifyPasswordHashBase
1. HexlifyResultEncoder
1. Md4HexlifyPasswordHash
1. Md4Pbkdf2PasswordHash
1. Md4Pbkdf2PasswordHashColon
1. Md4SimplePasswordHash
1. Md4SimpleSaltPasswordHash
1. Md5HexlifyPasswordHash
1. Md5Pbkdf2PasswordHash
1. Md5Pbkdf2PasswordHashColon
1. Md5SimplePasswordHash
1. Md5SimpleSaltPasswordHash
1. Md5_Sha1HexlifyPasswordHash
1. Md5_Sha1Pbkdf2PasswordHash
1. Md5_Sha1Pbkdf2PasswordHashColon
1. Md5_Sha1SimplePasswordHash
1. Md5_Sha1SimpleSaltPasswordHash
1. Mdc2HexlifyPasswordHash
1. Mdc2Pbkdf2PasswordHash
1. Mdc2Pbkdf2PasswordHashColon
1. Mdc2SimplePasswordHash
1. Mdc2SimpleSaltPasswordHash
1. PasswordHashMethodBase
1. PasswordHashMethodNotSupportError
1. Pbkdf2PasswordHashBase
1. ResultEncoderBase
1. Ripemd160HexlifyPasswordHash
1. Ripemd160Pbkdf2PasswordHash
1. Ripemd160Pbkdf2PasswordHashColon
1. Ripemd160SimplePasswordHash
1. Ripemd160SimpleSaltPasswordHash
1. Sha1HexlifyPasswordHash
1. Sha1Pbkdf2PasswordHash
1. Sha1Pbkdf2PasswordHashColon
1. Sha1SimplePasswordHash
1. Sha1SimpleSaltPasswordHash
1. Sha224HexlifyPasswordHash
1. Sha224Pbkdf2PasswordHash
1. Sha224Pbkdf2PasswordHashColon
1. Sha224SimplePasswordHash
1. Sha224SimpleSaltPasswordHash
1. Sha256HexlifyPasswordHash
1. Sha256Pbkdf2PasswordHash
1. Sha256Pbkdf2PasswordHashColon
1. Sha256SimplePasswordHash
1. Sha256SimpleSaltPasswordHash
1. Sha384HexlifyPasswordHash
1. Sha384Pbkdf2PasswordHash
1. Sha384Pbkdf2PasswordHashColon
1. Sha384SimplePasswordHash
1. Sha384SimpleSaltPasswordHash
1. Sha3_224HexlifyPasswordHash
1. Sha3_224Pbkdf2PasswordHash
1. Sha3_224Pbkdf2PasswordHashColon
1. Sha3_224SimplePasswordHash
1. Sha3_224SimpleSaltPasswordHash
1. Sha3_256HexlifyPasswordHash
1. Sha3_256Pbkdf2PasswordHash
1. Sha3_256Pbkdf2PasswordHashColon
1. Sha3_256SimplePasswordHash
1. Sha3_256SimpleSaltPasswordHash
1. Sha3_384HexlifyPasswordHash
1. Sha3_384Pbkdf2PasswordHash
1. Sha3_384Pbkdf2PasswordHashColon
1. Sha3_384SimplePasswordHash
1. Sha3_384SimpleSaltPasswordHash
1. Sha3_512HexlifyPasswordHash
1. Sha3_512Pbkdf2PasswordHash
1. Sha3_512Pbkdf2PasswordHashColon
1. Sha3_512SimplePasswordHash
1. Sha3_512SimpleSaltPasswordHash
1. Sha512HexlifyPasswordHash
1. Sha512Pbkdf2PasswordHash
1. Sha512Pbkdf2PasswordHashColon
1. Sha512SimplePasswordHash
1. Sha512SimpleSaltPasswordHash
1. Sha512_224HexlifyPasswordHash
1. Sha512_224Pbkdf2PasswordHash
1. Sha512_224Pbkdf2PasswordHashColon
1. Sha512_224SimplePasswordHash
1. Sha512_224SimpleSaltPasswordHash
1. Sha512_256HexlifyPasswordHash
1. Sha512_256Pbkdf2PasswordHash
1. Sha512_256Pbkdf2PasswordHashColon
1. Sha512_256SimplePasswordHash
1. Sha512_256SimpleSaltPasswordHash
1. ShaHexlifyPasswordHash
1. ShaPbkdf2PasswordHash
1. ShaPbkdf2PasswordHashColon
1. ShaSimplePasswordHash
1. ShaSimpleSaltPasswordHash
1. SimplePasswordHashBase
1. SimpleSaltPasswordHashBase
1. Sm3HexlifyPasswordHash
1. Sm3Pbkdf2PasswordHash
1. Sm3Pbkdf2PasswordHashColon
1. Sm3SimplePasswordHash
1. Sm3SimpleSaltPasswordHash
1. WhirlpoolHexlifyPasswordHash
1. WhirlpoolPbkdf2PasswordHash
1. WhirlpoolPbkdf2PasswordHashColon
1. WhirlpoolSimplePasswordHash
1. WhirlpoolSimpleSaltPasswordHash
1. Xxh128HexlifyPasswordHash
1. Xxh128Pbkdf2PasswordHash
1. Xxh128Pbkdf2PasswordHashColon
1. Xxh128SimplePasswordHash
1. Xxh128SimpleSaltPasswordHash
1. Xxh32HexlifyPasswordHash
1. Xxh32Pbkdf2PasswordHash
1. Xxh32Pbkdf2PasswordHashColon
1. Xxh32SimplePasswordHash
1. Xxh32SimpleSaltPasswordHash
1. Xxh64HexlifyPasswordHash
1. Xxh64Pbkdf2PasswordHash
1. Xxh64Pbkdf2PasswordHashColon
1. Xxh64SimplePasswordHash
1. Xxh64SimpleSaltPasswordHash
1. algorithms_available
1. get_blake2b
1. get_blake2b_base64
1. get_blake2b_digest
1. get_blake2b_hexdigest
1. get_blake2s
1. get_blake2s_base64
1. get_blake2s_digest
1. get_blake2s_hexdigest
1. get_file_blake2b
1. get_file_blake2b_base64
1. get_file_blake2b_digest
1. get_file_blake2b_hexdigest
1. get_file_blake2s
1. get_file_blake2s_base64
1. get_file_blake2s_digest
1. get_file_blake2s_hexdigest
1. get_file_hash
1. get_file_hash_base64
1. get_file_hash_hexdigest
1. get_file_hash_result
1. get_file_md4
1. get_file_md4_base64
1. get_file_md4_digest
1. get_file_md4_hexdigest
1. get_file_md5
1. get_file_md5_base64
1. get_file_md5_digest
1. get_file_md5_hexdigest
1. get_file_md5_sha1
1. get_file_md5_sha1_base64
1. get_file_md5_sha1_digest
1. get_file_md5_sha1_hexdigest
1. get_file_mdc2
1. get_file_mdc2_base64
1. get_file_mdc2_digest
1. get_file_mdc2_hexdigest
1. get_file_ripemd160
1. get_file_ripemd160_base64
1. get_file_ripemd160_digest
1. get_file_ripemd160_hexdigest
1. get_file_sha
1. get_file_sha1
1. get_file_sha1_base64
1. get_file_sha1_digest
1. get_file_sha1_hexdigest
1. get_file_sha224
1. get_file_sha224_base64
1. get_file_sha224_digest
1. get_file_sha224_hexdigest
1. get_file_sha256
1. get_file_sha256_base64
1. get_file_sha256_digest
1. get_file_sha256_hexdigest
1. get_file_sha384
1. get_file_sha384_base64
1. get_file_sha384_digest
1. get_file_sha384_hexdigest
1. get_file_sha3_224
1. get_file_sha3_224_base64
1. get_file_sha3_224_digest
1. get_file_sha3_224_hexdigest
1. get_file_sha3_256
1. get_file_sha3_256_base64
1. get_file_sha3_256_digest
1. get_file_sha3_256_hexdigest
1. get_file_sha3_384
1. get_file_sha3_384_base64
1. get_file_sha3_384_digest
1. get_file_sha3_384_hexdigest
1. get_file_sha3_512
1. get_file_sha3_512_base64
1. get_file_sha3_512_digest
1. get_file_sha3_512_hexdigest
1. get_file_sha512
1. get_file_sha512_224
1. get_file_sha512_224_base64
1. get_file_sha512_224_digest
1. get_file_sha512_224_hexdigest
1. get_file_sha512_256
1. get_file_sha512_256_base64
1. get_file_sha512_256_digest
1. get_file_sha512_256_hexdigest
1. get_file_sha512_base64
1. get_file_sha512_digest
1. get_file_sha512_hexdigest
1. get_file_sha_base64
1. get_file_sha_digest
1. get_file_sha_hexdigest
1. get_file_sm3
1. get_file_sm3_base64
1. get_file_sm3_digest
1. get_file_sm3_hexdigest
1. get_file_whirlpool
1. get_file_whirlpool_base64
1. get_file_whirlpool_digest
1. get_file_whirlpool_hexdigest
1. get_file_xxh128
1. get_file_xxh128_base64
1. get_file_xxh128_digest
1. get_file_xxh128_hexdigest
1. get_file_xxh32
1. get_file_xxh32_base64
1. get_file_xxh32_digest
1. get_file_xxh32_hexdigest
1. get_file_xxh64
1. get_file_xxh64_base64
1. get_file_xxh64_digest
1. get_file_xxh64_hexdigest
1. get_hash
1. get_hash_base64
1. get_hash_hexdigest
1. get_hash_result
1. get_md4
1. get_md4_base64
1. get_md4_digest
1. get_md4_hexdigest
1. get_md5
1. get_md5_base64
1. get_md5_digest
1. get_md5_hexdigest
1. get_md5_sha1
1. get_md5_sha1_base64
1. get_md5_sha1_digest
1. get_md5_sha1_hexdigest
1. get_mdc2
1. get_mdc2_base64
1. get_mdc2_digest
1. get_mdc2_hexdigest
1. get_password_hash
1. get_password_hash_methods
1. get_pbkdf2_blake2b
1. get_pbkdf2_blake2s
1. get_pbkdf2_hmac
1. get_pbkdf2_md4
1. get_pbkdf2_md5
1. get_pbkdf2_md5_sha1
1. get_pbkdf2_mdc2
1. get_pbkdf2_ripemd160
1. get_pbkdf2_sha
1. get_pbkdf2_sha1
1. get_pbkdf2_sha224
1. get_pbkdf2_sha256
1. get_pbkdf2_sha384
1. get_pbkdf2_sha3_224
1. get_pbkdf2_sha3_256
1. get_pbkdf2_sha3_384
1. get_pbkdf2_sha3_512
1. get_pbkdf2_sha512
1. get_pbkdf2_sha512_224
1. get_pbkdf2_sha512_256
1. get_pbkdf2_sm3
1. get_pbkdf2_whirlpool
1. get_pbkdf2_xxh128
1. get_pbkdf2_xxh32
1. get_pbkdf2_xxh64
1. get_ripemd160
1. get_ripemd160_base64
1. get_ripemd160_digest
1. get_ripemd160_hexdigest
1. get_salted_hash_base64
1. get_sha
1. get_sha1
1. get_sha1_base64
1. get_sha1_digest
1. get_sha1_hexdigest
1. get_sha224
1. get_sha224_base64
1. get_sha224_digest
1. get_sha224_hexdigest
1. get_sha256
1. get_sha256_base64
1. get_sha256_digest
1. get_sha256_hexdigest
1. get_sha384
1. get_sha384_base64
1. get_sha384_digest
1. get_sha384_hexdigest
1. get_sha3_224
1. get_sha3_224_base64
1. get_sha3_224_digest
1. get_sha3_224_hexdigest
1. get_sha3_256
1. get_sha3_256_base64
1. get_sha3_256_digest
1. get_sha3_256_hexdigest
1. get_sha3_384
1. get_sha3_384_base64
1. get_sha3_384_digest
1. get_sha3_384_hexdigest
1. get_sha3_512
1. get_sha3_512_base64
1. get_sha3_512_digest
1. get_sha3_512_hexdigest
1. get_sha512
1. get_sha512_224
1. get_sha512_224_base64
1. get_sha512_224_digest
1. get_sha512_224_hexdigest
1. get_sha512_256
1. get_sha512_256_base64
1. get_sha512_256_digest
1. get_sha512_256_hexdigest
1. get_sha512_base64
1. get_sha512_digest
1. get_sha512_hexdigest
1. get_sha_base64
1. get_sha_digest
1. get_sha_hexdigest
1. get_sm3
1. get_sm3_base64
1. get_sm3_digest
1. get_sm3_hexdigest
1. get_whirlpool
1. get_whirlpool_base64
1. get_whirlpool_digest
1. get_whirlpool_hexdigest
1. get_xxh128
1. get_xxh128_base64
1. get_xxh128_digest
1. get_xxh128_hexdigest
1. get_xxh32
1. get_xxh32_base64
1. get_xxh32_digest
1. get_xxh32_hexdigest
1. get_xxh64
1. get_xxh64_base64
1. get_xxh64_digest
1. get_xxh64_hexdigest
1. is_the_same_hash_method
1. method_load
1. new
1. pbkdf2_hmac
1. register_hexlify_password_hash
1. register_password_hash_method
1. register_pbkdf2_password_hash
1. register_simple_password_hash
1. register_simple_salt_password_hash
1. setup_hash_method_loader
1. validate_password_hash
1. validate_pbkdf2_blake2b
1. validate_pbkdf2_blake2s
1. validate_pbkdf2_hmac
1. validate_pbkdf2_md4
1. validate_pbkdf2_md5
1. validate_pbkdf2_md5_sha1
1. validate_pbkdf2_mdc2
1. validate_pbkdf2_ripemd160
1. validate_pbkdf2_sha
1. validate_pbkdf2_sha1
1. validate_pbkdf2_sha224
1. validate_pbkdf2_sha256
1. validate_pbkdf2_sha384
1. validate_pbkdf2_sha3_224
1. validate_pbkdf2_sha3_256
1. validate_pbkdf2_sha3_384
1. validate_pbkdf2_sha3_512
1. validate_pbkdf2_sha512
1. validate_pbkdf2_sha512_224
1. validate_pbkdf2_sha512_256
1. validate_pbkdf2_sm3
1. validate_pbkdf2_whirlpool
1. validate_pbkdf2_xxh128
1. validate_pbkdf2_xxh32
1. validate_pbkdf2_xxh64
1. zenutils.httputils
1. download
1. get_sitename
1. get_url_filename
1. get_url_save_path
1. get_urlinfo
1. urlparse
1. zenutils.importutils
1. get_caller_globals
1. get_caller_locals
1. import_from_string
1. import_module
1. zenutils.jsonutils
1. SimpleJsonEncoder
1. make_simple_json_encoder
1. register_global_encoder
1. simple_json_dumps
1. zenutils.listutils
1. append_new
1. chunk
1. clean_none
1. compare
1. compare_execute
1. first
1. group
1. ignore_none_element
1. int_list_to_bytes
1. is_ordered
1. list2dict
1. pad
1. replace
1. topological_sort
1. topological_test
1. unique
1. zenutils.logutils
1. get_console_handler
1. get_file_handler
1. get_simple_config
1. setup
1. zenutils.nameutils
1. get_last_names
1. get_random_name
1. get_suggest_first_names
1. guess_lastname
1. guess_surname
1. zenutils.numericutils
1. _infinity
1. binary_decompose
1. bytes2ints
1. decimal_change_base
1. float_split
1. from_bytes
1. get_float_part
1. infinity
1. int2bytes
1. ints2bytes
1. is_infinity
1. ninfinity
1. pinfinity
1. zenutils.packutils
1. AbstractResultPacker
1. RcmPacker
1. zenutils.perfutils
1. timeit
1. zenutils.randomutils
1. Lcg31Random
1. Random
1. UuidGenerator
1. choices
1. get_password_seed32
1. uuid1
1. uuid3
1. uuid4
1. uuid5
1. zenutils.serviceutils
1. DebugService
1. ServiceBase
1. zenutils.sixutils
1. BASESTRING_TYPES
1. BYTES
1. BYTES_TYPE
1. INT_TO_BYTES
1. NUMERIC_TYPES
1. PY2
1. PY3
1. STR_TYPE
1. TEXT
1. bchar
1. bstr_to_array
1. bytes_to_array
1. create_new_class
1. default_encoding
1. default_encodings
1. force_bytes
1. force_text
1. zenutils.socketserverutils
1. NStreamExchangeProtocolBase
1. ServerEngineBase
1. ServerHandle
1. zenutils.strutils
1. BAI
1. BASE64_CHARS
1. HEXLIFY_CHARS
1. QIAN
1. SHI
1. URLSAFEB64_CHARS
1. WAN
1. YI
1. binarify
1. bytes2ints
1. camel
1. captital_number
1. char_force_to_int
1. chunk
1. clean
1. combinations
1. combinations2
1. decodable
1. default_cn_digits
1. default_cn_float_places
1. default_cn_negative
1. default_cn_places
1. default_cn_yuan
1. default_encoding
1. default_encodings
1. default_quotes
1. default_random_string_choices
1. do_clean
1. encodable
1. force_float
1. force_int
1. force_numberic
1. force_type_to
1. format_with_mapping
1. get_all_substrings
1. get_base64image
1. get_image_bytes
1. html_element_css_append
1. int2bytes
1. ints2bytes
1. is_base64_decodable
1. is_chinese_character
1. is_hex_digits
1. is_str_composed_by_the_choices
1. is_unhexlifiable
1. is_urlsafeb64_decodable
1. is_uuid
1. join_lines
1. no_mapping
1. none_to_empty_string
1. parse_base64image
1. random_string
1. remove_prefix
1. remove_suffix
1. reverse
1. simplesplit
1. smart_get_binary_data
1. split
1. split2
1. str_composed_by
1. stringlist_append
1. strip_string
1. substrings
1. text_display_length
1. text_display_shorten
1. unbinarify
1. unquote
1. wholestrip
1. zenutils.sysutils
1. default_timeout_kill
1. execute_script
1. get_current_thread_id
1. get_node_ip
1. get_random_script_name
1. get_worker_id
1. psutil_timeout_kill
1. zenutils.threadutils
1. Counter
1. LoopIdle
1. Service
1. ServiceStop
1. ServiceTerminate
1. SimpleConsumer
1. SimpleProducer
1. SimpleProducerConsumerServer
1. SimpleServer
1. StartOnTerminatedService
1. zenutils.treeutils
1. SimpleRouterTree
1. build_tree
1. print_tree
1. print_tree_callback
1. tree_walk
1. zenutils.typingutils
1. Number
1. STRING_ENCODINGS
1. register_global_caster
1. smart_cast
## Compatibility
Test passed with python versions:
1. Python 2.7 passed
1. Python 3.2 passed
1. Python 3.3 passed
1. Python 3.4 passed
1. Python 3.5 passed
1. Python 3.7 passed
1. Python 3.8 passed
1. Python 3.9 passed
1. Python 3.10 passed
## Release
### v0.1.0
- First release.
### v0.2.0
- Add treeutils.SimpleRouterTree.
- Add randomutils.HashPrng.
- Add hashutils.get_password_hash and hashutils.validate_password_hash.
- Add dictutils.HttpHeadersDict.
- Add sysutils.get_node_ip.
### v0.3.1
- Add funcutils.retry.
- Fix hashutils.validate_password_hash problem.
### v0.3.2
- Add sm3 hash support in hashutils.
- Add xxhash hash support in hashutils.
- Export hashutils.pbkdf2_hmac to work with your self defined hash methods.
- Fix problem in sysutils.get_random_script_name on windows.
- Fix path string problem in tests.test_httputils on windows.
### v0.3.3
- Fix funcutils.isclass can not detect classes with metaclass. Use inspect.isclass instead.
- Add cacheutils.cache.
### v0.3.5
- Change default log file path from `pwd`/app.log to `pwd`/logs/app.log.
- Add fsutils.get_swap_filename.
- Add fsutils.safe_write.
- Add fsutils.get_safe_filename.
### v0.3.6
- Add sixutils.create_new_class.
- Fix hashutils problem in python3.3 and below.
- Extend numericutils.int2bytes as int.to_bytes.
### V0.3.7
- Add randomutils.Lcg31Random.
- Add randomutils.get_password_seed32.
### v0.3.8
- Fix force_text in handling NON-STR type data.
### v0.3.9
- Add delete_script parameter in fsutils.execute_script.
### v0.3.12
- dictutils.Object add select method.
- Add errorutils.
- Add packutils.
- Add perfutils.
- Add serviceutils.
### v0.3.15
- Add serviceutils.ServerEngineBase.
### v0.3.16
- Rename serviceutils.ServerEngineBase to socketserverutils.ServerEngineBase.
- Add socketserverutils.NStreamExchangeProtocolBase.
- Add ServerHandle.
| zenutils | /zenutils-0.3.16.tar.gz/zenutils-0.3.16/README.md | README.md |
Zenv
====
Zenv is container based virtual environments.
The main goal of Zenv is to simplify access to applications inside container, making it seamless in use like native (host-machine) applications
## Usage
```shell
> zenv init
Zenv created!
> # run `ls` command inside contaner
> ze ls
```
## Motivation
As a developer, when set up a project locally, I usually need to install additional applications on the system. Of course, modern package managers such as poetry, pipenv, npm, cargo, ext, perfectly solve for us most of the problems with dependencies within a single stack of technologies. But they do not allow to solve the problem with the installation of system libraries. If you have a lot of projects that require different versions of system libraries, then you have problems
In production, this problem has long been solved by container insulation, and as a rule, it is a `Docker`. Therefore, many of my colleagues use docker-images and docker-compose, not only to run services in a production environment but also to develop and debug programs on a local machine
Unfortunately, there are several problems along the way:
- Some of your familiar utilities may not be preinstalled in the container
- If you try to install packages in the process, you will encounter the lack of necessary rights
- Forget about debugging with `print`
- The main thing is lost the usual experience, you can not use your favorite customized shell
Of course, the problems described above are solved by creating a docker image specifically for developing a specific project, `zenv` just helps to create such containers very simply
## Features
- Simplify: all interaction with the container occurs with one short command: `ze`
- Zenv automatically forwarded current directory to the container with the same PWD
- Zenv automatically forwarded current UserID, GroupID to container
Therefore, files created in the container have the same rights as those created in the native console and you can also use `sudo` to get privileges
```shell
> sudo ze <command>
```
or
```shell
> sudo !!
```
- Zenv can forwarded environment vars as is native
```shell
> MYVAR=LIVE!!!! ze env
```
- And of course your could combinate native and containerized commands in Unix pipes
```shell
> ze ls | head -7 | ze tail -5
```
- Minimal performance impact
- Customization: you can additionally control container parameters using Zenvfile
## Install
1. Make sure you have the latest version of `Docker` installed
2. For linux, make sure you have your user’s [rights are allowed](https://docs.docker.com/install/linux/linux-postinstall/) to interact with doker
3. Make sure that you have python version 3.6 or higher
4. Execute:
```shell
> sudo pip install zenv-cli
# or
> sudo pip3 install zenv-cli
```
## How It works
By nature, zenv is a small automated layer over the official docker CLI
### init
Command `zenv init` create `Zenvfile` in current directory. This file describes the relationship with the docker image and container that will be created to execute isolated commands.
By default, used image is `ubuntu: latest`.
But you can change it by setting `-i` flag. For example:
```shell
> zenv init -i python:latest
```
Or edit `Zenvfile` manually
### Execute
Command `zenv exec <COMMAND>` or it shot alias `ze <COMMAND>` run `<COMMAND>` in a container environment. When running the command:
- Zenv checks current container status (running, stopped, removed), and up container if need.
- The container run with the command `sleep infinity`. Therefore it will be easily accessible
- UID and GID that ran the command are pushed into the container. Therefor your could use `sudo ze <COMMAND>`
- When executing the command, the directory from the path where Zenvfile is located is forwarded to the container as is a current PWD. Therefor your could run `ze` from deep into directories relative to Zenvfile
- Environment variables are also thrown into the container as a native.
```
> MYVAR=SUPER ze env
```
To avoid conflicts between host and container variables, all installed system variables are placed in the blacklist when Zenvfile is created, from which editing can be removed
### Other commands
```shell
> zenv --help
Usage: zenv [OPTIONS] COMMAND [ARGS]...
ZENV(Zen-env): Containers manager for developer environment
Usage:
> zenv init -i centos:latest & ze cat /etc/redhat-release
Options:
--help Show this message and exit.
Commands:
exec Call some command inside the container
info Show current container info
init Initialize Environment: create Zenvfile
rm Remove container (will stop the container, if need)
stop Stop container
stop-all Stop all zenv containers
```
## Example install jupyter notebook
```shell
> mkgir notebooks
> cd notebooks
> zenv init -i python:3.7.3
```
After edit Zenvfile to explode notebook ports. Update `ports = []` to `ports = ["8888:8888"]`
```
> sudo ze pip install jupyter numpy scipy matplotlib
```
Run notebook
```
> ze jupyter notebook --ip 0.0.0.0
```
launch your browser with url: http://localhost:8888
Also you could add this commands to Zenvfile:
```toml
[run]
init_commands = [
[ "__create_user__"],
["pip", "install", "jupyter", "numpy", "scipy", "matplotlib"]
]
[commands]
notebook = ["jupyter", "notebook", "--ip", "0.0.0.0"]
```
And launch notebook with command
```
> ze notebook
```
## Zenvfile
```toml
[main]
image = "ubuntu:latest"
name = "zenv-project" # container name
debug = false # for show docker commands
[run]
command = [ "__sleep__",]
init_commands = [ [ "__create_user__",],]
[exec]
env_file = ""
env_excludes = [ "TMPDIR",]
[run.options]
volume = [ "{zenvfilepath}:{zenvfilepath}:rw",]
detach = "true"
publish = []
[commands]
__sleep__ = [ "sleep", "365d",]
__create_user__ = [ "useradd", "-m", "-r", "-u", "{uid}", "-g", "{gid}", "zenv",]
```
| zenv-cli | /zenv-cli-0.4.3.tar.gz/zenv-cli-0.4.3/README.md | README.md |
import subprocess
import logging as logger
from . import const, utils
def get_command_with_options(command, aliases, exec_params):
"""
Find command by aliases and build exec docker options
"""
if command[0] in aliases:
key = command[0]
command = aliases[key]['command'] + list(command[1:])
command_exec_params = aliases[key].get('exec', {})
exec_params = utils.merge_config(command_exec_params, exec_params)
dotenv_env = (
utils.load_dotenv(exec_params['env_file'])
if 'env_file' in exec_params and exec_params['env_file'] else {}
)
exec_options = exec_params.get('options', {})
exec_options['env'] = utils.composit_environment(
dotenv_env=dotenv_env,
zenvfile_env=exec_options.get('env', {}),
blacklist=exec_params.get('env_excludes', {})
)
docker_exec_options = utils.build_docker_options(exec_options)
return command, docker_exec_options
def call(config, command):
container_name = config['main']['name']
container_status = status(container_name)
# composite environments
command, exec_options = get_command_with_options(
command, config['aliases'], config['exec']
)
if container_status == const.STATUS_NOT_EXIST:
options = {'name': container_name, **config['run']['options']}
run_command, _ = get_command_with_options(
config['run']['command'], config['aliases'], {})
run(
image=config['main']['image'],
command=run_command,
options=utils.build_docker_options(options),
path=config['main']['zenvfilepath']
)
# run init commands:
for init_command in config['run']['init_commands']:
init_command, init_options = get_command_with_options(
init_command, config['aliases'], {}
)
exec_(container_name, init_command, init_options)
elif container_status == const.STATUS_STOPED:
cmd = ['docker', 'start', container_name]
logger.debug(cmd)
subprocess.run(cmd)
return exec_(container_name, command, exec_options)
def run(image, command, options, path):
cmd = ['docker', 'run', *options, image, *command]
with utils.in_directory(path):
logger.debug(cmd)
result = subprocess.run(cmd)
return result.returncode
def exec_(container_name, command, options):
cmd = ('docker', 'exec', *options, container_name, *command)
logger.debug(cmd)
return subprocess.run(cmd).returncode
def status(container_name):
cmd = (
f"docker ps --all --filter 'name={container_name}' "
"--format='{{.Status}}'"
)
logger.debug(cmd)
result = subprocess.run(cmd, shell=True, check=True, capture_output=True)
status = (
result.stdout.decode().split()[0].upper() if result.stdout else None
)
if not status:
return const.STATUS_NOT_EXIST
elif status == 'EXITED':
return const.STATUS_STOPED
elif status == 'UP':
return const.STATUS_RUNNING
def version():
cmd = 'docker version'
subprocess.run(cmd, shell=True)
def stop(container_name):
cmd = f'docker stop {container_name}'
subprocess.run(cmd, shell=True)
def rm(container_name):
current_status = status(container_name)
if current_status == const.STATUS_RUNNING:
stop(container_name)
if current_status == const.STATUS_NOT_EXIST:
return
cmd = f'docker rm {container_name}'
subprocess.run(cmd, shell=True)
def stop_all(exclude_containers=()):
"""
Stop all containers started with `zenv-`
"""
cmd = (
"docker ps --format='{{.Names}}'"
)
result = subprocess.run(cmd, shell=True, check=True, capture_output=True)
for container_name in result.stdout.decode().split('\n'):
if (
container_name.startswith(const.CONTAINER_PREFIX + '-')
and container_name not in exclude_containers
):
stop(container_name) | zenv-cli | /zenv-cli-0.4.3.tar.gz/zenv-cli-0.4.3/zenv/core.py | core.py |
import os
import sys
import logging
from pathlib import Path
from contextlib import contextmanager
import click
import toml
from dotenv import parser
from . import const
class Default(dict):
def __missing__(self, key):
return '{' + key + '}'
def load_dotenv(dotenvfile):
try:
with open(dotenvfile) as file:
environments = [
bind.original.string.strip()
for bind in parser.parse_stream(file)
if not bind.error
]
except FileNotFoundError:
raise click.ClickException(f'Env file not found {dotenvfile}')
return environments
def get_config(zenvfile=None):
if not zenvfile:
zenvfile = find_file(os.getcwd(), fname=const.DEFAULT_FILENAME)
if not zenvfile:
raise click.ClickException('Zenvfile don\'t find. Make `zenv init`')
params = Default(
zenvfilepath=os.path.dirname(zenvfile),
pwd=os.getcwd(),
uid=os.getuid(),
gid=os.getgid(),
tty='true' if sys.stdin.isatty() else 'false',
env_excludes='[]'
)
content = Path(zenvfile).read_text().format_map(params)
config = toml.loads(content)
content = const.CONFIG_TEMPLATE.format_map(params)
origin_config = toml.loads(content)
merge_config(origin_config, origin_config['hidden'])
config = merge_config(config, origin_config)
# init logging
if 'debug' in config['main'] and config['main']['debug']:
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
logging.basicConfig(level=loglevel)
return config
def find_file(path: str, fname: str):
root_flag = path == '/'
while True:
fpath = os.path.join(path, fname)
if os.path.isfile(fpath):
return fpath
path = os.path.dirname(path)
if path == '/' and root_flag:
return None
root_flag = path == '/'
@contextmanager
def in_directory(path):
pwd = os.getcwd()
os.chdir(path)
yield path
os.chdir(pwd)
def merge_config(custom, origin):
"""
Update `custom` config data from `origin` config data
"""
if not isinstance(custom, dict):
custom = {}
for key, value in origin.items():
if key not in custom:
custom[key] = value
elif isinstance(value, dict):
custom[key] = merge_config(custom[key], value)
return custom
def composit_environment(dotenv_env, zenvfile_env, blacklist):
env = {}
# low priority
env.update({row.split('=', 1)[0]: row for row in dotenv_env})
# medium priority
env.update({row.split('=', 1)[0]: row for row in zenvfile_env})
# high priority
env.update({
var: f'{var}={value}' for var, value in os.environ.items()
if var not in blacklist
})
return list(env.values())
def build_docker_options(params):
options = []
for param, value in params.items():
if value in ("true", "false"):
option = [f'--{param}'] if value == "true" else []
elif isinstance(value, list):
option = []
for val in value:
option.extend([f'--{param}', val])
else:
option = [f'--{param}', value]
options.extend(option)
return options | zenv-cli | /zenv-cli-0.4.3.tar.gz/zenv-cli-0.4.3/zenv/utils.py | utils.py |
import os
import sys
import click
import toml
from . import const, utils, core
@click.group()
def cli():
"""
ZENV(Zen-env): Containers manager for developer environment
Usage:
> zenv init -i centos:latest & ze cat /etc/redhat-release
"""
pass
@cli.command()
@click.option('--image', '-i', default=const.DEFAULT_IMAGE,
help='Docker Image')
@click.option('--template', '-t', default=None, help='Zenvfile template')
@click.option('--container-name', '-c', default=None, help='Container name')
def init(image, template, container_name):
"""Initialize Environment: create Zenvfile"""
fpath = os.path.join(os.getcwd(), const.DEFAULT_FILENAME)
if os.path.exists(fpath):
raise click.ClickException(f'{fpath} already exist')
if template:
if not os.path.exists(template):
raise click.ClickException(f'Tempate ({template}) not exist')
with open(template, 'r') as zenvfile_template:
zenv_template = zenvfile_template.read()
else:
zenv_template = const.INIT_TEMPLATE
name = (
container_name
if container_name else os.path.basename(os.path.dirname(fpath))
)
image = image if image else const.DEFAULT_IMAGE
config_str = zenv_template.format_map(utils.Default(
id=const.CONTAINER_PREFIX,
image=image,
container_name=name or 'root',
env_excludes='["' + '", "'.join(os.environ.keys()) + '"]'
))
with open(fpath, 'w') as f:
f.write(config_str)
click.echo('Zenvfile created')
@cli.command(context_settings=dict(ignore_unknown_options=True),
add_help_option=False)
@click.option('--zenvfile', default=None, help='Path to Zenvfile')
@click.argument('command', required=True, nargs=-1, type=click.UNPROCESSED)
def exec(zenvfile, command):
"""Call some command inside the container"""
config = utils.get_config(zenvfile)
exit_code = core.call(config, command)
sys.exit(exit_code)
@cli.command()
@click.option('--zenvfile', default=None, help='Path to Zenvfile')
def info(zenvfile):
"""Show current container info"""
config = utils.get_config(zenvfile)
click.echo(f'Zenvfile: {config["main"]["zenvfilepath"]}')
click.echo(f'Image: {config["main"]["image"]}')
click.echo(f'Container: {config["main"]["name"]}')
status = core.status(config['main']['name'])
click.echo(f'Status: {status}')
commands = [
(alias, cmd)
for alias, cmd in config['aliases'].items()
if not alias.startswith('_')
]
if commands:
click.echo('Aliases:')
for alias, cmd in commands:
if 'description' in cmd:
descr = cmd['description']
else:
descr = ' '.join(cmd['command'])
if len(descr) > 80:
descr = descr[: 74] + ' ...'
click.echo(f' - {alias}: {descr}')
@cli.command()
@click.option('--zenvfile', default=None, help='Path to Zenvfile')
def stop(zenvfile):
"""Stop container"""
config = utils.get_config(zenvfile)
core.stop(config['main']['name'])
@cli.command()
@click.option('--zenvfile', default=None, help='Path to Zenvfile')
def rm(zenvfile):
"""Remove container (will stop the container, if need)"""
config = utils.get_config(zenvfile)
core.rm(config['main']['name'])
@cli.command(name='stop-all')
@click.option('--zenvfile', default=None, help='Path to Zenvfile')
@click.option('--exclude-current', '-e', 'exclude_current', is_flag=True,
help='Exclude current contaiчner')
def stop_all(zenvfile, exclude_current):
"""Stop all zenv containers"""
excludes = []
if exclude_current:
config = utils.get_config(zenvfile)
excludes.append(config['main']['name'])
core.stop_all(excludes) | zenv-cli | /zenv-cli-0.4.3.tar.gz/zenv-cli-0.4.3/zenv/cli.py | cli.py |
import importlib
import inspect
import urllib
__author__ = 'renzo'
class PathNotFound(Exception): pass
package_base = "web"
home_base = "home"
index_base = "index"
def _to_abs_package(package_slices):
if package_slices:
return package_base + "." + ".".join(package_slices)
return package_base
def _check_convention_params(args, convention_params):
convention_list = []
for a in args:
if a in convention_params:
convention_list.append(convention_params.get(a))
else:
break
return convention_list
def _check_params(params, convention_params, spec, **kwargs):
args = spec[0]
all_params = _check_convention_params(args, convention_params) + params
param_num = len(all_params)
max_args = len(args) if args else 0
defaults = spec[3]
defaults_num = len(defaults) if defaults else 0
min_args = max_args - defaults_num
kwargs_num = len(kwargs)
all_args_num = param_num + kwargs_num
if min_args <= all_args_num <= max_args: return all_params
varargs = spec[1]
method_kwargs = spec[2]
if varargs and method_kwargs: return all_params
if varargs and not kwargs and param_num >= min_args:
return all_params
if method_kwargs and param_num >= (min_args - kwargs_num):
return all_params
def _import_helper(package, module_name, fcn_name, params, convention_params, **kwargs):
try:
full_module = package + "." + module_name
module = importlib.import_module(full_module)
if hasattr(module, fcn_name):
fcn = getattr(module, fcn_name)
if fcn and inspect.isfunction(fcn):
all_params = _check_params(params, convention_params, inspect.getargspec(fcn), **kwargs)
if not (all_params is None):
return fcn, all_params
except ImportError:
pass
def _build_pack_and_slices(package, slices):
slice_number = min(len(slices), 2)
package = ".".join([package] + slices[:-slice_number])
path_slices = slices[-slice_number:]
return package, path_slices
def _search_full_path(package, path_slices, defaults=[], params=[], convention_params={}, **kwargs):
slices = path_slices + defaults
if len(slices) < 2: return
pack, slices = _build_pack_and_slices(package, slices)
result = _import_helper(pack, *slices, params=params, convention_params=convention_params, **kwargs)
if result or not path_slices:
return result
params.insert(0, path_slices.pop())
return _search_full_path(package, path_slices, defaults, params, convention_params, **kwargs)
def _maybe_import(package, path_slices, convention_params, **kwargs):
result = _search_full_path(package, path_slices[:], [], [], convention_params, **kwargs)
if result: return result
result = _search_full_path(package, path_slices[:], [index_base], [], convention_params, **kwargs)
if result: return result
result = _search_full_path(package, path_slices[:], [home_base, index_base], [], convention_params, **kwargs)
if result: return result
raise PathNotFound()
def to_handler(path, convention_params={}, **kwargs):
decoded_path = urllib.unquote(path)
path_slices = [d for d in decoded_path.split("/") if d != ""]
# Try importing package.handler.method
return _maybe_import(package_base, path_slices, convention_params, **kwargs)
def _build_params(*params):
if params:
def f(p):
if isinstance(p, basestring):
return urllib.quote(p)
return urllib.quote(str(p))
params = [f(p) for p in params]
return "/" + "/".join(params)
return ""
def to_path(handler, *params):
params = _build_params(*params)
if inspect.ismodule(handler):
name = handler.__name__
else:
name = handler.__module__ + "/" + handler.__name__
name = name.replace(package_base, "", 1)
def remove_from_end(path, suffix):
return path[:-len(suffix)-1] if path.endswith(suffix) else path
home_index = '/'.join((home_base, index_base))
name=remove_from_end(name,home_index)
name=remove_from_end(name,index_base)
if not name: return params or "/"
return name.replace(".", "/") + params
def _extract_full_module(klass):
return klass.__module__ + "/" + klass.__name__ | zenwarch | /zenwarch-2.1.2.tar.gz/zenwarch-2.1.2/zen/router.py | router.py |
from __future__ import absolute_import, unicode_literals
import json
import logging
import traceback
import time
from google.appengine.api import app_identity, mail, capabilities
from google.appengine.runtime import DeadlineExceededError
from zen.router import PathNotFound
def get_apis_statuses(e):
if not isinstance(e, DeadlineExceededError):
return {}
t1 = time.time()
statuses = {
'blobstore': capabilities.CapabilitySet('blobstore').is_enabled(),
'datastore_v3': capabilities.CapabilitySet('datastore_v3').is_enabled(),
'datastore_v3_write': capabilities.CapabilitySet('datastore_v3', ['write']).is_enabled(),
'images': capabilities.CapabilitySet('images').is_enabled(),
'mail': capabilities.CapabilitySet('mail').is_enabled(),
'memcache': capabilities.CapabilitySet('memcache').is_enabled(),
'taskqueue': capabilities.CapabilitySet('taskqueue').is_enabled(),
'urlfetch': capabilities.CapabilitySet('urlfetch').is_enabled(),
}
t2 = time.time()
statuses['time'] = t2 - t1
return statuses
def send_error_to_admins(exception, handler, write_tmpl):
import settings # workaround. See https://github.com/renzon/zenwarch/issues/3
tb = traceback.format_exc()
errmsg = exception.message
logging.error(errmsg)
logging.error(tb)
write_tmpl("/templates/error.html")
appid = app_identity.get_application_id()
subject = 'ERROR in %s: [%s] %s' % (appid, handler.request.path, errmsg)
body = """
------------- request ------------
%s
----------------------------------
------------- GET params ---------
%s
----------------------------------
----------- POST params ----------
%s
----------------------------------
----------- traceback ------------
%s
----------------------------------
""" % (handler.request, handler.request.GET, handler.request.POST, tb)
body += 'API statuses = ' + json.dumps(get_apis_statuses(exception), indent=4)
mail.send_mail_to_admins(sender=settings.SENDER_EMAIL,
subject=subject,
body=body)
def execute(next_process, handler, dependencies, **kwargs):
try:
next_process(dependencies, **kwargs)
except PathNotFound, e:
handler.response.set_status(404)
send_error_to_admins(e, handler, dependencies['_write_tmpl'])
except BaseException, e:
handler.response.status_code = 400
send_error_to_admins(e, handler, dependencies['_write_tmpl']) | zenwarch | /zenwarch-2.1.2.tar.gz/zenwarch-2.1.2/zen/gae/middleware/email_errors.py | email_errors.py |
from zeo_utils.zeo_base import ZeoBase
from zeo_utils.prop_parser import PropParser
class Network(ZeoBase):
def __init__(self, network_exec_fp: str):
""" 初始化 zeo++ 软件路径
"""
super(Network, self).__init__()
self._network_exec_fp = self._get_abs_path(network_exec_fp)
def test(self):
""" 测试 zeo++ 软件是否可以正常使用
"""
print(self._get_command_res(self._network_exec_fp))
def calc_pore_diameter(self, cif_fp: str, need_log: bool = False) -> {}:
""" 计算孔径
原理是调用命令 ./network.exe -ha -res ***.cif
:param cif_fp: cif文件的路径,相对路径或绝对路径都行
:param need_log:
"""
cif_fp = self._get_abs_path(cif_fp)
pdm = self._get_command_res(f"{self._network_exec_fp} -ha -res {cif_fp}")
return PropParser.parse(pdm, need_log=need_log)
def calc_specific_surface_area(self, cif_fp: str, chan_radius: float, probe_radius: float, num_samples: int,
need_log: bool = False) -> {}:
""" 计算比表面积
原理是调用命令 ./network.exe -ha -sa chen_radius probe_radius num_sample ***.cif
:param cif_fp: cif文件的路径,相对路径或绝对路径都行
:param chan_radius: 用于探测材料内孔道空间可及性情况的探针分子半径(Å)
:param probe_radius: 用于计算比表面积的探针分子半径(Å)
:param num_samples: 在每个材料原子周围进行Monte Carlo抽样探测的次数
:param need_log:
"""
cif_fp = self._get_abs_path(cif_fp)
ssa = self._get_command_res(f"{self._network_exec_fp} -ha -sa {chan_radius} {probe_radius} "
f"{num_samples} {cif_fp}")
return PropParser.parse(ssa, need_log=need_log)
def calc_accessible_volume(self, cif_fp: str, chan_radius: float, probe_radius: float,
num_samples: int, need_log: bool = False) -> {}:
""" 计算可及孔体积
原理是调用命令 ./network.exe -ha -vol chen_radius probe_radius num_sample ***.cif
:param cif_fp: cif文件的路径,相对路径或绝对路径都行
:param chan_radius: 用于探测材料内孔道空间可及性情况的探针分子半径(Å)
:param probe_radius: 用于计算比表面积的探针分子半径(Å)
:param num_samples: 在每个材料原子周围进行Monte Carlo抽样探测的次数
:param need_log:
"""
cif_fp = self._get_abs_path(cif_fp)
av = self._get_command_res(f"{self._network_exec_fp} -ha -vol {chan_radius} {probe_radius} {num_samples} "
f"{cif_fp}")
return PropParser.parse(av, need_log=need_log)
def calc_pore_size_distribution(self, cif_fp: str, chan_radius: float, probe_radius: float, num_samples: int,
need_log: bool = False) -> {}:
""" 计算孔径分布
原理是调用命令 ./network.exe -ha -psd chen_radius probe_radius num_sample ***.cif
:param cif_fp: cif文件的路径,相对路径或绝对路径都行
:param chan_radius: 用于探测材料内孔道空间可及性情况的探针分子半径(Å)
:param probe_radius: 用于计算比表面积的探针分子半径(Å)
:param num_samples: 在每个材料原子周围进行Monte Carlo抽样探测的次数
:param need_log:
"""
cif_fp = self._get_abs_path(cif_fp)
psd = self._get_command_res(f"{self._network_exec_fp} -ha -psd {chan_radius} {probe_radius} "
f"{num_samples} {cif_fp}")
return PropParser.parse(psd, need_log=need_log)
if __name__ == "__main__":
print(Network('../example/network.exe').test())
pass | zeo-utils | /zeo_utils-0.0.4.tar.gz/zeo_utils-0.0.4/zeo_utils/network.py | network.py |
Introduction
============
.. image:: https://badge.fury.io/py/zeo_connector.png
:target: https://pypi.python.org/pypi/zeo_connector
.. image:: https://img.shields.io/pypi/dm/zeo_connector.svg
:target: https://pypi.python.org/pypi/zeo_connector
.. image:: https://img.shields.io/pypi/l/zeo_connector.svg
.. image:: https://img.shields.io/github/issues/Bystroushaak/zeo_connector.svg
:target: https://github.com/Bystroushaak/zeo_connector/issues
Wrappers, which make working with ZEO_ little bit nicer.
By default, you have to do a lot of stuff, like create connection to database, maintain it, synchronize it (or running asyncore loop), handle reconnects and so on. Classes defined in this project makes all this work for you at the background.
.. _ZEO: http://www.zodb.org/en/latest/documentation/guide/zeo.html
Documentation
-------------
This module defines three classes:
- ZEOWrapperPrototype
- ZEOConfWrapper
- ZEOWrapper
ZEOWrapperPrototype
+++++++++++++++++++
``ZEOWrapperPrototype`` contains methods and shared attributes, which may be used by derived classes.
You can pretty much ignore this class, unless you want to make your own connector.
ZEOConfWrapper
++++++++++++++
``ZEOConfWrapper`` may be used to create connection to ZEO from `XML configuration file <https://pypi.python.org/pypi/ZEO/4.2.0b1#configuring-clients>`_.
Lets say you have file ``/tests/data/zeo_client.conf``:
.. code-block:: python
<zeoclient>
server localhost:60985
</zeoclient>
You can now create the ``ZEOConfWrapper`` object:
.. code-block:: python
from zeo_connector import ZEOConfWrapper
db_obj = ZEOConfWrapper(
conf_path="/tests/data/zeo_client.conf",
project_key="Some project key",
)
and save the data to the database:
.. code-block:: python
import transaction
with transaction.manager:
db_obj["data"] = "some data"
String ``"some data"`` is now saved under ``db._connection.root()[project_key]["data"]`` path.
ZEOWrapper
++++++++++
``ZEOWrapper`` doesn't use XML configuration file, but direct server/port specification:
.. code-block:: python
from zeo_connector import ZEOWrapper
different_db_obj = ZEOWrapper(
server="localhost",
port=60985,
project_key="Some project key",
)
So you can retreive the data you stored into the database:
.. code-block:: python
import transaction
with transaction.manager:
print different_db_obj["data"]
Running the ZEO server
----------------------
The examples expects, that the ZEO server is running. To run the ZEO, look at the help page of the ``runzeo`` script which is part of the ZEO bundle. This script requires commandline or XML configuration.
You can generate the configuration files using provided ``zeo_connector_gen_defaults.py`` script, which is part of the `zeo_connector_defaults <https://github.com/Bystroushaak/zeo_connector_defaults>` package::
$ zeo_connector_gen_defaults.py --help
usage: zeo_connector_gen_defaults.py [-h] [-s SERVER] [-p PORT] [-C] [-S]
[PATH]
This program will create the default ZEO XML configuration files.
positional arguments:
PATH Path to the database on the server (used in server
configuration only.
optional arguments:
-h, --help show this help message and exit
-s SERVER, --server SERVER
Server url. Default: localhost
-p PORT, --port PORT Port of the server. Default: 60985
-C, --only-client Create only CLIENT configuration.
-S, --only-server Create only SERVER configuration
For example::
$ zeo_connector_gen_defaults.py /tmp
will create ``zeo.conf`` file with following content:
.. code-block:: xml
<zeo>
address localhost:60985
</zeo>
<filestorage>
path /tmp/storage.fs
</filestorage>
<eventlog>
level INFO
<logfile>
path /tmp/zeo.log
format %(asctime)s %(message)s
</logfile>
</eventlog>
and ``zeo_client.conf`` containing:
.. code-block:: xml
<zeoclient>
server localhost:60985
</zeoclient>
You can change the ports and address of the server using ``--server`` or ``--port`` arguments.
To run the ZEO with the server configuration file, run the following command::
runzeo -C zeo.conf
To run the client, you may use ``ZEOConfWrapper``, as was show above:
.. code-block:: python
from zeo_connector import ZEOConfWrapper
db_obj = ZEOConfWrapper(
conf_path="./zeo_client.conf",
project_key="Some project key",
)
Installation
------------
Module is `hosted at PYPI <https://pypi.python.org/pypi/zeo_connector>`_, and can be easily installed using `PIP`_::
sudo pip install zeo_connector
.. _PIP: http://en.wikipedia.org/wiki/Pip_%28package_manager%29
Source code
-----------
Project is released under the MIT license. Source code can be found at GitHub:
- https://github.com/Bystroushaak/zeo_connector
Unittests
---------
You can run the tests using provided ``run_tests.sh`` script, which can be found in the root of the project.
If you have any trouble, just add ``--pdb`` switch at the end of your ``run_tests.sh`` command like this: ``./run_tests.sh --pdb``. This will drop you to `PDB`_ shell.
.. _PDB: https://docs.python.org/2/library/pdb.html
Requirements
++++++++++++
This script expects that package pytest_ is installed. In case you don't have it yet, it can be easily installed using following command::
pip install --user pytest
or for all users::
sudo pip install pytest
.. _pytest: http://pytest.org/
Example
+++++++
::
$ ./run_tests.sh
============================= test session starts ==============================
platform linux2 -- Python 2.7.6 -- py-1.4.30 -- pytest-2.7.2
rootdir: /home/bystrousak/Plocha/Dropbox/c0d3z/python/libs/zeo_connector, inifile:
plugins: cov
collected 7 items
tests/test_zeo_connector.py .......
=========================== 7 passed in 7.08 seconds ===========================
| zeo_connector | /zeo_connector-0.4.8.tar.gz/zeo_connector-0.4.8/README.rst | README.rst |
Changelog
=========
0.4.8
-----
- ZEO version un-pinned. Will continue in https://github.com/zopefoundation/ZEO/issues/77
0.4.7
-----
- Pinned older version of ZEO.
0.4.6
-----
- Cleanup of metadata files.
0.4.0 - 0.4.5
-------------
- Added ``@retry_and_reset`` decorator for all internal dict-methods calls.
- Project key is now optional, so this object may be used to access the root of the database.
- Property ``ASYNCORE_RUNNING`` renamed to ``_ASYNCORE_RUNNING``.
- Implemented ``.pack()``.
- Added ``@transaction_manager``.
- Added ``examples/database_handler.py`` and tests.
- Added @wraps(fn) to decorators.
- Added requirement for zope.interface.
- Attempt to solve https://github.com/WebArchivCZ/WA-KAT/issues/86
0.3.0
-----
- Environment generator and other shared parts moved to https://github.com/Bystroushaak/zeo_connector_defaults
- README.rst improved, added more documentation and additional sections.
0.2.0
-----
- Added standard dict methods, like ``.__contains__()``, ``.__delitem__()``, ``.__iter__()`` and so on.
0.1.0
-----
- Project created.
| zeo_connector | /zeo_connector-0.4.8.tar.gz/zeo_connector-0.4.8/CHANGELOG.rst | CHANGELOG.rst |
Introduction
============
.. image:: https://badge.fury.io/py/zeo_connector_defaults.png
:target: https://pypi.python.org/pypi/zeo_connector_defaults
.. image:: https://img.shields.io/pypi/dm/zeo_connector_defaults.svg
:target: https://pypi.python.org/pypi/zeo_connector_defaults
.. image:: https://img.shields.io/pypi/l/zeo_connector_defaults.svg
.. image:: https://img.shields.io/github/issues/Bystroushaak/zeo_connector_defaults.svg
:target: https://github.com/Bystroushaak/zeo_connector_defaults/issues
Default configuration files and configuration file generator for zeo_connector_.
.. _zeo_connector: https://github.com/Bystroushaak/zeo_connector
Documentation
-------------
This project provides generators of the testing environment for the ZEO-related tests. It also provides generator, for the basic ZEO configuration files.
zeo_connector_gen_defaults.py
+++++++++++++++++++++++++++++
This script simplifies the process of generation of ZEO configuration files.
ZEO tests
+++++++++
Typically, when you test your program which is using the ZEO database, you need to generate the database files, then run new thread with ``runzeo`` program, do tests, cleanup and stop the thread.
This module provides two functions, which do exactly this:
- zeo_connector_defaults.generate_environment()
- zeo_connector_defaults.cleanup_environment()
generate_environment
^^^^^^^^^^^^^^^^^^^^
This function will create temporary directory in ``/tmp`` and copy template files for ZEO client and server into this directory. Then it starts new thread with ``runzeo`` program using the temporary server configuration file.
Names of the files may be resolved using ``tmp_context_name()`` function.
Note:
This function works best, if added to setup part of your test environment.
cleanup_environment
^^^^^^^^^^^^^^^^^^^
Function, which stops the running ``runzeo`` thread and delete all the temporary files.
Note:
This function works best, if added to setup part of your test environment.
Context functions
^^^^^^^^^^^^^^^^^
There is also two `temp environment access functions`:
- tmp_context_name()
- tmp_context()
Both of them take one `fn` argument and return name of the file (``tmp_context_name()``) or content of the file (``tmp_context()``) in context of random temporary directory.
For example:
.. code-block:: python
tmp_context_name("zeo_client.conf")
returns the absolute path to the file ``zeo_client.conf``, which may be for example ``/tmp/tmp1r5keh/zeo_client.conf``.
You may also call it without the arguments, which will return just the name of the temporary directory:
.. code-block:: python
tmp_context_name()
which should return something like ``/tmp/tmp1r5keh``.
Tests example
+++++++++++++
Here is the example how your test may look like:
.. code-block:: python
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import pytest
from zeo_connector_defaults import generate_environment
from zeo_connector_defaults import cleanup_environment
from zeo_connector_defaults import tmp_context_name
# Setup =======================================================================
def setup_module(module):
generate_environment()
def teardown_module(module):
cleanup_environment()
# Fixtures ====================================================================
@pytest.fixture
def zeo_conf_wrapper():
return ZEOConfWrapper(
conf_path=tmp_context_name("zeo_client.conf"),
...
# Tests =======================================================================
def test_something(zeo_conf_wrapper):
...
Installation
------------
Module is `hosted at PYPI <https://pypi.python.org/pypi/zeo_connector_defaults>`_, and can be easily installed using `PIP`_::
sudo pip install zeo_connector_defaults
.. _PIP: http://en.wikipedia.org/wiki/Pip_%28package_manager%29
Source code
-----------
Project is released under the MIT license. Source code can be found at GitHub:
- https://github.com/Bystroushaak/zeo_connector_defaults
| zeo_connector_defaults | /zeo_connector_defaults-0.2.2.tar.gz/zeo_connector_defaults-0.2.2/README.rst | README.rst |
import sys
import os.path
import argparse
from string import Template
dirname = os.path.dirname(__file__)
imported_files = os.path.join(dirname, "../src/")
sys.path.insert(0, os.path.abspath(imported_files))
from zeo_connector_defaults import _SERVER_CONF_PATH
from zeo_connector_defaults import _CLIENT_CONF_PATH
# Functions & classes =========================================================
def create_configuration(args):
with open(_SERVER_CONF_PATH) as f:
server_template = f.read()
with open(_CLIENT_CONF_PATH) as f:
client_template = f.read()
if not args.only_server:
client = Template(client_template).substitute(
server=args.server,
port=args.port,
)
with open(os.path.basename(_CLIENT_CONF_PATH), "w") as f:
f.write(client)
if not args.only_client:
server = Template(server_template).substitute(
server=args.server,
port=args.port,
path=args.path,
)
with open(os.path.basename(_SERVER_CONF_PATH), "w") as f:
f.write(server)
# Main program ================================================================
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="""This program will create the default ZEO XML
configuration files."""
)
parser.add_argument(
"-s",
"--server",
default="localhost",
help="Server url. Default: localhost"
)
parser.add_argument(
"-p",
"--port",
default=60985,
type=int,
help="Port of the server. Default: 60985"
)
parser.add_argument(
"path",
metavar="PATH",
nargs='?',
default="",
help="""Path to the database on the server (used in server
configuration only."""
)
parser.add_argument(
"-C",
"--only-client",
action="store_true",
help="Create only CLIENT configuration."
)
parser.add_argument(
"-S",
"--only-server",
action="store_true",
help="Create only SERVER configuration."
)
args = parser.parse_args()
if not args.only_client and not args.path:
sys.stderr.write(
"You have to specify path to the database on for the DB server.\n"
)
sys.exit(1)
if args.only_client and args.only_server:
sys.stderr.write(
"You can't have --only-client and --only-server together!\n"
)
sys.exit(1)
create_configuration(args) | zeo_connector_defaults | /zeo_connector_defaults-0.2.2.tar.gz/zeo_connector_defaults-0.2.2/bin/zeo_connector_gen_defaults.py | zeo_connector_gen_defaults.py |
import logging
import os
import platform
import shutil
import sys
import tempfile
import urllib2
import urlparse
import setuptools.archive_util
import zc.buildout
# mx.ODBC Connect Client version
VERSION = '1.0.1'
BASE_URL = 'http://downloads.egenix.com/python/egenix-mxodbc-connect-client-' + VERSION + '.'
EXTENSION = '.prebuilt.zip'
MXBASE_URL = 'http://downloads.egenix.com/python/egenix-mx-base-3.1.2.'
# Keyed on .python_version_tuple()[:2] + (.system(), .machine())
# (methods from the platform module, python version tuple as ints)
# not all of these have been tested
_urls = {
# Linux 32bit
(2, 1, 'Linux', 'i686'): 'linux-i686-py2.1',
(2, 2, 'Linux', 'i686'): 'linux-i686-py2.2',
(2, 3, 'Linux', 'i686'): 'linux-i686-py2.3',
(2, 4, 'Linux', 'i686'): 'linux-i686-py2.4',
(2, 5, 'Linux', 'i686'): 'linux-i686-py2.5',
# Linux 64bit
(2, 1, 'Linux', 'x86_64'): 'py2.1',
(2, 2, 'Linux', 'x86_64'): 'py2.2',
(2, 3, 'Linux', 'x86_64'): 'py2.3',
(2, 4, 'Linux', 'x86_64'): 'py2.4',
(2, 5, 'Linux', 'x86_64'): 'py2.5',
# Mac OSX (fat binaries)
(2, 3, 'Darwin', 'i386'): 'py2.3',
(2, 4, 'Darwin', 'i386'): 'py2.4',
(2, 5, 'Darwin', 'i386'): 'py2.5',
(2, 3, 'Darwin', 'Power Macintosh'): 'py2.3',
(2, 4, 'Darwin', 'Power Macintosh'): 'py2.4',
(2, 5, 'Darwin', 'Power Macintosh'): 'py2.5',
# Windows
(2, 1, 'Windows', ''): 'win32-py2.1',
(2, 2, 'Windows', ''): 'win32-py2.2',
(2, 3, 'Windows', ''): 'win32-py2.3',
(2, 4, 'Windows', ''): 'win32-py2.4',
(2, 5, 'Windows', ''): 'win32-py2.5',
# XXX Solaris and FreeBSD
}
# Unicode size
_ucs = (sys.maxunicode < 66000) and 'ucs2' or 'ucs4'
_key = tuple(map(int, platform.python_version_tuple()[:2])) + (
platform.system(), platform.machine())
try:
URL = '%s%s%s' % (BASE_URL, _urls[_key], EXTENSION)
URL = URL.replace('linux-i686-', '')
except KeyError:
# Cannot determine for this platform
URL = ''
try:
MXBASE_URL = '%s%s_%s%s' % (MXBASE_URL, _urls[_key], _ucs, EXTENSION)
except KeyError:
# Cannot determine for this platform
MXBASE_URL = ''
def system(c):
if os.system(c):
raise SystemError('Failed', c)
class Recipe(object):
def __init__(self, buildout, name, options):
self.logger = logging.getLogger(name)
self.buildout = buildout
self.name = name
self.options = options
options['location'] = os.path.join(
buildout['buildout']['parts-directory'], self.name)
buildout['buildout'].setdefault(
'download-directory',
os.path.join(buildout['buildout']['directory'], 'downloads'))
self.options.setdefault('url', URL)
self.options.setdefault('licenses-archive', 'mxodbc-licenses.zip')
self.options.setdefault('license-key', '')
def install(self):
location = self.options['location']
if not os.path.exists(location):
os.mkdir(location)
self._install_mxbase(location)
self._install_mxodbc(location)
#self._install_license(location)
return [location]
def update(self):
pass
def _install_mxbase(self, location):
fname = self._download(MXBASE_URL)
tmp = tempfile.mkdtemp('buildout-' + self.name)
dirname = os.path.splitext(os.path.basename(fname))[0]
package = os.path.join(tmp, dirname)
here = os.getcwd()
try:
self.logger.debug('Extracting mx.Base archive')
setuptools.archive_util.unpack_archive(fname, tmp)
os.chdir(package)
self.logger.debug('Installing mx.BASE into %s', location)
system('"%s" setup.py -q install'
' --install-purelib="%s" --install-platlib="%s"' % (
sys.executable, location, location))
finally:
os.chdir(here)
shutil.rmtree(tmp)
def _install_mxodbc(self, location):
url = self.options['url']
fname = self._download(url)
tmp = tempfile.mkdtemp('buildout-' + self.name)
basename = os.path.basename(fname)
package = os.path.join(tmp, os.path.splitext(basename)[0])
here = os.getcwd()
try:
self.logger.debug('Extracting mx.ODBC archive')
setuptools.archive_util.unpack_archive(fname, tmp)
os.chdir(package)
self.logger.debug('Installing mx.ODBC into %s', location)
system('"%s" setup.py -q build --skip install'
' --install-purelib="%s" --install-platlib="%s"' % (
sys.executable, location, location))
finally:
os.chdir(here)
shutil.rmtree(tmp)
def _download(self, url):
download_dir = self.buildout['buildout']['download-directory']
if not os.path.isdir(download_dir):
os.mkdir(download_dir)
self.options.created(download_dir)
urlpath = urlparse.urlparse(url)[2]
fname = os.path.join(download_dir, urlpath.split('/')[-1])
if not os.path.exists(fname):
self.logger.info('Downloading ' + url)
f = open(fname, 'wb')
try:
f.write(urllib2.urlopen(url).read())
except Exception, e:
os.remove(fname)
raise zc.buildout.UserError(
"Failed to download URL %s: %s" % (url, str(e)))
f.close()
return fname
def _install_license(self, location):
licenses_archive = os.path.join(
self.buildout['buildout']['directory'],
self.options['licenses-archive'])
license_key = self.options['license-key']
dest = os.path.join(location, 'mx', 'ODBCConnect')
tmp = tempfile.mkdtemp('buildout-' + self.name)
try:
setuptools.archive_util.unpack_archive(licenses_archive, tmp)
directories = [f for f in os.listdir(tmp)
if os.path.isdir(os.path.join(tmp, f))]
license_key = license_key or directories[0]
if not license_key in directories:
raise zc.buildout.UserError(
"License key not found: %s" % license_key)
self.logger.info('Installing mx.ODBC.ZopeDA license %s', license_key)
license_path = os.path.join(tmp, license_key)
shutil.copy(os.path.join(license_path, 'license.py'), dest)
shutil.copy(os.path.join(license_path, 'license.txt'), dest)
finally:
shutil.rmtree(tmp) | zeomega.recipe.mxodbcconnect | /zeomega.recipe.mxodbcconnect-0.3.tar.gz/zeomega.recipe.mxodbcconnect-0.3/src/zeomega/recipe/mxodbcconnect/__init__.py | __init__.py |
# zeoplusplus
Python wrapper for the [Zeo++ library](http://zeoplusplus.org). Based on the latest released version 0.3.
## Installation
### pip
TODO
### From source
```sh
git clone https://github.com/lauri-codes/zeoplusplus.git
cd zeoplusplus
pip install .
```
## Getting the C++ part ready for packaging
By default the package comes with pre-build Voro++ shared library and prebuilt
Cython binding code. If you however need to re-create them, the following
instructions will help
### Voro++
TODO: The pre-build Voro++ library seems to be causing problems on other
machines. It should be compiled as a part of the installation to avoid these
problems.
Voro++ currently requires a separate build step, which has to be performed
before attempting the Cython build. This is done by adding the `-fPIC` flag to
the file in `src/voro++/config.mk`, and then creating a library file with
```sh
cd src/voro++/src
make
```
This will create the voro++ shared library file in `src/voro++/src`, which is
then linked in the Cython build by adding
```sh
libdirs = ["src/voro++/src"]
libraries = ['voro++']
```
to the extension definitions.
### Cython
The cython wrapper definitions live inside src/zeoplusplus. These bindings can
be recreated by first setting `USE_CYTHON=True` in setup.py, and then
recreating the bindings with:
```sh
python setup.py build_ext --inplace --force
```
Remember to disable cython in `setup.py` afterwards by setting `USE_CYTHON=False`
in setup.py.
| zeoplusplus | /zeoplusplus-0.1.1.tar.gz/zeoplusplus-0.1.1/README.md | README.md |
from __future__ import annotations
import warnings
from types import TracebackType
from typing import Any, Callable, Dict, List, Optional, Type
from urllib.parse import urljoin
import httpx
from packaging.version import InvalidVersion, Version
from zep_python.document.client import DocumentClient
from zep_python.exceptions import APIError
from zep_python.memory.client import MemoryClient
from zep_python.memory.models import (
Memory,
MemorySearchPayload,
MemorySearchResult,
Session,
)
from zep_python.user.client import UserClient
API_BASE_PATH = "/api/v1"
API_TIMEOUT = 10
MINIMUM_SERVER_VERSION = "0.11.0"
class ZepClient:
"""
ZepClient class implementation.
Attributes
----------
base_url : str
The base URL of the API.
memory : MemoryClient
The client used for making Memory API requests.
document : DocumentClient
The client used for making Document API requests.
Methods
-------
get_memory(session_id: str, lastn: Optional[int] = None) -> List[Memory]:
Retrieve memory for the specified session. (Deprecated)
add_memory(session_id: str, memory_messages: Memory) -> str:
Add memory to the specified session. (Deprecated)
delete_memory(session_id: str) -> str:
Delete memory for the specified session. (Deprecated)
search_memory(session_id: str, search_payload: SearchPayload,
limit: Optional[int] = None) -> List[SearchResult]:
Search memory for the specified session. (Deprecated)
close() -> None:
Close the HTTP client.
"""
base_url: str
memory: MemoryClient
document: DocumentClient
user: UserClient
def __init__(self, base_url: str, api_key: Optional[str] = None) -> None:
"""
Initialize the ZepClient with the specified base URL.
Parameters
----------
base_url : str
The base URL of the API.
api_key : Optional[str]
The API key to use for authentication. (optional)
"""
headers: Dict[str, str] = {}
if api_key is not None:
headers["Authorization"] = f"Bearer {api_key}"
self.base_url = concat_url(base_url, API_BASE_PATH)
self.aclient = httpx.AsyncClient(
base_url=self.base_url, headers=headers, timeout=API_TIMEOUT
)
self.client = httpx.Client(
base_url=self.base_url, headers=headers, timeout=API_TIMEOUT
)
self._healthcheck(base_url)
self.memory = MemoryClient(self.aclient, self.client)
self.document = DocumentClient(self.aclient, self.client)
self.user = UserClient(self.aclient, self.client)
def _healthcheck(self, base_url: str) -> None:
"""
Check that the Zep server is running, the API URL is correct,
and that the server version is compatible with this client.
Raises
------
ConnectionError
If the server is not running or the API URL is incorrect.
"""
url = concat_url(base_url, "/healthz")
error_msg = """Failed to connect to Zep server. Please check that:
- the server is running
- the API URL is correct
- No other process is using the same port
"""
try:
response = httpx.get(url)
if response.status_code != 200 or response.text != ".":
raise APIError(response, error_msg)
zep_server_version_str = response.headers.get("X-Zep-Version")
if zep_server_version_str:
if "dev" in zep_server_version_str:
return
zep_server_version = parse_version_string(zep_server_version_str)
else:
zep_server_version = Version("0.0.0")
if zep_server_version < Version(MINIMUM_SERVER_VERSION):
warnings.warn(
(
"You are using an incompatible Zep server version. Please"
" upgrade to {MINIMUM_SERVER_VERSION} or later."
),
Warning,
stacklevel=2,
)
except (httpx.ConnectError, httpx.NetworkError, httpx.TimeoutException) as e:
raise APIError(None, error_msg) from e
async def __aenter__(self) -> "ZepClient":
"""Asynchronous context manager entry point"""
return self
async def __aexit__(
self,
exc_type: Type[Exception],
exc_val: Exception,
exc_tb: TracebackType,
) -> None:
"""Asynchronous context manager exit point"""
await self.aclose()
def __enter__(self) -> "ZepClient":
"""Sync context manager entry point"""
return self
def __exit__(
self,
exc_type: Type[Exception],
exc_val: Exception,
exc_tb: TracebackType,
) -> None:
"""Sync context manager exit point"""
self.close()
# Facade methods for Memory API
def get_session(self, session_id: str) -> Session:
deprecated_warning(self.get_session)
return self.memory.get_session(session_id)
async def aget_session(self, session_id: str) -> Session:
deprecated_warning(self.aget_session)
return await self.memory.aget_session(session_id)
def add_session(self, session: Session) -> Session:
deprecated_warning(self.add_session)
return self.memory.add_session(session)
async def aadd_session(self, session: Session) -> Session:
deprecated_warning(self.aadd_session)
return await self.memory.aadd_session(session)
def get_memory(self, session_id: str, lastn: Optional[int] = None) -> Memory:
deprecated_warning(self.get_memory)
return self.memory.get_memory(session_id, lastn)
async def aget_memory(self, session_id: str, lastn: Optional[int] = None) -> Memory:
deprecated_warning(self.aget_memory)
return await self.memory.aget_memory(session_id, lastn)
def add_memory(self, session_id: str, memory_messages: Memory) -> str:
deprecated_warning(self.add_memory)
return self.memory.add_memory(session_id, memory_messages)
async def aadd_memory(self, session_id: str, memory_messages: Memory) -> str:
deprecated_warning(self.aadd_memory)
return await self.memory.aadd_memory(session_id, memory_messages)
def delete_memory(self, session_id: str) -> str:
deprecated_warning(self.delete_memory)
return self.memory.delete_memory(session_id)
async def adelete_memory(self, session_id: str) -> str:
deprecated_warning(self.adelete_memory)
return await self.memory.adelete_memory(session_id)
def search_memory(
self,
session_id: str,
search_payload: MemorySearchPayload,
limit: Optional[int] = None,
) -> List[MemorySearchResult]:
deprecated_warning(self.search_memory)
return self.memory.search_memory(session_id, search_payload, limit)
async def asearch_memory(
self,
session_id: str,
search_payload: MemorySearchPayload,
limit: Optional[int] = None,
) -> List[MemorySearchResult]:
deprecated_warning(self.asearch_memory)
return await self.memory.asearch_memory(session_id, search_payload, limit)
# Close the HTTP client
async def aclose(self) -> None:
"""
Asynchronously close the HTTP client.
[Optional] This method may be called when the ZepClient is no longer needed to
release resources.
"""
await self.aclient.aclose()
def close(self) -> None:
"""
Close the HTTP client.
[Optional] This method may be called when the ZepClient is no longer needed to
release resources.
"""
self.client.close()
def concat_url(base_url: str, path: str) -> str:
"""
Join the specified base URL and path.
Parameters
----------
base_url : str
The base URL to join.
path : str
The path to join.
Returns
-------
str
The joined URL.
"""
base_url = base_url.rstrip("/")
return urljoin(base_url + "/", path.lstrip("/"))
def deprecated_warning(func: Callable[..., Any]) -> Callable[..., Any]:
warnings.warn(
(
f"{func.__name__} method from the base client path is deprecated, "
"please use the corresponding method from zep_python.memory instead"
),
DeprecationWarning,
stacklevel=3,
)
return func
def parse_version_string(version_string: str) -> Version:
"""
Parse a string into a Version object.
Parameters
----------
version_string : str
The version string to parse.
Returns
-------
Version
The parsed version.
"""
try:
if "-" in version_string:
version_str = version_string.split("-")[0]
return Version(version_str if version_str else "0.0.0")
except InvalidVersion:
return Version("0.0.0")
return Version("0.0.0") | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/zep_client.py | zep_client.py |
from __future__ import annotations
from typing import Any, Dict, Optional, Union
import httpx
class ZepClientError(Exception):
"""
Base exception class for ZepClient errors.
Attributes
----------
message : str
The error message associated with the ZepClient error.
response_data : Optional[dict]
The response data associated with the ZepClient error.
Parameters
----------
message : str
The error message to be set for the exception.
response_data : Optional[dict], optional
The response data to be set for the exception, by default None.
"""
def __init__(
self, message: str, response_data: Optional[Dict[Any, Any]] = None
) -> None:
super().__init__(message)
self.message = message
self.response_data = response_data
def __str__(self):
return f"{self.message}: {self.response_data}"
class APIError(ZepClientError):
"""
Raised when the API response format is unexpected.
Inherits from ZepClientError.
"""
def __init__(
self, response: Union[httpx.Response, None] = None, message: str = "API error"
) -> None:
if response:
response_data = {
"status_code": response.status_code,
"message": response.text,
}
else:
response_data = None
super().__init__(message=message, response_data=response_data)
class AuthError(ZepClientError):
"""
Raised when API authentication fails.
Inherits from APIError.
"""
def __init__(
self,
response: Union[httpx.Response, None] = None,
message: str = "Authentication error",
) -> None:
if response:
response_data = {
"status_code": response.status_code,
"message": response.text,
}
else:
response_data = None
super().__init__(message=message, response_data=response_data)
class NotFoundError(ZepClientError):
"""
Raised when the API response contains no results.
Inherits from ZepClientError.
"""
def __init__(self, message: str) -> None:
super().__init__(message)
def handle_response(
response: httpx.Response, missing_doc: Optional[str] = None
) -> None:
missing_doc = missing_doc or "No query results found"
if response.status_code == 404:
raise NotFoundError(missing_doc)
if response.status_code == 401:
raise AuthError(response)
if not (200 <= response.status_code <= 299):
raise APIError(response) | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/exceptions.py | exceptions.py |
from __future__ import annotations
import warnings
from typing import (
Any,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base import VectorStore
from langchain.vectorstores.utils import maximal_marginal_relevance # type: ignore
from zep_python.document import Document as ZepDocument
from zep_python.document import DocumentCollection
class ZepVectorStore(VectorStore):
def __init__(
self,
collection: DocumentCollection,
texts: Optional[List[str]] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
embedding: Optional[Embeddings] = None,
**kwargs: Any,
) -> None:
warnings.warn(
(
"This experimental class has been deprecated. Please use the "
"official ZepVectorStore class in the Langchain package."
),
DeprecationWarning,
stacklevel=2,
)
if not isinstance(collection, DocumentCollection): # type: ignore
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
self._collection: Optional[DocumentCollection] = collection
self._texts: Optional[List[str]] = texts
self._embedding: Optional[Embeddings] = embedding
if self._texts is not None:
self.add_texts(self._texts, metadatas=metadata, **kwargs)
def _generate_documents_to_add(
self,
texts: Iterable[str],
metadatas: Optional[List[Dict[Any, Any]]] = None,
document_ids: Optional[List[str]] = None,
):
if (
self._collection
and self._collection.is_auto_embedded
and self._embedding is not None
):
warnings.warn(
"""The collection is set to auto-embed and an embedding
function is present. Ignoring the embedding function.""",
stacklevel=2,
)
self._embedding = None
embeddings = None
if self._embedding is not None:
embeddings = self._embedding.embed_documents(list(texts))
if self._collection and self._collection.embedding_dimensions != len(
embeddings[0]
):
raise ValueError(
"The embedding dimensions of the collection and the embedding"
" function do not match. Collection dimensions:"
f" {self._collection.embedding_dimensions}, Embedding dimensions:"
f" {len(embeddings[0])}"
)
documents: List[ZepDocument] = []
for i, d in enumerate(texts):
documents.append(
ZepDocument(
content=d,
metadata=metadatas[i] if metadatas else None,
document_id=document_ids[i] if document_ids else None,
embedding=embeddings[i] if embeddings else None,
)
)
return documents
def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[Dict[str, Any]]] = None,
document_ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
document_ids: Optional list of document ids associated with the texts.
kwargs: vectorstore specific parameters
Returns:
List of ids from adding the texts into the vectorstore.
"""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
documents = self._generate_documents_to_add(texts, metadatas, document_ids)
uuids = self._collection.add_documents(documents)
return uuids
async def aadd_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[Dict[str, Any]]] = None,
document_ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore."""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
documents = self._generate_documents_to_add(texts, metadatas, document_ids)
uuids = await self._collection.aadd_documents(documents)
return uuids
def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:
"""Run more documents through the embeddings and add to the vectorstore.
Args:
documents List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of UUIDs of the added texts.
"""
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents] # type: ignore
return self.add_texts(texts, metadatas, **kwargs) # type: ignore
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Run more documents through the embeddings and add to the vectorstore.
Args:
documents List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of UUIDs of the added texts.
"""
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents] # type: ignore
return await self.aadd_texts(texts, metadatas, **kwargs) # type: ignore
def search(
self,
query: str,
search_type: str,
metadata: Optional[Dict[str, Any]] = None,
k: int = 4,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return self.similarity_search(query, k, metadata, **kwargs)
elif search_type == "mmr":
return self.max_marginal_relevance_search(
query, k, metadata=metadata, **kwargs
)
else:
raise ValueError(
f"search_type of {search_type} not allowed. Expected "
"search_type to be 'similarity' or 'mmr'."
)
async def asearch(
self,
query: str,
search_type: str,
metadata: Optional[Dict[str, Any]] = None,
k: int = 5,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return await self.asimilarity_search(query, k, metadata, **kwargs)
elif search_type == "mmr":
return await self.amax_marginal_relevance_search(
query, k, metadata=metadata, **kwargs
)
else:
raise ValueError(
f"search_type of {search_type} not allowed. Expected "
"search_type to be 'similarity' or 'mmr'."
)
def similarity_search(
self,
query: str,
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query."""
results = self._similarity_search_with_relevance_scores(
query, k, metadata=metadata, **kwargs
)
return [doc for doc, _ in results]
def similarity_search_with_score( # type: ignore
self,
query: str,
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
*args: Any,
**kwargs: Any,
) -> List[Tuple[Document, Optional[float]]]:
"""Run similarity search with distance."""
return self._similarity_search_with_relevance_scores(
query, k, metadata=metadata, **kwargs
)
def _similarity_search_with_relevance_scores( # type: ignore
self,
query: str,
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Tuple[Document, Optional[float]]]:
"""
Default similarity search with relevance scores. Modify if necessary
in subclass.
Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Args:
query: input text
k: Number of Documents to return. Defaults to 4.
metadata: Optional, metadata filter
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 and
filter the resulting set of retrieved docs
Returns:
List of Tuples of (doc, similarity_score)
"""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
if self._embedding:
query_vector = self._embedding.embed_query(query)
results = self._collection.search(
embedding=query_vector, limit=k, metadata=metadata, **kwargs
)
else:
results = self._collection.search(
query, limit=k, metadata=metadata, **kwargs
)
return [
(
Document(
page_content=doc.content,
metadata=doc.metadata, # type: ignore
),
doc.score,
)
for doc in results
]
async def asimilarity_search_with_relevance_scores( # type: ignore
self,
query: str,
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Tuple[Document, Optional[float]]]:
"""Return docs most similar to query."""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
if self._embedding:
query_vector = self._embedding.embed_query(query)
results = await self._collection.asearch(
embedding=query_vector, limit=k, metadata=metadata, **kwargs
)
else:
results = await self._collection.asearch(
query, limit=k, metadata=metadata, **kwargs
)
return [
(
Document(
page_content=doc.content,
metadata=doc.metadata, # type: ignore
),
doc.score,
)
for doc in results
]
async def asimilarity_search(
self,
query: str,
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query."""
results = await self.asimilarity_search_with_relevance_scores(
query, k, metadata=metadata, **kwargs
)
return [doc for doc, _ in results]
def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
metadata: Optional, metadata filter
Returns:
List of Documents most similar to the query vector.
"""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
results = self._collection.search(
embedding=embedding, limit=k, metadata=metadata, **kwargs
)
return [
Document(
page_content=doc.content,
metadata=doc.metadata, # type: ignore
)
for doc in results
]
async def asimilarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector."""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
results = self._collection.search(
embedding=embedding, limit=k, metadata=metadata, **kwargs
)
return [
Document(
page_content=doc.content,
metadata=doc.metadata, # type: ignore
)
for doc in results
]
def _max_marginal_relevance_selection(
self,
query_vector: List[float],
results: List[ZepDocument],
k: int = 4,
lambda_mult: float = 0.5,
) -> List[Document]:
mmr_selected = maximal_marginal_relevance(
np.array([query_vector], dtype=np.float32),
[d.embedding for d in results],
k=k,
lambda_mult=lambda_mult,
)
selected = [results[i] for i in mmr_selected]
return [
Document(page_content=d.content, metadata=d.metadata) # type: ignore
for d in selected
]
def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
metadata: Optional, metadata to filter the resulting set of retrieved docs
Returns:
List of Documents selected by maximal marginal relevance.
"""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
if self._embedding:
query_vector = self._embedding.embed_query(query)
results = self._collection.search(
embedding=query_vector, limit=k, metadata=metadata, **kwargs
)
else:
results, query_vector = self._collection.search_return_query_vector(
query, limit=k, metadata=metadata, **kwargs
)
return self._max_marginal_relevance_selection(
query_vector, results, k=k, lambda_mult=lambda_mult
)
async def amax_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
if self._embedding:
query_vector = self._embedding.embed_query(query)
results = await self._collection.asearch(
embedding=query_vector, limit=k, metadata=metadata, **kwargs
)
else:
results, query_vector = await self._collection.asearch_return_query_vector(
query, limit=k, metadata=metadata, **kwargs
)
return self._max_marginal_relevance_selection(
query_vector, results, k=k, lambda_mult=lambda_mult
)
def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
metadata: Optional, metadata to filter the resulting set of retrieved docs
Returns:
List of Documents selected by maximal marginal relevance.
"""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
results = self._collection.search(
embedding=embedding, limit=k, metadata=metadata, **kwargs
)
return self._max_marginal_relevance_selection(
embedding, results, k=k, lambda_mult=lambda_mult
)
async def amax_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
if not isinstance(self._collection, DocumentCollection):
raise ValueError(
"collection should be an instance of a Zep DocumentCollection"
)
results = await self._collection.asearch(
embedding=embedding, limit=k, metadata=metadata, **kwargs
)
return self._max_marginal_relevance_selection(
embedding, results, k=k, lambda_mult=lambda_mult
)
@classmethod
def from_texts( # type: ignore
cls: Type[ZepVectorStore],
texts: List[str],
collection: DocumentCollection,
embedding: Optional[Embeddings] = None,
metadatas: Optional[List[Dict[str, Any]]] = None,
**kwargs: Any,
) -> ZepVectorStore:
"""Return VectorStore initialized from texts and embeddings."""
return cls(
collection=collection, texts=texts, embedding=embedding, metadata=metadatas
)
@property
def embeddings(self) -> Optional[Embeddings]:
return self._embedding
def delete( # type: ignore
self, uuids: Optional[List[str]] = None, **kwargs: Any
) -> None:
"""Delete by Zep vector UUIDs.
Parameters
----------
uuids : Optional[List[str]]
The UUIDs of the vectors to delete.
Raises
------
ValueError
If no UUIDs are provided.
"""
if uuids is None or len(uuids) == 0:
raise ValueError("No uuids provided to delete.")
if self._collection is None:
raise ValueError("No collection name provided.")
for u in uuids:
self._collection.delete_document(u) | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/experimental/langchain/zep_vectorstore.py | zep_vectorstore.py |
from __future__ import annotations
from typing import Any, Dict, List, Optional
import httpx
from zep_python.exceptions import handle_response
from zep_python.utils import filter_dict
from .collections import DocumentCollection
class DocumentClient:
"""
This class implements Zep's document APIs.
Attributes:
client (httpx.Client): Synchronous API client.
aclient (httpx.AsyncClient): Asynchronous API client.
Methods:
aadd_collection(name: str, embedding_dimensions: int,
description: Optional[str] = "",
metadata: Optional[Dict[str, Any]] = None,
is_auto_embedded: bool = True) -> DocumentCollection:
Asynchronously creates a collection.
add_collection(name: str, embedding_dimensions: int,
description: Optional[str] = "",
metadata: Optional[Dict[str, Any]] = None,
is_auto_embedded: bool = True) -> DocumentCollection:
Synchronously creates a collection.
aupdate_collection(name: str, description: Optional[str] = "",
metadata: Optional[Dict[str, Any]] = None
) -> DocumentCollection:
Asynchronously updates a collection.
update(name: str, description: Optional[str] = "",
metadata: Optional[Dict[str, Any]] = None) -> DocumentCollection:
Synchronously updates a collection.
adelete_collection(collection_name: str) -> str:
Asynchronously deletes a collection.
delete_collection(collection_name: str) -> str:
Synchronously deletes a collection.
aget_collection(collection_name: str) -> DocumentCollection:
Asynchronously retrieves a collection.
get_collection(collection_name: str) -> DocumentCollection:
Synchronously retrieves a collection.
alist_collections() -> List[DocumentCollection]:
Asynchronously retrieves all collections.
list_collections() -> List[DocumentCollection]:
Synchronously retrieves all collections.
"""
def __init__(self, aclient: httpx.AsyncClient, client: httpx.Client) -> None:
"""
Initialize the DocumentClient with the specified httpx clients.
"""
self.aclient = aclient
self.client = client
async def aadd_collection(
self,
name: str,
embedding_dimensions: int,
description: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
is_auto_embedded: bool = True,
) -> DocumentCollection:
"""
Asynchronously creates a collection.
Parameters
----------
name : str
The name of the collection to be created.
description: str
The description of the collection to be created.
embedding_dimensions : int
The number of dimensions of the embeddings to use for documents
in this collection. This must match your model's embedding dimensions.
metadata : Optional[Dict[str, Any]], optional
A dictionary of metadata to be associated with the collection,
by default None.
is_auto_embedded : bool, optional
Whether the collection is automatically embedded, by default True.
Returns
-------
DocumentCollection
The newly created collection object, retrieved from the server.
Raises
------
APIError
If the API response format is unexpected, or if the server returns an error.
"""
if embedding_dimensions is None or embedding_dimensions <= 0:
raise ValueError("embedding_dimensions must be a positive integer")
collection = DocumentCollection(
name=name,
description=description,
embedding_dimensions=embedding_dimensions,
metadata=metadata,
is_auto_embedded=is_auto_embedded,
)
response = await self.aclient.post(
f"/collection/{name}",
json=collection.dict(exclude_none=True),
)
handle_response(response)
return await self.aget_collection(collection.name)
def add_collection(
self,
name: str,
embedding_dimensions: int,
description: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
is_auto_embedded: bool = True,
) -> DocumentCollection:
"""
Creates a collection.
Parameters
----------
name : str
The name of the collection to be created.
description: str
The description of the collection to be created.
embedding_dimensions : int
The number of dimensions of the embeddings to use for documents
in this collection. This must match your model's embedding dimensions.
metadata : Optional[Dict[str, Any]], optional
A dictionary of metadata to be associated with the collection,
by default None.
is_auto_embedded : bool, optional
Whether the collection is automatically embedded, by default True.
Returns
-------
DocumentCollection
The newly created collection object, retrieved from the server.
Raises
------
APIError
If the API response format is unexpected, or if the server returns an error.
AuthError
If the API key is invalid.
"""
collection = DocumentCollection(
name=name,
description=description,
embedding_dimensions=embedding_dimensions,
metadata=metadata,
is_auto_embedded=is_auto_embedded,
)
response = self.client.post(
f"/collection/{name}",
json=collection.dict(exclude_none=True),
)
handle_response(response)
return self.get_collection(collection.name)
# Document Collection APIs : Get a document collection
async def aget_collection(self, name: str) -> DocumentCollection:
"""
Asynchronously retrieves a collection.
Parameters
----------
name : str
Collection name.
Returns
-------
DocumentCollection
Retrieved collection.
Raises
------
ValueError
If no collection name is provided.
NotFoundError
If collection not found.
APIError
If API response is unexpected.
AuthError
If the API key is invalid.
"""
if name is None or name.strip() == "":
raise ValueError("collection name must be provided")
response = await self.aclient.get(
f"/collection/{name}",
)
handle_response(response)
filtered_response = filter_dict(response.json())
return DocumentCollection(
client=self.client, aclient=self.aclient, **filtered_response
)
def get_collection(self, name: str) -> DocumentCollection:
"""
Retrieves a collection.
Parameters
----------
name : str
Collection name.
Returns
-------
DocumentCollection
Retrieved collection.
Raises
------
ValueError
If no collection name is provided.
NotFoundError
If collection not found.
APIError
If API response is unexpected.
AuthError
If the API key is invalid.
"""
if name is None or name.strip() == "":
raise ValueError("collection name must be provided")
response = self.client.get(
f"/collection/{name}",
)
handle_response(response)
filtered_response = filter_dict(response.json())
return DocumentCollection(
client=self.client, aclient=self.aclient, **filtered_response
)
async def aupdate_collection(
self,
name: str,
description: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> DocumentCollection:
"""
Asynchronously updates a collection.
Parameters
----------
name : str
Collection name.
description: Optional[str], optional
Collection description.
metadata : Optional[Dict[str, Any]], optional
A dictionary of metadata to be associated with the collection.
Returns
-------
DocumentCollection
Updated collection.
Raises
------
NotFoundError
If collection not found.
APIError
If API response is unexpected.
AuthError
If the API key is invalid.
"""
collection = DocumentCollection(
name=name,
description=description,
metadata=metadata,
)
response = await self.aclient.patch(
f"/collection/{collection.name}",
json=collection.dict(exclude_none=True),
)
handle_response(response)
return await self.aget_collection(collection.name)
def update_collection(
self,
name: str,
description: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> DocumentCollection:
"""
Updates a collection.
Parameters
----------
name : str
Collection name.
description: Optional[str], optional
Collection description.
metadata : Optional[Dict[str, Any]], optional
A dictionary of metadata to be associated with the collection.
Returns
-------
DocumentCollection
Updated collection.
Raises
------
NotFoundError
If collection not found.
APIError
If API response is unexpected.
AuthError
If the API key is invalid.
"""
collection = DocumentCollection(
name=name,
description=description,
metadata=metadata,
)
response = self.client.patch(
f"/collection/{collection.name}",
json=collection.dict(exclude_none=True),
)
handle_response(response)
return self.get_collection(collection.name)
async def alist_collections(self) -> List[DocumentCollection]:
"""
Asynchronously lists all collections.
Returns
-------
List[DocumentCollection]
The list of document collection objects.
Raises
------
APIError
If the API response format is unexpected.
AuthError
If the API key is invalid.
"""
response = await self.aclient.get(
"/collection",
)
handle_response(response)
return [DocumentCollection(**collection) for collection in response.json()]
def list_collections(self) -> List[DocumentCollection]:
"""
Lists all collections.
Returns
-------
List[DocumentCollection]
The list of document collection objects.
Raises
------
APIError
If the API response format is unexpected.
AuthError
If the API key is invalid.
"""
response = self.client.get(
"/collection",
)
handle_response(response)
return [DocumentCollection(**collection) for collection in response.json()]
async def adelete_collection(self, collection_name: str) -> None:
"""
Asynchronously delete a collection.
Parameters
----------
collection_name : str
The name of the collection to delete.
Returns
-------
None
Raises
------
NotFoundError
If the collection is not found.
APIError
If the API response format is unexpected.
AuthError
If the API key is invalid.
"""
if collection_name is None or collection_name.strip() == "":
raise ValueError("collection name must be provided")
response = await self.aclient.delete(
f"/collection/{collection_name}",
)
handle_response(response)
def delete_collection(self, collection_name: str) -> None:
"""
Deletes a collection.
Parameters
----------
collection_name : str
The name of the collection to delete.
Returns
-------
None
Raises
------
NotFoundError
If the collection is not found.
APIError
If the API response format is unexpected.
AuthError
If the API key is invalid.
"""
if collection_name is None or collection_name.strip() == "":
raise ValueError("collection name must be provided")
response = self.client.delete(
f"/collection/{collection_name}",
)
handle_response(response) | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/document/client.py | client.py |
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Optional
if TYPE_CHECKING:
from pydantic import BaseModel, Extra, Field
else:
try:
from pydantic.v1 import BaseModel, Extra, Field
except ImportError:
from pydantic import BaseModel, Extra, Field
class Document(BaseModel):
"""
Represents a document base.
Attributes
----------
uuid : Optional[str]
The unique identifier of the document.
created_at : Optional[datetime]
The timestamp of when the document was created.
updated_at : Optional[datetime]
The timestamp of when the document was last updated.
document_id : Optional[str]
The unique identifier of the document (name or some id).
content : str
The content of the document.
metadata : Optional[Dict[str, Any]]
Any additional metadata associated with the document.
is_embedded : Optional[bool]
Whether the document has an embedding.
embedding : Optional[List[float]]
The embedding of the document.
score : Optional[float]
The normed score of the search result. Available only
when the document is returned as part of a query result.
"""
uuid: Optional[str] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
document_id: Optional[str] = Field(default=None, max_length=100)
content: str = Field(..., min_length=1)
metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)
is_embedded: Optional[bool] = None
embedding: Optional[List[float]] = None
score: Optional[float] = None
def to_dict(self) -> Dict[str, Any]:
"""
Returns a dictionary representation of the document.
Returns
-------
Dict[str, Any]
A dictionary containing the attributes of the document.
"""
return self.dict()
class DocumentCollectionModel(BaseModel):
"""
Represents a collection of documents.
Attributes
----------
uuid : str
The unique identifier of the collection.
created_at : Optional[datetime]
The timestamp of when the collection was created.
updated_at : Optional[datetime]
The timestamp of when the collection was last updated.
name : str
The unique name of the collection.
description : Optional[str]
The description of the collection.
metadata : Optional[Dict[str, Any]]
Any additional metadata associated with the collection.
embedding_dimensions : int
The dimensions of the embedding model.
is_auto_embedded : bool
Flag to indicate whether the documents in the collection should be
automatically embedded by Zep. (Default: True)
is_indexed : bool
Flag indicating whether an index has been created for this collection.
"""
uuid: Optional[str] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
name: str = Field(
...,
min_length=5,
max_length=40,
regex="^[a-zA-Z0-9_-]*$",
)
description: Optional[str] = Field(default=None, max_length=1000)
metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)
embedding_dimensions: Optional[int] = Field(ge=8, le=2000, default=None)
is_auto_embedded: Optional[bool] = True
is_indexed: Optional[bool] = None
document_count: Optional[int] = None
document_embedded_count: Optional[int] = None
is_normalized: Optional[bool] = None
class Config:
extra = Extra.forbid
def to_dict(self) -> Dict[str, Any]:
"""
Returns a dictionary representation of the document collection.
Returns
-------
Dict[str, Any]
A dictionary containing the attributes of the document collection.
"""
return self.dict() | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/document/models.py | models.py |
import warnings
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import httpx
if TYPE_CHECKING:
from pydantic import PrivateAttr
else:
try:
from pydantic.v1 import PrivateAttr
except ImportError:
from pydantic import PrivateAttr
from zep_python.exceptions import handle_response
from zep_python.utils import filter_dict
from .models import Document, DocumentCollectionModel
MIN_DOCS_TO_INDEX = 10_000
LARGE_BATCH_WARNING_LIMIT = 1000
LARGE_BATCH_WARNING = (
f"Batch size is greater than {LARGE_BATCH_WARNING_LIMIT}. "
"This may result in slow performance or out-of-memory failures."
)
class DocumentCollection(DocumentCollectionModel):
__doc__ = DocumentCollectionModel.__doc__ or ""
_client: Optional[httpx.Client] = PrivateAttr(default=None)
_aclient: Optional[httpx.AsyncClient] = PrivateAttr(default=None)
def __init__(
self,
aclient: Optional[httpx.AsyncClient] = None,
client: Optional[httpx.Client] = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self._aclient = aclient
self._client = client
@property
def status(self) -> str:
"""
Get the status of the collection.
Returns
-------
str
The status of the collection.
`ready`: All documents have been embedded and the collection is ready for
search.
`pending`: The collection is still processing.
"""
if self.document_count and (
self.document_embedded_count == self.document_count
):
return "ready"
else:
return "pending"
async def aadd_documents(self, documents: List[Document]) -> List[str]:
"""
Asynchronously create documents.
documents : List[Document]
A list of Document objects representing the documents to create.
Returns
-------
List[str]
The UUIDs of the created documents.
Raises
------
APIError
If the API response format is unexpected.
"""
if not self._aclient:
raise ValueError(
"Can only add documents once a collection has been created"
)
if documents is None:
raise ValueError("document list must be provided")
documents_dicts = [document.dict(exclude_none=True) for document in documents]
response = await self._aclient.post(
f"/collection/{self.name}/document",
json=documents_dicts,
)
handle_response(response)
return response.json()
def add_documents(self, documents: List[Document]) -> List[str]:
"""
Create documents.
documents : List[Document]
A list of Document objects representing the documents to create.
Returns
-------
List[str]
The UUIDs of the created documents.
Raises
------
APIError
If the API response format is unexpected.
"""
if not self._client:
raise ValueError(
"Can only add documents once a collection has been created"
)
if documents is None:
raise ValueError("document list must be provided")
documents_dicts = [document.dict(exclude_none=True) for document in documents]
response = self._client.post(
f"/collection/{self.name}/document",
json=documents_dicts,
)
handle_response(response)
return response.json()
async def aupdate_document(
self,
uuid: str,
description: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""
Asynchronously update document by UUID.
Parameters
----------
uuid : str
The UUID of the document to update.
description : Optional[str]
The description of the document.
metadata : Optional[Dict[str, Any]]
The metadata of the document.
Returns
-------
None
Raises
------
NotFoundError
If the document is not found.
APIError
If the API response format is unexpected.
"""
if not self._aclient:
raise ValueError(
"Can only update documents once a collection has been retrieved or"
" created"
)
if uuid is None:
raise ValueError("document uuid must be provided")
if description is None and metadata is None:
raise ValueError("description or metadata must be provided")
payload = filter_dict({"description": description, "metadata": metadata})
response = await self._aclient.patch(
f"/collection/{self.name}/document/uuid/{uuid}",
json=payload,
)
handle_response(response)
def update_document(
self,
uuid: str,
document_id: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""
Update document by UUID.
Parameters
----------
uuid : str
The UUID of the document to update.
document_id : Optional[str]
The document_id of the document.
metadata : Optional[Dict[str, Any]]
The metadata of the document.
Returns
-------
None
Raises
------
NotFoundError
If the document is not found.
APIError
If the API response format is unexpected.
"""
if not self._client:
raise ValueError(
"Can only update documents once a collection has been retrieved or"
" created"
)
if uuid is None:
raise ValueError("document uuid must be provided")
if document_id is None and metadata is None:
raise ValueError("document_id or metadata must be provided")
payload = filter_dict({"document_id": document_id, "metadata": metadata})
response = self._client.patch(
f"/collection/{self.name}/document/uuid/{uuid}",
json=payload,
)
handle_response(response)
async def adelete_document(self, uuid: str) -> None:
"""
Asynchronously delete document.
Parameters
----------
uuid: str
The uuid of the document to be deleted.
Returns
-------
None
Raises
------
NotFoundError
If the document is not found.
APIError
If the API response format is unexpected.
"""
if not self._aclient:
raise ValueError(
"Can only delete a document once a collection has been retrieved"
)
if uuid is None or uuid.strip() == "":
raise ValueError("document uuid must be provided")
response = await self._aclient.delete(
f"/collection/{self.name}/document/uuid/{uuid}",
)
handle_response(response)
def delete_document(self, uuid: str) -> None:
"""
Delete document.
Parameters
----------
uuid: str
The uuid of the document to be deleted.
Returns
-------
None
Raises
------
NotFoundError
If the document is not found.
APIError
If the API response format is unexpected.
"""
if not self._client:
raise ValueError(
"Can only delete a document once a collection has been retrieved"
)
if uuid is None or uuid.strip() == "":
raise ValueError("document uuid must be provided")
response = self._client.delete(
f"/collection/{self.name}/document/uuid/{uuid}",
)
handle_response(response)
async def aget_document(self, uuid: str) -> Document:
"""
Asynchronously gets a document.
Parameters
----------
uuid: str
The name of the document to get.
Returns
-------
Document
The retrieved document.
Raises
------
NotFoundError
If the document is not found.
APIError
If the API response format is unexpected.
"""
if not self._aclient:
raise ValueError(
"Can only get a document once a collection has been retrieved"
)
if uuid is None or uuid.strip() == "":
raise ValueError("document uuid must be provided")
response = await self._aclient.get(
f"/collection/{self.name}/document/uuid/{uuid}",
)
handle_response(response)
return Document(**response.json())
def get_document(self, uuid: str) -> Document:
"""
Gets a document.
Parameters
----------
uuid: str
The name of the document to get.
Returns
-------
Document
The retrieved document.
Raises
------
NotFoundError
If the document is not found.
APIError
If the API response format is unexpected.
"""
if not self._client:
raise ValueError(
"Can only get a document once a collection has been retrieved"
)
if uuid is None or uuid.strip() == "":
raise ValueError("document uuid must be provided")
response = self._client.get(
f"/collection/{self.name}/document/uuid/{uuid}",
)
handle_response(response)
return Document(**response.json())
async def aget_documents(self, uuids: List[str]) -> List[Document]:
"""
Asynchronously gets a list of documents.
Parameters
----------
uuids: List[str]
The list of document uuids to get.
Returns
-------
List[Document]
The list of document objects.
Raises
------
APIError
If the API response format is unexpected.
"""
if not self._aclient:
raise ValueError(
"Can only get documents once a collection has been retrieved"
)
if not uuids or len(uuids) == 0:
raise ValueError("document uuids must be provided")
if len(uuids) > LARGE_BATCH_WARNING_LIMIT:
warnings.warn(LARGE_BATCH_WARNING, stacklevel=2)
response = await self._aclient.post(
f"/collection/{self.name}/document/list/get",
json={"uuids": uuids},
)
handle_response(response)
return [Document(**document) for document in response.json()]
def get_documents(self, uuids: List[str]) -> List[Document]:
"""
Gets a list of documents.
Parameters
----------
uuids: List[str]
The list of document uuids to get.
Returns
-------
List[Document]
The list of document objects.
Raises
------
APIError
If the API response format is unexpected.
"""
if not self._client:
raise ValueError(
"Can only get documents once a collection has been retrieved"
)
if not uuids or len(uuids) == 0:
raise ValueError("document uuids must be provided")
if len(uuids) > LARGE_BATCH_WARNING_LIMIT:
warnings.warn(LARGE_BATCH_WARNING, stacklevel=2)
response = self._client.post(
f"/collection/{self.name}/document/list/get",
json={"uuids": uuids},
)
handle_response(response)
return [Document(**document) for document in response.json()]
def create_index(
self,
force: bool = False,
) -> None:
"""
Creates an index for a DocumentCollection.
Parameters
----------
force : bool, optional
If True, forces the creation of the index even if the number of documents
is less than then minimum recommended for indexing. Defaults to False.
Raises
------
APIError
If the API response format is unexpected.
"""
if not self._client:
raise ValueError("Can only index a collection it has been retrieved")
if (
not force
and self.document_count
and (self.document_count <= MIN_DOCS_TO_INDEX)
):
raise ValueError(
f"Collection must have at least {MIN_DOCS_TO_INDEX} documents to be"
" indexed. Please see the Zep documentation on index best practices."
" Pass force=True to override."
)
params = filter_dict({"force": force})
response = self._client.post(
f"/collection/{self.name}/index/create",
params=params,
)
handle_response(response)
async def asearch_return_query_vector(
self,
text: Optional[str] = None,
embedding: Optional[List[float]] = None,
metadata: Optional[Dict[str, Any]] = None,
limit: Optional[int] = None,
) -> Tuple[List[Document], List[float]]:
if not self._aclient:
raise ValueError(
"Can only search documents once a collection has been retrieved"
)
if text is None and embedding is None and metadata is None:
raise ValueError("One of text, embedding, or metadata must be provided.")
if text is not None and not isinstance(text, str):
raise ValueError("Text must be a string.")
url = f"/collection/{self.name}/search"
params = {"limit": limit} if limit is not None and limit > 0 else {}
response = await self._aclient.post(
url,
params=params,
json={"text": text, "embedding": embedding, "metadata": metadata},
)
# If the collection is not found, return an empty list
if response.status_code == 404:
return [], []
# Otherwise, handle the response for other errors
handle_response(response)
return (
[Document(**document) for document in response.json()["results"]],
response.json()["query_vector"],
)
async def asearch(
self,
text: Optional[str] = None,
embedding: Optional[List[float]] = None,
metadata: Optional[Dict[str, Any]] = None,
limit: Optional[int] = None,
) -> List[Document]:
"""
Async search over documents in a collection based on provided search criteria.
One of text, embedding, or metadata must be provided.
Returns an empty list if no documents are found.
Parameters
----------
text : Optional[str], optional
The search text.
embedding : Optional[List[float]], optional
The embedding vector to search for.
metadata : Optional[Dict[str, Any]], optional
Document metadata to filter on.
limit : Optional[int], optional
Limit the number of returned documents.
Returns
-------
List[Document]
The list of documents that match the search criteria.
Raises
------
APIError
If the API response format is unexpected or there's an error from the API.
"""
results, _ = await self.asearch_return_query_vector(
text=text, embedding=embedding, metadata=metadata, limit=limit
)
return results
def search_return_query_vector(
self,
text: Optional[str] = None,
embedding: Optional[List[float]] = None,
metadata: Optional[Dict[str, Any]] = None,
limit: Optional[int] = None,
) -> Tuple[List[Document], List[float]]:
if not self._client:
raise ValueError(
"Can only search documents once a collection has been retrieved"
)
if text is None and embedding is None and metadata is None:
raise ValueError("One of text, embedding, or metadata must be provided.")
if text is not None and not isinstance(text, str):
raise ValueError("Text must be a string.")
url = f"/collection/{self.name}/search"
params = {"limit": limit} if limit is not None and limit > 0 else {}
response = self._client.post(
url,
params=params,
json={"text": text, "embedding": embedding, "metadata": metadata},
)
# If the collection is not found, return an empty list
if response.status_code == 404:
return [], []
# Otherwise, handle the response for other errors
handle_response(response)
return (
[Document(**document) for document in response.json()["results"]],
response.json()["query_vector"],
)
def search(
self,
text: Optional[str] = None,
embedding: Optional[List[float]] = None,
metadata: Optional[Dict[str, Any]] = None,
limit: Optional[int] = None,
) -> List[Document]:
"""
Searches over documents in a collection based on provided search criteria.
One of text, embedding, or metadata must be provided.
Returns an empty list if no documents are found.
Parameters
----------
text : Optional[str], optional
The search text.
embedding : Optional[List[float]], optional
The embedding vector to search for.
metadata : Optional[Dict[str, Any]], optional
Document metadata to filter on.
limit : Optional[int], optional
Limit the number of returned documents.
Returns
-------
List[Document]
The list of documents that match the search criteria.
Raises
------
APIError
If the API response format is unexpected or there's an error from the API.
"""
results, _ = self.search_return_query_vector(
text=text, embedding=embedding, metadata=metadata, limit=limit
)
return results | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/document/collections.py | collections.py |
from __future__ import annotations
from typing import Any, AsyncGenerator, Dict, Generator, List, Optional
import httpx
from zep_python.exceptions import APIError, handle_response
from zep_python.memory.models import (
Memory,
MemorySearchPayload,
MemorySearchResult,
Message,
Session,
Summary,
)
class MemoryClient:
"""
memory_client class implementation for memory APIs.
Attributes
----------
aclient : httpx.AsyncClient
The async client used for making API requests.
client : httpx.Client
The client used for making API requests.
"""
aclient: httpx.AsyncClient
client: httpx.Client
def __init__(self, aclient: httpx.AsyncClient, client: httpx.Client) -> None:
self.aclient = aclient
self.client = client
def _parse_get_memory_response(self, response_data: Any) -> Memory:
"""Parse the response from the get_memory API call."""
messages: List[Message]
try:
messages = [
Message.parse_obj(m) for m in response_data.get("messages", None)
]
if len(messages) == 0:
raise ValueError("Messages can't be empty")
except (TypeError, ValueError) as e:
raise APIError(message="Unexpected response format from the API") from e
summary: Optional[Summary] = None
if response_data.get("summary", None) is not None:
summary = Summary.parse_obj(response_data["summary"])
memory = Memory(
messages=messages,
# Add the 'summary' field if it is present in the response.
summary=summary,
# Add any other fields from the response that are relevant to the
# Memory class.
)
return memory
def _gen_get_params(self, lastn: Optional[int] = None) -> Dict[str, Any]:
params = {}
if lastn is not None:
params["lastn"] = lastn
return params
# Memory APIs : Get a Session
def get_session(self, session_id: str) -> Session:
"""
Retrieve the session with the specified ID.
Parameters
----------
session_id : str
The ID of the session to retrieve.
Returns
-------
Session
The session with the specified ID.
Raises
------
NotFoundError
If the session with the specified ID is not found.
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
ConnectionError
If the connection to the server fails.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
url = f"/sessions/{session_id}"
try:
response = self.client.get(url)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response, f"No session found for session {session_id}")
response_data = response.json()
return Session.parse_obj(response_data)
# Memory APIs : Get a Session Asynchronously
async def aget_session(self, session_id: str) -> Session:
"""
Asynchronously retrieve the session with the specified ID.
Parameters
----------
session_id : str
The ID of the session to retrieve.
Returns
-------
Session
The session with the specified ID.
Raises
------
NotFoundError
If the session with the specified ID is not found.
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
ConnectionError
If the connection to the server fails.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
url = f"/sessions/{session_id}"
try:
response = await self.aclient.get(url)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response, f"No session found for session {session_id}")
response_data = response.json()
return Session.parse_obj(response_data)
# Memory APIs : Add a Session
def add_session(self, session: Session) -> Session:
"""
Add a session.
Parameters
----------
session : Session
The session to add.
Returns
-------
Session
The added session.
Raises
------
ValueError
If the session is None or empty.
APIError
If the API response format is unexpected.
ConnectionError
If the connection to the server fails.
"""
if session is None:
raise ValueError("session must be provided")
if session.session_id is None or session.session_id.strip() == "":
raise ValueError("session.session_id must be provided")
url = "sessions"
try:
response = self.client.post(url, json=session.dict(exclude_none=True))
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response, f"Failed to add session {session.session_id}")
return Session.parse_obj(response.json())
# Memory APIs : Add a Session Asynchronously
async def aadd_session(self, session: Session) -> Session:
"""
Asynchronously add a session.
Parameters
----------
session : Session
The session to add.
Returns
-------
Session
The added session.
Raises
------
ValueError
If the session is None or empty.
APIError
If the API response format is unexpected.
ConnectionError
If the connection to the server fails.
"""
if session is None:
raise ValueError("session must be provided")
if session.session_id is None or session.session_id.strip() == "":
raise ValueError("session.session_id must be provided")
url = "sessions"
try:
response = await self.aclient.post(
url, json=session.dict(exclude_none=True)
)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response, f"Failed to add session {session.session_id}")
return Session.parse_obj(response.json())
# Memory APIs : Update a Session
def update_session(self, session: Session) -> Session:
"""
Update the specified session.
Parameters
----------
session : Session
The session data to update.
Returns
-------
Session
The updated session.
Raises
------
NotFoundError
If the session with the specified ID is not found.
ValueError
If the session ID or session is None.
APIError
If the API response format is unexpected.
"""
if session is None:
raise ValueError("session must be provided")
if session.session_id is None or session.session_id.strip() == "":
raise ValueError("session_id must be provided")
response = self.client.patch(
f"/sessions/{session.session_id}",
json=session.dict(exclude_none=True),
)
handle_response(response, f"Failed to update session {session.session_id}")
return Session.parse_obj(response.json())
# Memory APIs : Update a Session Asynchronously
async def aupdate_session(self, session: Session) -> Session:
"""
Asynchronously update the specified session.
Parameters
----------
session : Session
The session data to update.
Returns
-------
Session
The updated session.
Raises
------
NotFoundError
If the session with the specified ID is not found.
ValueError
If the session ID or session is None.
APIError
If the API response format is unexpected.
"""
if session is None:
raise ValueError("session must be provided")
if session.session_id is None or session.session_id.strip() == "":
raise ValueError("session_id must be provided")
response = await self.aclient.patch(
f"/sessions/{session.session_id}",
json=session.dict(exclude_none=True),
)
handle_response(response, f"Failed to update session {session.session_id}")
return Session.parse_obj(response.json())
# Memory APIs : Get a List of Sessions
def list_sessions(
self, limit: Optional[int] = None, cursor: Optional[int] = None
) -> List[Session]:
"""
Retrieve a list of paginated sessions.
Parameters
----------
limit : Optional[int]
Limit the number of results returned.
cursor : Optional[int]
Cursor for pagination.
Returns
-------
List[Session]
A list of all sessions paginated.
Raises
------
APIError
If the API response format is unexpected.
ConnectionError
If the connection to the server fails.
"""
url = "sessions"
params = {}
if limit is not None:
params["limit"] = limit
if cursor is not None:
params["cursor"] = cursor
try:
response = self.client.get(url, params=params)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response, "Failed to get sessions")
response_data = response.json()
return [Session.parse_obj(session) for session in response_data]
# Memory APIs : Get a List of Sessions Asynchronously
async def alist_sessions(
self, limit: Optional[int] = None, cursor: Optional[int] = None
) -> List[Session]:
"""
Asynchronously retrieve a list of paginated sessions.
Parameters
----------
limit : Optional[int]
Limit the number of results returned.
cursor : Optional[int]
Cursor for pagination.
Returns
-------
List[Session]
A list of all sessions paginated.
Raises
------
APIError
If the API response format is unexpected.
"""
url = "sessions"
params = {}
if limit is not None:
params["limit"] = limit
if cursor is not None:
params["cursor"] = cursor
try:
response = await self.aclient.get(url, params=params)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response, "Failed to get sessions")
response_data = response.json()
return [Session.parse_obj(session) for session in response_data]
def list_all_sessions(
self, chunk_size: int = 100
) -> Generator[List[Session], None, None]:
"""
Retrieve all sessions, handling pagination automatically.
Yields a generator of lists of sessions.
Parameters
----------
chunk_size : int
The number of sessions to retrieve at a time.
Yields
------
List[Session]
The next chunk of sessions from the server.
Raises
------
APIError
If the API response format is unexpected.
ConnectionError
If the connection to the server fails.
"""
cursor: Optional[int] = None
while True:
response = self.list_sessions(limit=chunk_size, cursor=cursor)
if len(response) == 0:
# We've reached the last page
break
yield response
if cursor is None:
cursor = 0
cursor += chunk_size
async def alist_all_sessions(
self, chunk_size: int = 100
) -> AsyncGenerator[List[Session], None]:
"""
Asynchronously retrieve all sessions, handling pagination automatically.
Yields a generator of lists of sessions.
Parameters
----------
chunk_size : int
The number of sessions to retrieve at a time.
Yields
------
List[Session]
The next chunk of sessions from the server.
Raises
------
APIError
If the API response format is unexpected.
"""
cursor: Optional[int] = None
while True:
response = await self.alist_sessions(limit=chunk_size, cursor=cursor)
if len(response) == 0:
# We've reached the last page
break
yield response
if cursor is None:
cursor = 0
cursor += chunk_size
# Memory APIs : Get Memory
def get_memory(self, session_id: str, lastn: Optional[int] = None) -> Memory:
"""
Retrieve memory for the specified session.
Parameters
----------
session_id : str
The ID of the session for which to retrieve memory.
lastn : Optional[int], optional
The number of most recent memory entries to retrieve. Defaults to None (all
entries).
Returns
-------
Memory
A memory object containing a Summary, metadata, and list of Messages.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
url = f"/sessions/{session_id}/memory"
params = self._gen_get_params(lastn)
response = self.client.get(url, params=params)
handle_response(response, f"No memory found for session {session_id}")
response_data = response.json()
return self._parse_get_memory_response(response_data)
# Memory APIs : Get Memory Asynchronously
async def aget_memory(self, session_id: str, lastn: Optional[int] = None) -> Memory:
"""
Asynchronously retrieve memory for the specified session.
Parameters
----------
session_id : str
The ID of the session for which to retrieve memory.
lastn : Optional[int], optional
The number of most recent memory entries to retrieve. Defaults to None (all
entries).
Returns
-------
Memory
A memory object containing a Summary, metadata, and list of Messages.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
url = f"/sessions/{session_id}/memory"
params = self._gen_get_params(lastn)
response = await self.aclient.get(url, params=params)
handle_response(response, f"No memory found for session {session_id}")
response_data = response.json()
return self._parse_get_memory_response(response_data)
# Memory APIs : Add Memory
def add_memory(self, session_id: str, memory_messages: Memory) -> str:
"""
Add memory to the specified session.
Parameters
----------
session_id : str
The ID of the session to which memory should be added.
memory_messages : Memory
A Memory object representing the memory messages to be added.
Returns
-------
str
The response text from the API.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
response = self.client.post(
f"/sessions/{session_id}/memory",
json=memory_messages.dict(exclude_none=True),
)
handle_response(response)
return response.text
# Memory APIs : Add Memory Asynchronously
async def aadd_memory(self, session_id: str, memory_messages: Memory) -> str:
"""
Asynchronously add memory to the specified session.
Parameters
----------
session_id : str
The ID of the session to which memory should be added.
memory_messages : Memory
A Memory object representing the memory messages to be added.
Returns
-------
str
The response text from the API.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
response = await self.aclient.post(
f"/sessions/{session_id}/memory",
json=memory_messages.dict(exclude_none=True),
)
handle_response(response)
return response.text
# Memory APIs : Delete Memory
def delete_memory(self, session_id: str) -> str:
"""
Delete memory for the specified session.
Parameters
----------
session_id : str
The ID of the session for which memory should be deleted.
Returns
-------
str
The response text from the API.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
response = self.client.delete(f"/sessions/{session_id}/memory")
handle_response(response)
return response.text
# Memory APIs : Delete Memory Asynchronously
async def adelete_memory(self, session_id: str) -> str:
"""
Asynchronously delete memory for the specified session.
Parameters
----------
session_id : str
The ID of the session for which memory should be deleted.
Returns
-------
str
The response text from the API.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
response = await self.aclient.delete(f"/sessions/{session_id}/memory")
handle_response(response)
return response.text
# Memory APIs : Search Memory
def search_memory(
self,
session_id: str,
search_payload: MemorySearchPayload,
limit: Optional[int] = None,
) -> List[MemorySearchResult]:
"""
Search memory for the specified session.
Parameters
----------
session_id : str
The ID of the session for which memory should be searched.
search_payload : MemorySearchPayload
A SearchPayload object representing the search query.
limit : Optional[int], optional
The maximum number of search results to return. Defaults to None (no limit).
Returns
-------
List[MemorySearchResult]
A list of SearchResult objects representing the search results.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
if search_payload is None:
raise ValueError("search_payload must be provided")
params = {"limit": limit} if limit is not None else {}
response = self.client.post(
f"/sessions/{session_id}/search",
json=search_payload.dict(),
params=params,
)
handle_response(response)
return [
MemorySearchResult(**search_result) for search_result in response.json()
]
# Memory APIs : Search Memory Asynchronously
async def asearch_memory(
self,
session_id: str,
search_payload: MemorySearchPayload,
limit: Optional[int] = None,
) -> List[MemorySearchResult]:
"""
Asynchronously search memory for the specified session.
Parameters
----------
session_id : str
The ID of the session for which memory should be searched.
search_payload : MemorySearchPayload
A SearchPayload object representing the search query.
limit : Optional[int], optional
The maximum number of search results to return. Defaults to None (no limit).
Returns
-------
List[MemorySearchResult]
A list of SearchResult objects representing the search results.
Raises
------
ValueError
If the session ID is None or empty.
APIError
If the API response format is unexpected.
"""
if session_id is None or session_id.strip() == "":
raise ValueError("session_id must be provided")
if search_payload is None:
raise ValueError("search_payload must be provided")
params = {"limit": limit} if limit is not None else {}
response = await self.aclient.post(
f"/sessions/{session_id}/search",
json=search_payload.dict(),
params=params,
)
handle_response(response)
return [
MemorySearchResult(**search_result) for search_result in response.json()
] | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/memory/client.py | client.py |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional
if TYPE_CHECKING:
from pydantic import BaseModel, Field
else:
try:
from pydantic.v1 import BaseModel, Field
except ImportError:
from pydantic import BaseModel, Field
class Session(BaseModel):
"""
Represents a session object with a unique identifier, metadata,
and other attributes.
Attributes
----------
uuid : Optional[str]
A unique identifier for the session.
This is generated server-side and is not expected to be present on creation.
created_at : str
The timestamp when the session was created.
Generated by the server.
updated_at : str
The timestamp when the session was last updated.
Generated by the server.
deleted_at : Optional[datetime]
The timestamp when the session was deleted.
Generated by the server.
session_id : str
The unique identifier of the session.
metadata : Dict[str, Any]
The metadata associated with the session.
"""
uuid: Optional[str] = None
id: Optional[int] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
deleted_at: Optional[str] = None
session_id: str
user_id: Optional[str] = None
metadata: Dict[str, Any]
class Summary(BaseModel):
"""
Represents a summary of a conversation.
Attributes
----------
uuid : str
The unique identifier of the summary.
created_at : str
The timestamp of when the summary was created.
content : str
The content of the summary.
recent_message_uuid : str
The unique identifier of the most recent message in the conversation.
token_count : int
The number of tokens in the summary.
Methods
-------
to_dict() -> Dict[str, Any]:
Returns a dictionary representation of the summary.
"""
uuid: str = Field("A uuid is required")
created_at: str = Field("A created_at is required")
content: str = Field("Content is required")
recent_message_uuid: str = Field("A recent_message_uuid is required")
token_count: int = Field("A token_count is required")
def to_dict(self) -> Dict[str, Any]:
"""
Returns a dictionary representation of the summary.
Returns
-------
Dict[str, Any]
A dictionary containing the attributes of the summary.
"""
return self.dict()
class Message(BaseModel):
"""
Represents a message in a conversation.
Attributes
----------
uuid : str, optional
The unique identifier of the message.
created_at : str, optional
The timestamp of when the message was created.
role : str
The role of the sender of the message (e.g., "user", "assistant").
content : str
The content of the message.
token_count : int, optional
The number of tokens in the message.
Methods
-------
to_dict() -> Dict[str, Any]:
Returns a dictionary representation of the message.
"""
role: str = Field("A role is required")
content: str = Field("Content is required")
uuid: Optional[str] = Field(optional=True, default=None)
created_at: Optional[str] = Field(optional=True, default=None)
token_count: Optional[int] = Field(optional=True, default=None)
metadata: Optional[Dict[str, Any]] = Field(optional=True, default=None)
def to_dict(self) -> Dict[str, Any]:
"""
Returns a dictionary representation of the message.
Returns
-------
Dict[str, Any]
A dictionary containing the attributes of the message.
"""
return self.dict()
class Memory(BaseModel):
"""
Represents a memory object with messages, metadata, and other attributes.
Attributes
----------
messages : Optional[List[Dict[str, Any]]]
A list of message objects, where each message contains a role and content.
metadata : Optional[Dict[str, Any]]
A dictionary containing metadata associated with the memory.
summary : Optional[Summary]
A Summary object.
uuid : Optional[str]
A unique identifier for the memory.
created_at : Optional[str]
The timestamp when the memory was created.
token_count : Optional[int]
The token count of the memory.
Methods
-------
to_dict() -> Dict[str, Any]:
Returns a dictionary representation of the message.
"""
messages: List[Message] = Field(
default=[], description="A List of Messages or empty List is required"
)
metadata: Optional[Dict[str, Any]] = Field(optional=True, default=None)
summary: Optional[Summary] = Field(optional=True, default=None)
uuid: Optional[str] = Field(optional=True, default=None)
created_at: Optional[str] = Field(optional=True, default=None)
token_count: Optional[int] = Field(optional=True, default=None)
def to_dict(self) -> Dict[str, Any]:
return self.dict()
class MemorySearchPayload(BaseModel):
"""
Represents a search payload for querying memory.
Attributes
----------
metadata : Dict[str, Any]
Metadata associated with the search query.
text : str
The text of the search query.
"""
text: str = Field("A text is required")
metadata: Optional[Dict[str, Any]] = Field(optional=True, default=None)
class MemorySearchResult(BaseModel):
"""
Represents a search result from querying memory.
Attributes
----------
message : Optional[Dict[str, Any]]
The message associated with the search result.
metadata : Optional[Dict[str, Any]]
Metadata associated with the search result.
summary : Optional[str]
The summary of the search result.
dist : Optional[float]
The distance metric of the search result.
"""
message: Optional[Dict[str, Any]] = None
metadata: Optional[Dict[str, Any]] = None
summary: Optional[str] = None
dist: Optional[float] = None | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/memory/models.py | models.py |
from typing import AsyncGenerator, Generator, List, Optional
import httpx
from httpx import AsyncClient, Client
from zep_python.exceptions import handle_response
from ..memory.models import Session
from .models import CreateUserRequest, UpdateUserRequest, User
class UserClient:
"""
UserClient class implementation for user APIs.
Attributes
----------
aclient : httpx.AsyncClient
The async client used for making API requests.
client : httpx.Client
The client used for making API requests.
"""
def __init__(self, aclient: AsyncClient, client: Client) -> None:
"""
Initialize the UserClient.
Parameters
----------
aclient : httpx.AsyncClient
The async client used for making API requests.
client : httpx.Client
The client used for making API requests.
"""
self.aclient = aclient
self.client = client
def add(self, user: CreateUserRequest) -> User:
"""
Add a user.
Parameters
----------
user : CreateUserRequest
The user to add.
Returns
-------
User
The user that was added.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
try:
response = self.client.post("/user", json=user.dict(exclude_none=True))
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return User.parse_obj(response.json())
async def aadd(self, user: CreateUserRequest) -> User:
"""
Async add a user.
Parameters
----------
user : CreateUserRequest
The user to add.
Returns
-------
User
The user that was added.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
try:
response = await self.aclient.post(
"/user", json=user.dict(exclude_none=True)
)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return User.parse_obj(response.json())
def get(self, user_id: str) -> User:
"""
Get a user.
Parameters
----------
user_id : str
The user_id of the user to get.
Returns
-------
User
The user that was retrieved.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
NotFoundError
If the user does not exist.
"""
try:
response = self.client.get(f"/user/{user_id}")
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return User.parse_obj(response.json())
async def aget(self, user_id: str) -> User:
"""
Async get a user.
Parameters
----------
user_id : str
The user_id of the user to get.
Returns
-------
User
The user that was retrieved.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
NotFoundError
If the user does not exist.
"""
if user_id is None:
raise ValueError("user_id must be provided")
try:
response = await self.aclient.get(f"/user/{user_id}")
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return User.parse_obj(response.json())
def update(self, user: UpdateUserRequest) -> User:
"""
Update a user.
Parameters
----------
user : UpdateUserRequest
The user to update.
Returns
-------
User
The user that was updated.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
NotFoundError
If the user does not exist
"""
if user.user_id is None:
raise ValueError("user_id must be provided")
try:
response = self.client.patch(
f"/user/{user.user_id}", json=user.dict(exclude_none=True)
)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return User.parse_obj(response.json())
async def aupdate(self, user: UpdateUserRequest) -> User:
"""
Async update a user.
Parameters
----------
user : UpdateUserRequest
The user to update.
Returns
-------
User
The user that was updated.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
NotFoundError
If the user does not exist.
"""
if user.user_id is None:
raise ValueError("user_id must be provided")
try:
response = await self.aclient.patch(
f"/user/{user.user_id}", json=user.dict(exclude_none=True)
)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return User.parse_obj(response.json())
def delete(self, user_id: str) -> None:
"""
Delete a user.
Parameters
----------
user_id : str
The user_id of the user to delete.
Returns
-------
None
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
NotFoundError
If the user does not exist.
"""
try:
response = self.client.delete(f"/user/{user_id}")
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
async def adelete(self, user_id: str) -> None:
"""
Async delete a user.
Parameters
----------
user_id : str
The user_id of the user to delete.
Returns
-------
None
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
NotFoundError
If the user does not exist.
"""
try:
response = await self.aclient.delete(f"/user/{user_id}")
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
def list(
self, limit: Optional[int] = None, cursor: Optional[int] = None
) -> List[User]:
"""
List users.
Parameters
----------
limit : Optional[int]
The maximum number of users to return.
cursor : Optional[int]
The cursor to use for pagination.
Returns
-------
List[User]
The list of users. If no users are found, an empty list is returned.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
try:
response = self.client.get(
"/user", params={"limit": limit, "cursor": cursor}
)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return [User.parse_obj(user) for user in response.json()]
async def alist(
self, limit: Optional[int] = None, cursor: Optional[int] = None
) -> List[User]:
"""
Async list users.
Parameters
----------
limit : Optional[int]
The maximum number of users to return.
cursor : Optional[int]
The cursor to use for pagination.
Returns
-------
List[User]
The list of users. An empty list is returned if there are no users.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
try:
response = await self.aclient.get(
"/user", params={"limit": limit, "cursor": cursor}
)
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return [User.parse_obj(user) for user in response.json()]
def list_chunked(self, chunk_size: int = 100) -> Generator[List[User], None, None]:
"""
List all users in chunks.
This method uses pagination to retrieve the users in chunks and returns a
generator that yields each chunk of users as a list.
Parameters
----------
chunk_size : int, optional
The number of users to retrieve in each chunk, by default 100
Returns
-------
Generator[List[User], None, None]
A generator that yields each chunk of users as a list.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
cursor: Optional[int] = None
while True:
response = self.list(limit=chunk_size, cursor=cursor)
if len(response) == 0:
# We've reached the last page
break
yield response
if cursor is None:
cursor = 0
cursor += chunk_size
async def alist_chunked(
self, chunk_size: int = 100
) -> AsyncGenerator[List[User], None]:
"""
Async list all users in chunks.
This method uses pagination to retrieve the users in chunks and returns a
generator that yields each chunk of users as a list.
Parameters
----------
chunk_size : int, optional
The number of users to retrieve in each chunk, by default 100
Returns
-------
Generator[List[User], None, None]
A generator that yields each chunk of users as a list.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
cursor: Optional[int] = None
while True:
response = await self.alist(limit=chunk_size, cursor=cursor)
if len(response) == 0:
# We've reached the last page
break
yield response
if cursor is None:
cursor = 0
cursor += chunk_size
def get_sessions(self, user_id: str) -> List[Session]:
"""
List all sessions associated with this user.
Parameters
----------
user_id : str
The user_id of the user whose sessions to list.
Returns
-------
List[Session]
The list of sessions.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
try:
response = self.client.get(f"/user/{user_id}/sessions")
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return [Session.parse_obj(session) for session in response.json()]
async def aget_sessions(self, user_id: str) -> List[Session]:
"""
Async list all sessions associated with this user.
Parameters
----------
user_id : str
The user_id of the user whose sessions to list.
Returns
-------
List[Session]
The list of sessions.
Raises
------
ConnectionError
If the client fails to connect to the server.
APIError
If the server returns an error.
"""
try:
response = await self.aclient.get(f"/user/{user_id}/sessions")
except httpx.NetworkError as e:
raise ConnectionError("Failed to connect to server") from e
handle_response(response)
return [Session.parse_obj(session) for session in response.json()] | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/user/client.py | client.py |
from datetime import datetime
from typing import Any, Dict, Optional
from uuid import UUID
from pydantic import BaseModel
class User(BaseModel):
"""
Represents a user object with a unique identifier, metadata,
and other attributes.
Attributes
----------
uuid : Optional[UUID]
A unique identifier for the user. Used internally as a primary key.
id : Optional[int]
The ID of the user. Used as a cursor for pagination.
created_at : Optional[datetime]
The timestamp when the user was created.
updated_at : Optional[datetime]
The timestamp when the user was last updated.
deleted_at : Optional[datetime]
The timestamp when the user was deleted.
user_id : str
The unique identifier of the user.
email : Optional[str]
The email of the user.
first_name : Optional[str]
The first name of the user.
last_name : Optional[str]
The last name of the user.
metadata : Optional[Dict[str, Any]]
The metadata associated with the user.
"""
uuid: Optional[UUID] = None
id: Optional[int] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
deleted_at: Optional[datetime] = None
user_id: str
email: Optional[str] = None
first_name: Optional[str] = None
last_name: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
class CreateUserRequest(BaseModel):
"""
Represents a request to create a user.
Attributes
----------
user_id : str
The unique identifier of the user.
email : Optional[str]
The email of the user.
first_name : Optional[str]
The first name of the user.
last_name : Optional[str]
The last name of the user.
metadata : Optional[Dict[str, Any]]
The metadata associated with the user.
"""
user_id: str
email: Optional[str] = None
first_name: Optional[str] = None
last_name: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
class UpdateUserRequest(BaseModel):
"""
Represents a request to update a user.
Attributes
----------
uuid : Optional[UUID]
A unique identifier for the user.
user_id : str
The unique identifier of the user.
email : Optional[str]
The email of the user.
first_name : Optional[str]
The first name of the user.
last_name : Optional[str]
The last name of the user.
metadata : Optional[Dict[str, Any]]
The metadata associated with the user.
"""
uuid: Optional[UUID] = None
user_id: str
email: Optional[str] = None
first_name: Optional[str] = None
last_name: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None | zep-python | /zep_python-1.1.2-py3-none-any.whl/zep_python/user/models.py | models.py |
import warnings
from datetime import datetime
from typing import Optional, Union
import jwt
import requests
from dataclassy import dataclass
from urllib3.exceptions import InsecureRequestWarning
from zepben.auth.client.util import construct_url
from zepben.auth.common.auth_exception import AuthException
from zepben.auth.common.auth_method import AuthMethod
__all__ = ["ZepbenTokenFetcher", "create_token_fetcher"]
@dataclass
class ZepbenTokenFetcher(object):
"""
Fetches access tokens from an authentication provider using the OAuth 2.0 protocol.
"""
audience: str
""" Audience to use when requesting tokens """
issuer_domain: str
""" The domain of the token issuer. """
auth_method: AuthMethod = AuthMethod.OAUTH
""" The authentication method used by the server """
issuer_protocol: str = "https"
""" Protocol of the token issuer. You should not change this unless you are absolutely sure of what you are doing. Setting it to
anything other than https is a major security risk as tokens will be sent in the clear. """
token_path: str = "/oauth/token"
""" Path for requesting token from `issuer_domain`. """
token_request_data = {}
""" Data to pass in token requests. """
refresh_request_data = {}
""" Data to pass in refresh token requests. """
verify: Union[bool, str] = True
"""
Passed through to requests.post(). When this is a boolean, it determines whether or not to verify the HTTPS certificate of the OAUTH service.
When this is a string, it is used as the filename of the certificate truststore to use when verifying the OAUTH service.
"""
_access_token = None
_refresh_token = None
_token_expiry = datetime.min
_token_type = None
def __init__(self):
self.token_request_data["audience"] = self.audience
self.refresh_request_data["audience"] = self.audience
def fetch_token(self) -> str:
"""
Returns a JWT access token and its type in the form of '<type> <3 part JWT>', retrieved from the configured OAuth2 token provider.
Throws AuthException if an access token request fails.
"""
if datetime.utcnow() > self._token_expiry:
# Stored token has expired, try to refresh
self._access_token = None
if self._refresh_token:
self._fetch_token_auth0(True)
if self._access_token is None:
# If using the refresh token did not work for any reason, self._access_token will still be None.
# and thus we must try get a fresh access token using credentials instead.
self._fetch_token_auth0()
# Just to give a friendly error if a token retrieval failed for a case we haven't handled.
if not self._token_type or not self._access_token:
raise Exception(
f"Token couldn't be retrieved from {construct_url(self.issuer_protocol, self.issuer_domain, self.token_path)} using configuration "
f"{self.auth_method}, audience: {self.audience}, token issuer: {self.issuer_domain}"
)
return f"{self._token_type} {self._access_token}"
def _fetch_token_auth0(self, use_refresh: bool = False):
if use_refresh:
self.refresh_request_data["refresh_token"] = self._refresh_token
response = requests.post(
construct_url(self.issuer_protocol, self.issuer_domain, self.token_path),
headers={"content-type": "application/json"},
json=self.refresh_request_data if use_refresh else self.token_request_data,
verify=self.verify
)
if not response.ok:
raise AuthException(response.status_code, f'Token fetch failed, Error was: {response.reason} {response.text}')
try:
data = response.json()
except ValueError:
raise AuthException(response.status_code, f'Response did not contain expected JSON - response was: {response.text}')
if "error" in data or "access_token" not in data:
raise AuthException(
response.status_code,
f'{data.get("error", "Access Token absent in token response")} - {data.get("error_description", f"Response was: {data}")}'
)
self._token_type = data["token_type"]
self._access_token = data["access_token"]
self._token_expiry = datetime.fromtimestamp(jwt.decode(self._access_token, options={"verify_signature": False})['exp'])
if use_refresh:
self._refresh_token = data.get("refresh_token", None)
def fetch_graphql_token(self, client_id, username, password) -> str:
self.token_request_data.update({
'client_id': client_id,
'scope': 'offline_access openid profile email0'
})
self.refresh_request_data.update({
"grant_type": "refresh_token",
'client_id': client_id,
'scope': 'offline_access openid profile email0'
})
self.token_request_data.update({
'grant_type': 'password',
'username': username,
'password': password
})
return self.fetch_token()
def create_token_fetcher(
conf_address: str,
verify_conf: Union[bool, str] = True,
verify_auth: Union[bool, str] = True,
auth_type_field: str = "authType",
audience_field: str = "audience",
issuer_domain_field: str = "issuer"
) -> Optional[ZepbenTokenFetcher]:
"""
Helper method to fetch auth related configuration from `conf_address` and create a :class:`ZepbenTokenFetcher`
:param conf_address: The url to retrieve the authentication config from.
:param verify_conf: Passed through to requests.get() when retrieving the authentication config. When this is a boolean, it determines whether to verify
the HTTPS certificate of `conf_address`. When this is a string, it is used as the filename of the certificate truststore to use
when verifying `conf_address`.
:param verify_auth: Passed through to the resulting :class:`ZepbenTokenFetcher`.
:param auth_type_field: The field name to look up in the JSON response from the conf_address for `token_fetcher.auth_method`.
:param audience_field: The field name to look up in the JSON response from the conf_address for `token_fetcher.auth_method`.
:param issuer_domain_field: The field name to look up in the JSON response from the conf_address for `token_fetcher.auth_method`.
:returns: A :class:`ZepbenTokenFetcher` if the server reported authentication was configured, otherwise None.
"""
with warnings.catch_warnings():
if not verify_conf:
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
try:
response = requests.get(conf_address, verify=verify_conf)
except Exception as e:
warnings.warn(str(e))
warnings.warn("If RemoteDisconnected, this process may hang indefinitely.")
raise ConnectionError("Are you trying to connect to a HTTPS server with HTTP?")
else:
if response.ok:
try:
auth_config_json = response.json()
auth_method = AuthMethod(auth_config_json[auth_type_field])
if auth_method is not AuthMethod.NONE:
return ZepbenTokenFetcher(
audience=auth_config_json[audience_field],
issuer_domain=auth_config_json[issuer_domain_field],
auth_method=auth_method,
verify=verify_auth
)
except ValueError:
raise AuthException(response.status_code, f"Expected JSON response from {conf_address}, but got: {response.text}.")
else:
raise AuthException(
response.status_code,
f"{conf_address} responded with: {response.reason} {response.text}"
)
return None | zepben.auth | /zepben.auth-0.10.0b3-py3-none-any.whl/zepben/auth/client/zepben_token_fetcher.py | zepben_token_fetcher.py |
# Zepben Evolve Python SDK #
The Python Evolve SDK contains everything necessary to communicate with a [Zepben EWB Server](https://github.com/zepben/energy-workbench-server). See the [architecture](docs/architecture.md) documentation for more details.
ote this project is still a work in progress and unstable, and breaking changes may occur prior to 1.0.0.
# Requirements #
- Python 3.7 or later
- pycryptodome, which requires a C/C++ compiler to be installed.
On Linux, python headers (typically `python-dev`) is also necessary to build pycryptodome.
##### On Windows systems:
Download and run [Build Tools for Visual Studio 2019](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019)
When in the installer, select and install:
- C++ build tools
- Windows 10 SDK
- The latest version of MSVC v142 x64/x86 build tools.
After this you should be able to `pip install zepben.cimbend` without issues.
# Installation #
pip install zepben.cimbend
# Building #
python setup.py bdist_wheel
# Developing ##
This library depends on protobuf and gRPC for messaging. To set up for developing against this library, clone it first:
git clone https://github.com/zepben/evolve-sdk-python.git
Install as an editable install. It's recommended to install in a [Python virtualenv](https://virtualenv.pypa.io/en/stable/)
cd evolve-sdk-python
pip install -e .[test]
Run the tests:
python -m pytest
| zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/README.md | README.md |
from __future__ import annotations
import re
import os
from collections.abc import Sized
from typing import Set, List, Optional, Iterable, Callable, Any, TypeVar, Generator
from uuid import UUID
from dataclassy.dataclass import DataClassMeta
T = TypeVar('T')
# phs_to_cores = {SinglePhaseKind.A: 0,
# SinglePhaseKind.B: 1,
# SinglePhaseKind.C: 2,
# SinglePhaseKind.N: 3}
#
# cores_to_phs = {0: SinglePhaseKind.A,
# 1: SinglePhaseKind.B,
# 2: SinglePhaseKind.C,
# 3: SinglePhaseKind.N}
def snake2camelback(name):
return ''.join(word.title() for word in name.split('_'))
_camel_pattern = re.compile(r'(?<!^)(?=[A-Z])')
def camel2snake(name):
return _camel_pattern.sub('_', name).lower()
def iter_but_not_str(obj):
return isinstance(obj, Iterable) and not isinstance(obj, (str, bytes, bytearray, dict))
def get_equipment_connections(cond_equip, exclude: Set = None) -> List:
""" Utility function wrapping :meth:`zepben.cimbend.ConductingEquipment.get_connections` """
return cond_equip.get_connected_equipment(exclude=exclude)
# def phs_kind_to_idx(phase: SinglePhaseKind):
# return phs_to_cores[phase]
def get_by_mrid(collection: Optional[Iterable[IdentifiedObject]], mrid: str) -> IdentifiedObject:
"""
Get an `zepben.cimbend.cim.iec61970.base.core.identified_object.IdentifiedObject` from `collection` based on
its mRID.
`collection` The collection to operate on
`mrid` The mRID of the `IdentifiedObject` to lookup in the collection
Returns The `IdentifiedObject`
Raises `KeyError` if `mrid` was not found in the collection.
"""
if not collection:
raise KeyError(mrid)
for io in collection:
if io.mrid == mrid:
return io
raise KeyError(mrid)
def contains_mrid(collection: Optional[Iterable[IdentifiedObject]], mrid: str) -> bool:
"""
Check if a collection of `zepben.cimbend.cim.iec61970.base.core.identified_object.IdentifiedObject` contains an
object with a specified mRID.
`collection` The collection to operate on
`mrid` The mRID to look up.
Returns True if an `IdentifiedObject` is found in the collection with the specified mRID, False otherwise.
"""
if not collection:
return False
try:
if get_by_mrid(collection, mrid):
return True
except KeyError:
return False
def safe_remove(collection: Optional[List], obj: IdentifiedObject):
"""
Remove an IdentifiedObject from a collection safely.
Raises `ValueError` if `obj` is not in the collection.
Returns The collection if successfully removed or None if after removal the collection was empty.
"""
if collection is not None:
collection.remove(obj)
if not collection:
return None
return collection
else:
raise ValueError(obj)
def nlen(sized: Optional[Sized]) -> int:
"""
Get the len of a nullable sized type.
`sized` The object to get length of
Returns 0 if `sized` is None, otherwise len(`sized`)
"""
return 0 if sized is None else len(sized)
def ngen(collection: Optional[Iterable[T]]) -> Generator[T, None, None]:
if collection:
for item in collection:
yield item
def is_none_or_empty(sized: Optional[Sized]) -> bool:
"""
Check if a given object is empty and return None if it is.
`sized` Any type implementing `__len__`
Returns `sized` if len(sized) > 0, or None if sized is None or len(sized) == 0.
"""
return sized is None or not len(sized)
def require(condition: bool, lazy_message: Callable[[], Any]):
"""
Raise a `ValueError` if condition is not met, with the result of calling `lazy_message` as the message,
if the result is false.
"""
if not condition:
raise ValueError(str(lazy_message()))
def pb_or_none(cim: Optional[Any]):
""" Convert to a protobuf type or return None if cim was None """
return cim.to_pb() if cim is not None else None
class CopyableUUID(UUID):
def __init__(self):
super().__init__(bytes=os.urandom(16), version=4)
def copy(self):
return UUID(bytes=os.urandom(16), version=4) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/util.py | util.py |
__all__ = ["MetricsStore"]
# Copyright 2020 Zeppelin Bend Pty Ltd
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
class MetricsStore(object):
"""
We store buckets of time (5 minute intervals), which map to meters which map to Reading types (see metering.py)
to ordered lists of readings of that type.
If a meter doesn't report for a bucket, that meter did not report any metrics for that time period
"""
def __init__(self, bucket_duration: int = 5000):
self.store = dict()
self.bucket_duration = bucket_duration
self._ordered_buckets = []
self._bucket_times = set()
def _get_bucket(self, timestamp):
"""
Return the timestamp defining each bucket. These will start from 0 and be in intervals of `self.bucket_duration`
"""
return timestamp - (timestamp % self.bucket_duration)
def __next__(self):
for r in self.ascending_iteration():
yield r
raise StopIteration()
@property
def buckets(self):
"""
Time buckets in this metrics store.
Returns List of present time buckets in ascending order
"""
# We lazy sort because we don't want to slow down write times. This will probably disappear in the long run
# TODO: Revisit this after first stable version, potentially when a timeseries DB is implemented
ordered_buckets = sorted(self._bucket_times)
return ordered_buckets
def ascending_iteration(self):
"""
Returns Mapping of meter IDs to Meter's by bucket time in ascending order
"""
for bucket_time in self.buckets:
for meter in self.store[bucket_time].values():
yield meter
def store_meter_reading(self, meter_reading, reading_type):
"""
Stores a given meter reading. If the meter already has readings in the bucket it will append
the readings to the existing meter, based on the type of the reading.
Note that a MeterReadings mRID is not used as part of this function. For the purposes of storing readings,
only the associated meter mRID is considered.
`meter_reading`
Returns
"""
for reading in meter_reading.readings:
bucket_time = self._get_bucket(reading.timestamp)
bucket = self.store.get(bucket_time, {})
self._bucket_times.add(bucket_time)
reading_types = bucket.get(meter_reading.meter_mrid, {})
readings = reading_types.get(reading_type, [])
readings.append(reading)
reading_types[reading_type] = readings
bucket[meter_reading.meter_mrid] = reading_types
self.store[bucket_time] = bucket | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/measurement/metrics_store.py | metrics_store.py |
from enum import Enum
__all__ = ["UnitSymbol", "unit_symbol_from_id", "unit_symbol_from_cim_name"]
def unit_symbol_from_cim_name(value: str):
return _unitsymbol_by_cim_name[value]
def unit_symbol_from_id(value: int):
return _unitsymbol_members_by_id[value]
class UnitSymbol(Enum):
"""
The derived units defined for usage in the CIM. In some cases, the derived unit is equal to an SI unit. Whenever possible, the standard derived symbol is
used instead of the formula for the derived unit. For example, the unit symbol Farad is defined as “F” instead of “CPerV”. In cases where a standard
symbol does not exist for a derived unit, the formula for the unit is used as the unit symbol. For example, density does not have a standard symbol and
so it is represented as “kgPerm3”. With the exception of the “kg”, which is an SI unit, the unit symbols do not contain multipliers and therefore
represent the base derived unit to which a multiplier can be applied as a whole. Every unit symbol is treated as an unparseable text as if it were a
single-letter symbol. The meaning of each unit symbol is defined by the accompanying descriptive text and not by the text contents of the unit symbol. To
allow the widest possible range of serializations without requiring special character handling, several substitutions are made which deviate from the
format described in IEC 80000-1. The division symbol “/” is replaced by the letters “Per”. Exponents are written in plain text after the unit as “m3”
instead of being formatted as “m” with a superscript of 3 or introducing a symbol as in “m^3”. The degree symbol “°” is replaced with the letters “deg”.
Any clarification of the meaning for a substitution is included in the description for the unit symbol. Non-SI units are included in list of unit symbols
to allow sources of data to be correctly labelled with their non-SI units (for example, a GPS sensor that is reporting numbers that represent feet
instead of meters). This allows software to use the unit symbol information correctly convert and scale the raw data of those sources into SI-based
units. The integer values are used for harmonization with IEC 61850.
"""
NONE = (0, "none")
"""Dimension less quantity, e.g. count, per unit, etc."""
METRES = (1, "m")
"""Length in metres."""
KG = (2, "kg")
"""Mass in kilograms. Note: multiplier “k” is included in this unit symbol for compatibility with IEC 61850-7-3."""
SECONDS = (3, "s")
"""Time in seconds."""
A = (4, "A")
"""Current in amperes."""
K = (5, "K")
"""Temperature in kelvins."""
MOL = (6, "mol")
"""Amount of substance in moles."""
CD = (7, "cd")
"""Luminous intensity in candelas."""
DEG = (8, "deg")
"""Plane angle in degrees."""
RAD = (9, "rad")
"""Plane angle in radians (m/m)."""
SR = (10, "sr")
"""Solid angle in steradians (m2/m2)."""
GY = (11, "Gy")
"""Absorbed dose in grays (J/kg)."""
BQ = (12, "Bq")
"""Radioactivity in becquerels (1/s)."""
DEGC = (13, "degC")
"""Relative temperature in degrees Celsius.In the SI unit system the symbol is °C. Electric charge is measured in coulomb that has the unit symbol C.
To distinguish degree Celsius from coulomb the symbol used in the UML is degC. The reason for not using °C is that the special character ° is difficult to
manage in software."""" """
SV = (14, "Sv")
"""Dose equivalent in sieverts (J/kg)."""
F = (15, "F")
"""Electric capacitance in farads (C/V)."""
C = (16, "C")
"""Electric charge in coulombs (A·s)."""
SIEMENS = (17, "S")
"""Conductance in siemens."""
HENRYS = (18, "H")
"""Electric inductance in henrys (Wb/A)."""
V = (19, "V")
"""Electric potential in volts (W/A)."""
OHM = (20, "ohm")
"""Electric resistance in ohms (V/A)."""
J = (21, "J")
"""Energy in joules (N·m = C·V = W·s)."""
N = (22, "N")
"""Force in newtons (kg·m/s²)."""
HZ = (23, "Hz")
"""Frequency in hertz (1/s)."""
LX = (24, "lx")
"""Illuminance in lux (lm/m²)."""
LM = (25, "lm")
"""Luminous flux in lumens (cd·sr)."""
WB = (26, "Wb")
"""Magnetic flux in webers (V·s)."""
T = (27, "T")
"""Magnetic flux density in teslas (Wb/m2)."""
W = (28, "W")
"""Real power in watts (J/s). Electrical power may have real and reactive components. The real portion of electrical power (I²R or VIcos(phi)),
is expressed in Watts. See also apparent power and reactive power."""
PA = (29, "Pa")
"""Pressure in pascals (N/m²). Note: the absolute or relative measurement of pressure is implied with this entry. See below for more explicit forms."""
M2 = (30, "m2")
"""Area in square metres (m²)."""
M3 = (31, "m3")
"""Volume in cubic metres (m³)."""
MPERS = (32, "mPers")
"""Velocity in metres per second (m/s)."""
MPERS2 = (33, "mPers2")
"""Acceleration in metres per second squared (m/s²)."""
M3PERS = (34, "m3Pers")
"""Volumetric flow rate in cubic metres per second (m³/s)."""
MPERM3 = (35, "mPerm3")
"""Fuel efficiency in metres per cubic metres (m/m³)."""
KGM = (36, "kgm")
"""Moment of mass in kilogram metres (kg·m) (first moment of mass).
Note: multiplier “k” is included in this unit symbol for compatibility with IEC 61850-7-3."""
KGPERM3 = (37, "kgPerm3")
"""Density in kilogram/cubic metres (kg/m³). Note: multiplier “k” is included in this unit symbol for compatibility with IEC 61850-7-3."""
M2PERS = (38, "m2Pers")
"""Viscosity in square metres / second (m²/s)."""
WPERMK = (39, "WPermK")
"""Thermal conductivity in watt/metres kelvin."""
JPERK = (40, "JPerK")
"""Heat capacity in joules/kelvin."""
PPM = (41, "ppm")
"""Concentration in parts per million."""
ROTPERS = (42, "rotPers")
"""Rotations per second (1/s). See also Hz (1/s)."""
RADPERS = (43, "radPers")
"""Angular velocity in radians per second (rad/s)."""
WPERM2 = (44, "WPerm2")
"""Heat flux density, irradiance, watts per square metre."""
JPERM2 = (45, "JPerm2")
"""Insulation energy density, joules per square metre or watt second per square metre."""
SPERM = (46, "SPerm")
"""Conductance per length (F/m)."""
KPERS = (47, "KPers")
"""Temperature change rate in kelvins per second."""
PAPERS = (48, "PaPers")
"""Pressure change rate in pascals per second."""
JPERKGK = (49, "JPerkgK")
"""Specific heat capacity, specific entropy, joules per kilogram Kelvin."""
VA = (50, "VA")
"""Apparent power in volt amperes. See also real power and reactive power."""
VAR = (51, "VAr")
"""Reactive power in volt amperes reactive. The “reactive” or “imaginary” component of electrical power (VIsin(phi)). (See also real power and apparent power).
Note: Different meter designs use different methods to arrive at their results. Some meters may compute reactive power as an arithmetic value, while others
compute the value vectorially. The data consumer should determine the method in use and the suitability of the measurement for the intended purpose."""
COSPHI = (52, "cosPhi")
"""Power factor, dimensionless.
Note 1: This definition of power factor only holds for balanced systems. See the alternative definition under code 153.
Note 2 : Beware of differing sign conventions in use between the IEC and EEI. It is assumed that the data consumer understands the type of meter in use
and the sign convention in use by the utility."""
VS = (53, "Vs")
"""Volt seconds (Ws/A)."""
V2 = (54, "V2")
"""Volt squared (W²/A²)."""
AS = (55, "As")
"""Ampere seconds (A·s)."""
A2 = (56, "A2")
"""Amperes squared (A²)."""
A2S = (57, "A2s")
"""Ampere squared time in square amperes (A²s)."""
VAH = (58, "VAh")
"""Apparent energy in volt ampere hours."""
WH = (59, "Wh")
"""Real energy in watt hours."""
VARH = (60, "VArh")
"""Reactive energy in volt ampere reactive hours."""
VPERHZ = (61, "VPerHz")
"""Magnetic flux in volt per hertz."""
HZPERS = (62, "HzPers")
"""Rate of change of frequency in hertz per second."""
CHARACTER = (63, "character")
"""Number of characters."""
CHARPERS = (64, "charPers")
"""Data rate (baud) in characters per second."""
KGM2 = (65, "kgm2")
"""Moment of mass in kilogram square metres (kg·m²) (Second moment of mass, commonly called the moment of inertia). Note: multiplier “k” is included in
this unit symbol for compatibility with IEC 61850-7-3."""
DB = (66, "dB")
"""Sound pressure level in decibels. Note: multiplier “d” is included in this unit symbol for compatibility with IEC 61850-7-3."""
WPERS = (67, "WPers")
"""Ramp rate in watts per second."""
LPERS = (68, "lPers")
"""Volumetric flow rate in litres per second."""
DBM = (69, "dBm")
"""Power level (logarithmic ratio of signal strength , Bel-mW), normalized to 1mW.
Note: multiplier “d” is included in this unit symbol for compatibility with IEC 61850-7-3."""
HOURS = (70, "h")
"""Time in hours, hour = 60 min = 3600 s."""
MIN = (71, "min")
"""Time in minutes, minute = 60 s."""
Q = (72, "Q")
"""Quantity power, Q."""
QH = (73, "Qh")
"""Quantity energy, Qh."""
OHMM = (74, "ohmm")
"""Resistivity, ohm metres, (rho)."""
APERM = (75, "APerm")
"""A/m, magnetic field strength, amperes per metre."""
V2H = (76, "V2h")
"""Volt-squared hour, volt-squared-hours."""
A2H = (77, "A2h")
"""Ampere-squared hour, ampere-squared hour."""
AH = (78, "Ah")
"""Ampere-hours, ampere-hours."""
COUNT = (79, "count")
"""Amount of substance, Counter value."""
FT3 = (80, "ft3")
"""Volume, cubic feet."""
M3PERH = (81, "m3Perh")
"""Volumetric flow rate, cubic metres per hour."""
GAL = (82, "gal")
"""Volume in gallons, US gallon (1 gal = 231 in3 = 128 fl ounce)."""
BTU = (83, "Btu")
"""Energy, British Thermal Units."""
L = (84, "l")
"""Volume in litres, litre = dm3 = m3/1000."""
LPERH = (85, "lPerh")
"""Volumetric flow rate, litres per hour."""
LPERL = (86, "lPerl")
"""Concentration, The ratio of the volume of a solute divided by the volume of the solution.
Note: Users may need use a prefix such a ‘µ’ to express a quantity such as ‘µL/L’."""
GPERG = (87, "gPerg")
"""Concentration, The ratio of the mass of a solute divided by the mass of the solution.
Note: Users may need use a prefix such a ‘µ’ to express a quantity such as ‘µg/g’."""
MOLPERM3 = (88, "molPerm3")
"""Concentration, The amount of substance concentration, (c), the amount of solvent in moles divided by the volume of solution in m³."""
MOLPERMOL = (89, "molPermol")
"""Concentration, Molar fraction, the ratio of the molar amount of a solute divided by the molar amount of the solution."""
MOLPERKG = (90, "molPerkg")
"""Concentration, Molality, the amount of solute in moles and the amount of solvent in kilograms."""
SPERS = (91, "sPers")
"""Time, Ratio of time. Note: Users may need to supply a prefix such as ‘µ’ to show rates such as ‘µs/s’."""
HZPERHZ = (92, "HzPerHz")
"""Frequency, rate of frequency change. Note: Users may need to supply a prefix such as ‘m’ to show rates such as ‘mHz/Hz’."""
VPERV = (93, "VPerV")
"""Voltage, ratio of voltages. Note: Users may need to supply a prefix such as ‘m’ to show rates such as ‘mV/V’."""
APERA = (94, "APerA")
"""Current, ratio of amperages. Note: Users may need to supply a prefix such as ‘m’ to show rates such as ‘mA/A’."""
VPERVA = (95, "VPerVA")
"""Power factor, PF, the ratio of the active power to the apparent power.
Note: The sign convention used for power factor will differ between IEC meters and EEI (ANSI) meters.
It is assumed that the data consumers understand the type of meter being used and agree on the sign convention in use at any given utility."""
REV = (96, "rev")
"""Amount of rotation, revolutions."""
KAT = (97, "kat")
"""Catalytic activity, katal = mol / s."""
JPERKG = (98, "JPerkg")
"""Specific energy, Joules / kg."""
M3UNCOMPENSATED = (99, "m3Uncompensated")
"""Volume, cubic metres, with the value uncompensated for weather effects."""
M3COMPENSATED = (100, "m3Compensated")
"""Volume, cubic metres, with the value compensated for weather effects."""
WPERW = (101, "WPerW")
"""Signal Strength, ratio of power. Note: Users may need to supply a prefix such as ‘m’ to show rates such as ‘mW/W’."""
THERM = (102, "therm")
"""Energy, therms."""
ONEPERM = (103, "onePerm")
"""Wavenumber, reciprocal metres, (1/m)."""
M3PERKG = (104, "m3Perkg")
"""Specific volume, cubic metres per kilogram, v."""
PAS = (105, "Pas")
"""Dynamic viscosity, pascal seconds."""
NM = (106, "Nm")
"""Moment of force, newton metres."""
NPERM = (107, "NPerm")
"""Surface tension, newton per metre."""
RADPERS2 = (108, "radPers2")
"""Angular acceleration, radians per second squared."""
JPERM3 = (109, "JPerm3")
"""Energy density, joules per cubic metre."""
VPERM = (110, "VPerm")
"""Electric field strength, volts per metre."""
CPERM3 = (111, "CPerm3")
"""Electric charge density, coulombs per cubic metre."""
CPERM2 = (112, "CPerm2")
"""Surface charge density, coulombs per square metre."""
FPERM = (113, "FPerm")
"""Permittivity, farads per metre."""
HPERM = (114, "HPerm")
"""Permeability, henrys per metre."""
JPERMOL = (115, "JPermol")
"""Molar energy, joules per mole."""
JPERMOLK = (116, "JPermolK")
"""Molar entropy, molar heat capacity, joules per mole kelvin."""
CPERKG = (117, "CPerkg")
"""Exposure (x rays), coulombs per kilogram."""
GYPERS = (118, "GyPers")
"""Absorbed dose rate, grays per second."""
WPERSR = (119, "WPersr")
"""Radiant intensity, watts per steradian."""
WPERM2SR = (120, "WPerm2sr")
"""Radiance, watts per square metre steradian."""
KATPERM3 = (121, "katPerm3")
"""Catalytic activity concentration, katals per cubic metre."""
D = (122, "d")
"""Time in days, day = 24 h = 86400 s."""
ANGLEMIN = (123, "anglemin")
"""Plane angle, minutes."""
ANGLESEC = (124, "anglesec")
"""Plane angle, seconds."""
HA = (125, "ha")
"""Area, hectares."""
TONNE = (126, "tonne")
"""Mass in tons, “tonne” or “metric ton” (1000 kg = 1 Mg)."""
BAR = (127, "bar")
"""Pressure in bars, (1 bar = 100 kPa)."""
MMHG = (128, "mmHg")
"""Pressure, millimetres of mercury (1 mmHg is approximately 133.3 Pa)."""
MILES_NAUTICAL = (129, "M")
"""Length, nautical miles (1 M = 1852 m)."""
KN = (130, "kn")
"""Speed, knots (1 kn = 1852/3600) m/s."""
MX = (131, "Mx")
"""Magnetic flux, maxwells (1 Mx = 10-8 Wb)."""
G = (132, "G")
"""Magnetic flux density, gausses (1 G = 10-4 T)."""
OE = (133, "Oe")
"""Magnetic field in oersteds, (1 Oe = (103/4p) A/m)."""
VH = (134, "Vh")
"""Volt-hour, Volt hours."""
WPERA = (135, "WPerA")
"""Active power per current flow, watts per Ampere."""
ONEPERHZ = (136, "onePerHz")
"""Reciprocal of frequency (1/Hz)."""
VPERVAR = (137, "VPerVAr")
"""Power factor, PF, the ratio of the active power to the apparent power.
Note: The sign convention used for power factor will differ between IEC meters and EEI (ANSI) meters.
It is assumed that the data consumers understand the type of meter being used and agree on the sign convention in use at any given utility."""
OHMPERM = (138, "ohmPerm")
"""Electric resistance per length in ohms per metre ((V/A)/m)."""
KGPERJ = (139, "kgPerJ")
"""Weight per energy in kilograms per joule (kg/J). Note: multiplier “k” is included in this unit symbol for compatibility with IEC 61850-7-3."""
JPERS = (140, "JPers")
"""Energy rate in joules per second (J/s)."""
@property
def short_name(self):
return str(self)[11:]
def __str__(self):
return self.value[1]
def id(self):
return self.value[0]
_unitsymbol_members_by_id = [us for us in UnitSymbol.__members__.values()]
_unitsymbol_by_cim_name = {str(us): us for us in UnitSymbol.__members__.values()} | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/domain/unit_symbol.py | unit_symbol.py |
from __future__ import annotations
from typing import List, Optional, Generator
from zepben.cimbend.cim.iec61970.base.core.conducting_equipment import ConductingEquipment
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.cim.iec61970.base.core.power_system_resource import PowerSystemResource
from zepben.cimbend.cim.iec61970.base.wires.vector_group import VectorGroup
from zepben.cimbend.cim.iec61970.base.wires.winding_connection import WindingConnection
from zepben.cimbend.util import require, nlen, get_by_mrid, ngen, safe_remove
__all__ = ["TapChanger", "RatioTapChanger", "PowerTransformer", "PowerTransformerEnd", "TransformerEnd"]
class TapChanger(PowerSystemResource):
"""
Mechanism for changing transformer winding tap positions.
"""
control_enabled: bool = True
"""Specifies the regulation status of the equipment. True is regulating, false is not regulating."""
neutral_u: int = 0
"""Voltage at which the winding operates at the neutral tap setting."""
_high_step: int = 1
_low_step: int = 0
_neutral_step: int = 0
_normal_step: int = 0
_step: float = 0.0
def __init__(self, high_step: int = 1, low_step: int = 0, neutral_step: int = 0, normal_step: int = 0, step: float = 0.0):
self._high_step = high_step
self._low_step = low_step
self._neutral_step = neutral_step
self._normal_step = normal_step
self._step = step
self._validate_steps()
@property
def high_step(self):
"""Highest possible tap step position, advance from neutral. The attribute shall be greater than lowStep."""
return self._high_step
@high_step.setter
def high_step(self, val):
require(val > self._low_step, lambda: f"High step {val} must be greater than low step {self._low_step}")
self._check_steps(self.low_step, val)
self._high_step = val
@property
def low_step(self):
"""Lowest possible tap step position, retard from neutral"""
return self._low_step
@low_step.setter
def low_step(self, val):
require(val < self._high_step, lambda: f"Low step {val} must be less than high step {self._high_step}")
self._check_steps(val, self.high_step)
self._low_step = val
@property
def neutral_step(self):
"""The neutral tap step position for this winding. The attribute shall be equal or greater than lowStep and equal or less than highStep."""
return self._neutral_step
@neutral_step.setter
def neutral_step(self, val):
require(self._low_step <= val <= self._high_step, lambda: f"Neutral step {val} must be between high step {self._high_step} and low step {self._low_step}")
self._neutral_step = val
@property
def normal_step(self):
"""
The tap step position used in "normal" network operation for this winding. For a "Fixed" tap changer indicates the current physical tap setting.
The attribute shall be equal or greater than lowStep and equal or less than highStep.
"""
return self._normal_step
@normal_step.setter
def normal_step(self, val):
require(self._low_step <= val <= self._high_step, lambda: f"Normal step {val} must be between high step {self._high_step} and low step {self._low_step}")
self._normal_step = val
@property
def step(self):
"""
Tap changer position. Starting step for a steady state solution. Non integer values are allowed to support continuous tap variables.
The reasons for continuous value are to support study cases where no discrete tap changers has yet been designed, a solutions where a narrow voltage
band force the tap step to oscillate or accommodate for a continuous solution as input.
The attribute shall be equal or greater than lowStep and equal or less than highStep.
"""
return self._step
@step.setter
def step(self, val):
require(self._low_step <= val <= self._high_step, lambda: f"Step {val} must be between high step {self._high_step} and low step {self._low_step}")
self._step = val
def _check_steps(self, low, high):
require(low <= self.step <= high, lambda: f"New value would invalidate current step of {self.step}")
require(low <= self.normal_step <= high,
lambda: f"New value would invalidate current normal_step of {self.normal_step}")
require(low <= self.neutral_step <= high,
lambda: f"New value would invalidate current neutral_step of {self.neutral_step}")
def _validate_steps(self):
require(self.high_step > self.low_step,
lambda: f"High step [{self.high_step}] must be greater than low step [{self.low_step}]")
require(self.low_step <= self.neutral_step <= self.high_step,
lambda: f"Neutral step [{self.neutral_step}] must be between high step [{self._high_step}] and low step [{self._low_step}]")
require(self._low_step <= self.normal_step <= self._high_step,
lambda: f"Normal step [{self.normal_step}] must be between high step [{self._high_step}] and low step [{self._low_step}]")
require(self._low_step <= self.step <= self._high_step,
lambda: f"Step [{self.step}] must be between high step [{self._high_step}] and low step [{self._low_step}]")
class RatioTapChanger(TapChanger):
"""
A tap changer that changes the voltage ratio impacting the voltage magnitude but not the phase angle across the transformer.
Angle sign convention (general): Positive value indicates a positive phase shift from the winding where the tap is located to the other winding
(for a two-winding transformer).
"""
transformer_end: Optional[TransformerEnd] = None
"""`TransformerEnd` to which this ratio tap changer belongs."""
step_voltage_increment: float = 0.0
"""Tap step increment, in per cent of neutral voltage, per step position."""
class TransformerEnd(IdentifiedObject):
"""
A conducting connection point of a power transformer. It corresponds to a physical transformer winding terminal.
In earlier CIM versions, the TransformerWinding class served a similar purpose, but this class is more flexible
because it associates to terminal but is not a specialization of ConductingEquipment.
"""
grounded: bool = False
"""(for Yn and Zn connections) True if the neutral is solidly grounded."""
r_ground: float = 0.0
"""(for Yn and Zn connections) Resistance part of neutral impedance where 'grounded' is true"""
x_ground: float = 0.0
"""(for Yn and Zn connections) Reactive part of neutral impedance where 'grounded' is true"""
ratio_tap_changer: Optional[RatioTapChanger] = None
"""Ratio tap changer associated with this transformer end."""
terminal: Optional[Terminal] = None
"""The terminal of the transformer that this end is associated with"""
base_voltage: Optional[BaseVoltage] = None
"""Base voltage of the transformer end. This is essential for PU calculation."""
end_number: int = 0
"""Number for this transformer end, corresponding to the end’s order in the power transformer vector group or phase angle clock number.
Highest voltage winding should be 1. Each end within a power transformer should have a unique subsequent end number.
Note the transformer end number need not match the terminal sequence number."""
class PowerTransformerEnd(TransformerEnd):
"""
A PowerTransformerEnd is associated with each Terminal of a PowerTransformer.
The impedance values r, r0, x, and x0 of a PowerTransformerEnd represents a star equivalent as follows
1) for a two Terminal PowerTransformer the high voltage PowerTransformerEnd has non zero values on r, r0, x, and x0
while the low voltage PowerTransformerEnd has zero values for r, r0, x, and x0.
2) for a three Terminal PowerTransformer the three PowerTransformerEnds represents a star equivalent with each leg
in the star represented by r, r0, x, and x0 values.
3) For a three Terminal transformer each PowerTransformerEnd shall have g, g0, b and b0 values corresponding the no load losses
distributed on the three PowerTransformerEnds. The total no load loss shunt impedances may also be placed at one of the
PowerTransformerEnds, preferably the end numbered 1, having the shunt values on end 1 is the preferred way.
4) for a PowerTransformer with more than three Terminals the PowerTransformerEnd impedance values cannot be used.
Instead use the TransformerMeshImpedance or split the transformer into multiple PowerTransformers.
"""
_power_transformer: Optional[PowerTransformer] = None
"""The power transformer of this power transformer end."""
rated_s: int = 0
"""Normal apparent power rating. The attribute shall be a positive value. For a two-winding transformer the values for the high and low voltage sides
shall be identical."""
rated_u: int = 0
"""Rated voltage: phase-phase for three-phase windings, and either phase-phase or phase-neutral for single-phase windings. A high voltage side, as given by
TransformerEnd.endNumber, shall have a ratedU that is greater or equal than ratedU for the lower voltage sides."""
r: float = 0.0
"""Resistance (star-phases) of the transformer end. The attribute shall be equal or greater than zero for non-equivalent transformers."""
x: float = 0.0
"""Positive sequence series reactance (star-phases) of the transformer end."""
r0: float = 0.0
"""Zero sequence series resistance (star-phases) of the transformer end."""
x0: float = 0.0
"""Zero sequence series reactance of the transformer end."""
g: float = 0.0
"""Magnetizing branch conductance."""
g0: float = 0.0
"""Zero sequence magnetizing branch conductance (star-phases)."""
b: float = 0.0
"""Magnetizing branch susceptance (B mag). The value can be positive or negative."""
b0: float = 0.0
"""Zero sequence magnetizing branch susceptance."""
connection_kind: WindingConnection = WindingConnection.UNKNOWN_WINDING
"""Kind of `zepben.protobuf.cim.iec61970.base.wires.winding_connection.WindingConnection` for this end."""
phase_angle_clock: int = 0
"""Terminal voltage phase angle displacement where 360 degrees are represented with clock hours. The valid values are 0 to 11. For example, for the
secondary side end of a transformer with vector group code of 'Dyn11', specify the connection kind as wye with neutral and specify the phase angle of the
clock as 11. The clock value of the transformer end number specified as 1, is assumed to be zero."""
def __init__(self, power_transformer: PowerTransformer = None):
if power_transformer:
self.power_transformer = power_transformer
@property
def power_transformer(self):
"""The power transformer of this power transformer end."""
return self._power_transformer
@power_transformer.setter
def power_transformer(self, pt):
if self._power_transformer is None or self._power_transformer is pt:
self._power_transformer = pt
else:
raise ValueError(f"power_transformer for {str(self)} has already been set to {self._power_transformer}, cannot reset this field to {pt}")
@property
def nominal_voltage(self):
return self.base_voltage.nominal_voltage if self.base_voltage else self.rated_u
class PowerTransformer(ConductingEquipment):
"""
An electrical device consisting of two or more coupled windings, with or without a magnetic core, for introducing
mutual coupling between electric circuits.
Transformers can be used to control voltage and phase shift (active power flow). A power transformer may be composed of separate transformer tanks that
need not be identical. A power transformer can be modeled with or without tanks and is intended for use in both balanced and unbalanced representations.
A power transformer typically has two terminals, but may have one (grounding), three or more terminals.
The inherited association ConductingEquipment.BaseVoltage should not be used.
The association from TransformerEnd to BaseVoltage should be used instead.
Attributes -
vector_group : `zepben.protobuf.cim.iec61970.base.wires.VectorGroup` of the transformer for protective relaying.
power_transformer_ends :
"""
vector_group: VectorGroup = VectorGroup.UNKNOWN
"""
Vector group of the transformer for protective relaying, e.g., Dyn1. For unbalanced transformers, this may not be simply
determined from the constituent winding connections and phase angle displacements.
The vectorGroup string consists of the following components in the order listed: high voltage winding connection, mid
voltage winding connection(for three winding transformers), phase displacement clock number from 0 to 11, low voltage
winding connection phase displacement clock number from 0 to 11. The winding connections are D(delta), Y(wye),
YN(wye with neutral), Z(zigzag), ZN(zigzag with neutral), A(auto transformer). Upper case means the high voltage,
lower case mid or low.The high voltage winding always has clock position 0 and is not included in the vector group
string. Some examples: YNy0(two winding wye to wye with no phase displacement), YNd11(two winding wye to delta with
330 degrees phase displacement), YNyn0d5(three winding transformer wye with neutral high voltage, wye with neutral mid
voltage and no phase displacement, delta low voltage with 150 degrees displacement).
Phase displacement is defined as the angular difference between the phasors representing the voltages between the
neutral point(real or imaginary) and the corresponding terminals of two windings, a positive sequence voltage system
being applied to the high-voltage terminals, following each other in alphabetical sequence if they are lettered, or in
numerical sequence if they are numbered: the phasors are assumed to rotate in a counter-clockwise sense.
"""
_power_transformer_ends: Optional[List[PowerTransformerEnd]] = None
def __init__(self, usage_points: List[UsagePoint] = None, equipment_containers: List[EquipmentContainer] = None,
operational_restrictions: List[OperationalRestriction] = None, current_feeders: List[Feeder] = None, terminals: List[Terminal] = None,
power_transformer_ends: List[PowerTransformerEnd] = None):
super(PowerTransformer, self).__init__(usage_points=usage_points, equipment_containers=equipment_containers, operational_restrictions=operational_restrictions,
current_feeders=current_feeders, terminals=terminals)
if power_transformer_ends:
for end in power_transformer_ends:
self.add_end(end)
def num_ends(self):
"""
Get the number of `PowerTransformerEnd`s for this `PowerTransformer`.
"""
return nlen(self._power_transformer_ends)
@property
def ends(self) -> Generator[PowerTransformerEnd, None, None]:
"""The `PowerTransformerEnd`s for this `PowerTransformer`."""
return ngen(self._power_transformer_ends)
def get_base_voltage(self, terminal: Terminal = None):
if terminal is None:
return self.base_voltage
for end in self.ends:
if end.terminal is terminal:
return end.base_voltage
else:
return None
def get_end_by_mrid(self, mrid: str) -> PowerTransformerEnd:
"""
Get the `PowerTransformerEnd` for this `PowerTransformer` identified by `mrid`
`mrid` the mRID of the required `PowerTransformerEnd`
Returns The `PowerTransformerEnd` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._power_transformer_ends, mrid)
def get_end_by_num(self, end_number: int):
"""
Get the `PowerTransformerEnd` on this `PowerTransformer` by its `end_number`.
`end_number` The `end_number` of the `PowerTransformerEnd` in relation to this `PowerTransformer`s VectorGroup.
Returns The `PowerTransformerEnd` referred to by `end_number`
Raises IndexError if no `PowerTransformerEnd` was found with end_number `end_number`.
"""
if self._power_transformer_ends:
for end in self._power_transformer_ends:
if end.end_number == end_number:
return end
raise IndexError(f"No TransformerEnd with end_number {end_number} was found in PowerTransformer {str(self)}")
def add_end(self, end: PowerTransformerEnd) -> PowerTransformer:
"""
Associate a `PowerTransformerEnd` with this `PowerTransformer`. If `end.end_number` == 0, the end will be assigned an end_number of
`self.num_ends() + 1`.
`end` the `PowerTransformerEnd` to associate with this `PowerTransformer`.
Returns A reference to this `PowerTransformer` to allow fluent use.
Raises `ValueError` if another `PowerTransformerEnd` with the same `mrid` already exists for this `PowerTransformer`.
"""
if self._validate_end(end):
return self
if end.end_number == 0:
end.end_number = self.num_ends() + 1
self._power_transformer_ends = list() if self._power_transformer_ends is None else self._power_transformer_ends
self._power_transformer_ends.append(end)
self._power_transformer_ends.sort(key=lambda t: t.end_number)
return self
def remove_end(self, end: PowerTransformerEnd) -> PowerTransformer:
"""
`end` the `PowerTransformerEnd` to disassociate from this `PowerTransformer`.
Raises `ValueError` if `end` was not associated with this `PowerTransformer`.
Returns A reference to this `PowerTransformer` to allow fluent use.
"""
self._power_transformer_ends = safe_remove(self._power_transformer_ends, end)
return self
def clear_ends(self) -> PowerTransformer:
"""
Clear all `PowerTransformerEnd`s.
Returns A reference to this `PowerTransformer` to allow fluent use.
"""
self._power_transformer_ends.clear()
return self
def _validate_end(self, end: PowerTransformerEnd) -> bool:
"""
Validate an end against this `PowerTransformer`'s `PowerTransformerEnd`s.
`end` The `PowerTransformerEnd` to validate.
Returns True if `end` is already associated with this `PowerTransformer`, otherwise False.
Raises `ValueError` if `end.power_transformer` is not this `PowerTransformer`, or if this `PowerTransformer` has a different `PowerTransformerEnd`
with the same mRID.
"""
if self._validate_reference(end, self.get_end_by_mrid, "A PowerTransformerEnd"):
return True
if self._validate_reference_by_sn(end.end_number, end, self.get_end_by_num, "A PowerTransformerEnd", "end_number"):
return True
require(end.power_transformer is self,
lambda: f"PowerTransformerEnd {end} references another PowerTransformer {end.power_transformer}, expected {str(self)}.")
return False | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/wires/power_transformer.py | power_transformer.py |
from __future__ import annotations
from typing import List, Optional, Generator
from zepben.cimbend.cim.iec61970.base.wires.energy_connection import EnergyConnection
from zepben.cimbend.cim.iec61970.base.wires.energy_source_phase import EnergySourcePhase
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
__all__ = ["EnergySource"]
class EnergySource(EnergyConnection):
"""
A generic equivalent for an energy supplier on a transmission or distribution voltage level.
"""
_energy_source_phases: Optional[List[EnergySourcePhase]] = None
active_power: float = 0.0
"""High voltage source active injection. Load sign convention is used, i.e. positive sign means flow out from a node. Starting value for steady state solutions"""
r: float = 0.0
"""Positive sequence Thevenin resistance."""
x: float = 0.0
"""Positive sequence Thevenin reactance."""
reactive_power: float = 0.0
"""High voltage source reactive injection. Load sign convention is used, i.e. positive sign means flow out from a node.
Starting value for steady state solutions."""
voltage_angle: float = 0.0
"""Phase angle of a-phase open circuit."""
voltage_magnitude: float = 0.0
"""Phase-to-phase open circuit voltage magnitude."""
p_max: float = 0.0
p_min: float = 0.0
r0: float = 0.0
rn: float = 0.0
x0: float = 0.0
xn: float = 0.0
def __init__(self, usage_points: List[UsagePoint] = None, equipment_containers: List[EquipmentContainer] = None,
operational_restrictions: List[OperationalRestriction] = None, current_feeders: List[Feeder] = None, terminals: List[Terminal] = None,
energy_source_phases: List[EnergySourcePhase] = None):
super(EnergySource, self).__init__(usage_points=usage_points, equipment_containers=equipment_containers,
operational_restrictions=operational_restrictions,
current_feeders=current_feeders, terminals=terminals)
if energy_source_phases:
for phase in energy_source_phases:
self.add_phase(phase)
@property
def phases(self) -> Generator[EnergySourcePhase, None, None]:
"""
The `EnergySourcePhase`s for this `EnergySource`.
"""
return ngen(self._energy_source_phases)
def has_phases(self):
"""
Check if this source has any associated `EnergySourcePhase`s
Returns True if there is at least one `EnergySourcePhase`, otherwise False
"""
return nlen(self._energy_source_phases) > 0
def num_phases(self):
"""Return the number of `EnergySourcePhase`s associated with this `EnergySource`"""
return nlen(self._energy_source_phases)
def get_phase(self, mrid: str) -> EnergySource:
"""
Get the `zepben.cimbend.cim.iec61970.base.wires.energy_source_phase.EnergySourcePhase` for this `EnergySource` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61970.base.wires.energy_source_phase.EnergySourcePhase`
Returns The `zepben.cimbend.cim.iec61970.base.wires.energy_source_phase.EnergySourcePhase` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._energy_source_phases, mrid)
def add_phase(self, phase: EnergySourcePhase) -> EnergySource:
"""
Associate an `zepben.cimbend.cim.iec61970.base.wires.energy_source_phase.EnergySourcePhase` with this `EnergySource`
`phase` the `EnergySourcePhase` to associate with this `EnergySource`.
Returns A reference to this `EnergySource` to allow fluent use.
Raises `ValueError` if another `EnergySourcePhase` with the same `mrid` already exists for this `EnergySource`.
"""
if self._validate_reference(phase, self.get_phase, "An EnergySourcePhase"):
return self
self._energy_source_phases = list() if self._energy_source_phases is None else self._energy_source_phases
self._energy_source_phases.append(phase)
return self
def remove_phases(self, phase: EnergySourcePhase) -> EnergySource:
"""
Disassociate an `phase` from this `EnergySource`
`phase` the `EnergySourcePhase` to disassociate from this `EnergySource`.
Returns A reference to this `EnergySource` to allow fluent use.
Raises `ValueError` if `phase` was not associated with this `EnergySource`.
"""
self._energy_source_phases = safe_remove(self._energy_source_phases, phase)
return self
def clear_phases(self) -> EnergySource:
"""
Clear all phases.
Returns A reference to this `EnergySource` to allow fluent use.
"""
self._energy_source_phases = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/wires/energy_source.py | energy_source.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61970.base.core.power_system_resource import PowerSystemResource
from zepben.cimbend.cim.iec61970.base.wires.energy_connection import EnergyConnection
from zepben.cimbend.cim.iec61970.base.wires.phase_shunt_connection_kind import PhaseShuntConnectionKind
from zepben.cimbend.cim.iec61970.base.wires.single_phase_kind import SinglePhaseKind
__all__ = ["EnergyConsumer", "EnergyConsumerPhase"]
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
class EnergyConsumerPhase(PowerSystemResource):
"""A single phase of an energy consumer."""
_energy_consumer: Optional[EnergyConsumer] = None
phase: SinglePhaseKind = SinglePhaseKind.X
"""Phase of this energy consumer component. If the energy consumer is wye connected, the connection is from the indicated phase to the central ground or
neutral point. If the energy consumer is delta connected, the phase indicates an energy consumer connected from the indicated phase to the next
logical non-neutral phase. """
p: float = 0.0
"""Active power of the load. Load sign convention is used, i.e. positive sign means flow out from a node. For voltage dependent loads the value is at
rated voltage. Starting value for a steady state solution."""
q: float = 0.0
"""Reactive power of the load. Load sign convention is used, i.e. positive sign means flow out from a node. For voltage dependent loads the value is at
rated voltage. Starting value for a steady state solution."""
p_fixed: float = 0.0
"""Active power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node."""
q_fixed: float = 0.0
"""Reactive power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node."""
def __init__(self, energy_consumer: EnergyConsumer = None):
if energy_consumer:
self.energy_consumer = energy_consumer
@property
def energy_consumer(self):
"""The `zepben.cimbend.cim.iec61970.base.wires.EnergyConsumer` that has this phase."""
return self._energy_consumer
@energy_consumer.setter
def energy_consumer(self, ec):
if self._energy_consumer is None or self._energy_consumer is ec:
self._energy_consumer = ec
else:
raise ValueError(f"energy_consumer for {str(self)} has already been set to {self._energy_consumer}, cannot reset this field to {ec}")
class EnergyConsumer(EnergyConnection):
"""Generic user of energy - a point of consumption on the power system phases. May also represent a pro-sumer with negative p/q values. """
_energy_consumer_phases: Optional[List[EnergyConsumerPhase]] = None
"""The individual phase models for this energy consumer."""
customer_count: int = 0
"""Number of individual customers represented by this demand."""
grounded: bool = False
"""Used for Yn and Zn connections. True if the neutral is solidly grounded."""
phase_connection: PhaseShuntConnectionKind = PhaseShuntConnectionKind.D
"""`zepben.protobuf.cim.iec61970.base.wires.phase_shunt_connection_kind.PhaseShuntConnectionKind` - The type of phase connection,
such as wye, delta, I (single phase)."""
p: float = 0.0
"""Active power of the load. Load sign convention is used, i.e. positive sign means flow out from a node. For voltage dependent loads the value is at
rated voltage. Starting value for a steady state solution."""
p_fixed: float = 0.0
"""Active power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node."""
q: float = 0.0
"""Reactive power of the load. Load sign convention is used, i.e. positive sign means flow out from a node. For voltage dependent loads the value is at
rated voltage. Starting value for a steady state solution."""
q_fixed: float = 0.0
"""Power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node."""
def __init__(self, usage_points: List[UsagePoint] = None, equipment_containers: List[EquipmentContainer] = None,
operational_restrictions: List[OperationalRestriction] = None, current_feeders: List[Feeder] = None, terminals: List[Terminal] = None,
energy_consumer_phases: List[EnergyConsumerPhase] = None):
super(EnergyConsumer, self).__init__(usage_points=usage_points, equipment_containers=equipment_containers, operational_restrictions=operational_restrictions,
current_feeders=current_feeders, terminals=terminals)
if energy_consumer_phases:
for phase in energy_consumer_phases:
self.add_phase(phase)
def has_phases(self):
"""
Check if this consumer has any associated `EnergyConsumerPhases`
Returns True if there is at least one `EnergyConsumerPhase`, otherwise False
"""
return nlen(self._energy_consumer_phases) > 0
def num_phases(self):
"""Get the number of `EnergySourcePhase`s for this `EnergyConsumer`."""
return nlen(self._energy_consumer_phases)
@property
def phases(self) -> Generator[EnergyConsumerPhase, None, None]:
"""The individual phase models for this energy consumer."""
return ngen(self._energy_consumer_phases)
def get_phase(self, mrid: str) -> EnergyConsumer:
"""
Get the `EnergyConsumerPhase` for this `EnergyConsumer` identified by `mrid`
`mrid` The mRID of the required `EnergyConsumerPhase`
Returns The `EnergyConsumerPhase` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._energy_consumer_phases, mrid)
def add_phase(self, phase: EnergyConsumerPhase) -> EnergyConsumer:
"""
Associate an `EnergyConsumerPhase` with this `EnergyConsumer`
`phase` the `EnergyConsumerPhase` to associate with this `EnergyConsumer`.
Returns A reference to this `EnergyConsumer` to allow fluent use.
Raises `ValueError` if another `EnergyConsumerPhase` with the same `mrid` already exists for this `EnergyConsumer`.
"""
if self._validate_reference(phase, self.get_phase, "An EnergyConsumerPhase"):
return self
self._energy_consumer_phases = list() if self._energy_consumer_phases is None else self._energy_consumer_phases
self._energy_consumer_phases.append(phase)
return self
def remove_phase(self, phase: EnergyConsumerPhase) -> EnergyConsumer:
"""
Disassociate `phase` from this `OperationalRestriction`.
`phase` the `EnergyConsumerPhase` to disassociate with this `EnergyConsumer`.
Raises `KeyError` if `phase` was not associated with this `EnergyConsumer`.
Returns A reference to this `EnergyConsumer` to allow fluent use.
Raises `ValueError` if `phase` was not associated with this `EnergyConsumer`.
"""
self._energy_consumer_phases = safe_remove(self._energy_consumer_phases, phase)
return self
def clear_phases(self) -> EnergyConsumer:
"""
Clear all phases.
Returns A reference to this `EnergyConsumer` to allow fluent use.
"""
self._energy_consumer_phases = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/wires/energy_consumer.py | energy_consumer.py |
from zepben.cimbend.cim.iec61970.base.wires.energy_connection import RegulatingCondEq
from zepben.cimbend.cim.iec61970.base.wires.phase_shunt_connection_kind import PhaseShuntConnectionKind
__all__ = ["ShuntCompensator", "LinearShuntCompensator"]
class ShuntCompensator(RegulatingCondEq):
"""
A shunt capacitor or reactor or switchable bank of shunt capacitors or reactors. A section of a shunt compensator
is an individual capacitor or reactor. A negative value for reactivePerSection indicates that the compensator is
a reactor. ShuntCompensator is a single terminal device. Ground is implied.
"""
grounded: bool = False
"""Used for Yn and Zn connections. True if the neutral is solidly grounded. nom_u : The voltage at which the nominal reactive power may be calculated.
This should normally be within 10% of the voltage at which the capacitor is connected to the network."""
nom_u: int = 0
"""The voltage at which the nominal reactive power may be calculated. This should normally be within 10% of the voltage at which the capacitor is connected
to the network."""
phase_connection: PhaseShuntConnectionKind = PhaseShuntConnectionKind.UNKNOWN
"""The type of phase connection, such as wye or delta."""
sections: float = 0.0
"""
Shunt compensator sections in use. Starting value for steady state solution. Non integer values are allowed to support continuous variables. The
reasons for continuous value are to support study cases where no discrete shunt compensator's has yet been designed, a solutions where a narrow voltage
band force the sections to oscillate or accommodate for a continuous solution as input.
For `LinearShuntCompensator` the value shall be between zero and `ShuntCompensator.maximumSections`. At value zero the shunt compensator conductance and
admittance is zero. Linear interpolation of conductance and admittance between the previous and next integer section is applied in case of non-integer
values.
For `NonlinearShuntCompensator`s shall only be set to one of the NonlinearShuntCompensatorPoint.sectionNumber. There is no interpolation between
NonlinearShuntCompensatorPoint-s.
"""
class LinearShuntCompensator(ShuntCompensator):
"""A linear shunt compensator has banks or sections with equal admittance values."""
b0_per_section: float = 0.0
"""Zero sequence shunt (charging) susceptance per section"""
b_per_section: float = 0.0
"""Positive sequence shunt (charging) susceptance per section"""
g0_per_section: float = 0.0
"""Zero sequence shunt (charging) conductance per section"""
g_per_section: float = 0.0
"""Positive sequence shunt (charging) conductance per section""" | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/wires/shunt_compensator.py | shunt_compensator.py |
from __future__ import annotations
from typing import List
from zepben.cimbend.cim.iec61970.base.core.conducting_equipment import ConductingEquipment
from zepben.cimbend.cim.iec61970.base.wires.single_phase_kind import SinglePhaseKind
__all__ = ["Switch", "Breaker", "Disconnector", "Jumper", "Fuse", "ProtectedSwitch", "Recloser"]
from zepben.cimbend.util import require
def _calculate_open_state(current_state: int, is_open: bool, phase: SinglePhaseKind = None) -> int:
require(phase != SinglePhaseKind.NONE and phase != SinglePhaseKind.INVALID, lambda: f"Invalid phase {phase} specified")
if phase is None:
return 0b1111 if is_open else 0
else:
return current_state | phase.bit_mask if is_open else current_state & ~phase.bit_mask
def _check_open(current_state: int, phase: SinglePhaseKind = None) -> bool:
require(phase != SinglePhaseKind.NONE and phase != SinglePhaseKind.INVALID, lambda: f"Invalid phase {phase} specified")
if phase is None:
return current_state != 0
else:
return (current_state & phase.bit_mask) != 0
class Switch(ConductingEquipment):
"""
A generic device designed to close, or open, or both, one or more electric circuits.
All switches are two terminal devices including grounding switches.
NOTE: The normal and currently open properties are implemented as an integer rather than a boolean to allow for the caching of
measurement values if the switch is operating un-ganged. These values will cache the latest values from the measurement
value for each phase of the switch.
"""
_open: int = 0
"""Tells if the switch is considered open when used as input to topology processing."""
_normal_open: int = 0
"""The attribute is used in cases when no Measurement for the status value is present. If the Switch has a status measurement the Discrete.normalValue
is expected to match with the Switch.normalOpen."""
def is_normally_open(self, phase: SinglePhaseKind = None):
"""
Check if the switch is normally open on `phase`.
`phase` The `single_phase_kind.SinglePhaseKind` to check the normal status. A `phase` of `None` (default) checks if any phase is open.
Returns True if `phase` is open in its normal state, False if it is closed
"""
return _check_open(self._normal_open, phase)
def get_normal_state(self) -> int:
"""
Get the underlying normal open states. Stored as 4 bits, 1 per phase.
"""
return self._normal_open
def is_open(self, phase: SinglePhaseKind = None):
"""
Check if the switch is currently open on `phase`.
`phase` The `zepben.cimbend.cim.iec61970.base.wires.single_phase_kind.SinglePhaseKind` to check the current status. A `phase` of `None` (default) checks
if any phase is open.
Returns True if `phase` is open in its current state, False if it is closed
"""
return _check_open(self._open, phase)
def get_state(self) -> int:
"""
The attribute tells if the switch is considered open when used as input to topology processing.
Get the underlying open states. Stored as 4 bits, 1 per phase.
"""
return self._open
def set_normally_open(self, is_normally_open: bool, phase: SinglePhaseKind = None) -> Switch:
"""
`is_normally_open` indicates if the phase(s) should be opened.
`phase` the phase to set the normal status. If set to None will default to all phases.
Returns This `Switch` to be used fluently.
"""
self._normal_open = _calculate_open_state(self._normal_open, is_normally_open, phase)
return self
def set_open(self, is_open: bool, phase: SinglePhaseKind = None) -> Switch:
"""
`is_open` indicates if the phase(s) should be opened.
`phase` the phase to set the current status. If set to None will default to all phases.
Returns This `Switch` to be used fluently.
"""
self._open = _calculate_open_state(self._open, is_open, phase)
return self
class ProtectedSwitch(Switch):
"""
A ProtectedSwitch is a switching device that can be operated by ProtectionEquipment.
"""
pass
class Breaker(ProtectedSwitch):
"""
A mechanical switching device capable of making, carrying, and breaking currents under normal circuit conditions
and also making, carrying for a specified time, and breaking currents under specified abnormal circuit conditions
e.g. those of short circuit.
"""
def is_substation_breaker(self):
"""Convenience function for detecting if this breaker is part of a substation. Returns true if this Breaker is associated with a Substation."""
return self.num_substations() > 0
class Disconnector(Switch):
"""
A manually operated or motor operated mechanical switching device used for changing the connections in a circuit,
or for isolating a circuit or equipment from a source of power. It is required to open or close circuits when
negligible current is broken or made.
"""
pass
class Fuse(Switch):
"""
An overcurrent protective device with a circuit opening fusible part that is heated and severed by the passage of
overcurrent through it. A fuse is considered a switching device because it breaks current.
"""
pass
class Jumper(Switch):
"""
A short section of conductor with negligible impedance which can be manually removed and replaced if the circuit is de-energized.
Note that zero-impedance branches can potentially be modeled by other equipment types.
"""
pass
class Recloser(ProtectedSwitch):
"""
Pole-mounted fault interrupter with built-in phase and ground relays, current transformer (CT), and supplemental controls.
"""
pass | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/wires/switch.py | switch.py |
from __future__ import annotations
from dataclassy import dataclass
from typing import List, Optional, Dict, Generator, Tuple
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_object_style import DiagramObjectStyle
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_style import DiagramStyle
from zepben.cimbend.cim.iec61970.base.diagramlayout.orientation_kind import OrientationKind
from zepben.cimbend.util import nlen, require, contains_mrid, ngen, safe_remove
__all__ = ["DiagramObjectPoint", "Diagram", "DiagramObject"]
@dataclass(slots=True)
class DiagramObjectPoint(object):
"""
A point in a given space defined by 3 coordinates and associated to a diagram object. The coordinates may be positive
or negative as the origin does not have to be in the corner of a diagram.
"""
x_position: float
"""The X coordinate of this point."""
y_position: float
"""The Y coordinate of this point."""
def __str__(self):
return f"x:{self.x_position}|y:{self.y_position}"
class DiagramObject(IdentifiedObject):
"""
An object that defines one or more points in a given space. This object can be associated with anything
that specializes IdentifiedObject. For single line diagrams such objects typically include such items as
analog values, breakers, disconnectors, power transformers, and transmission lines.
"""
_diagram: Optional[Diagram] = None
"""A diagram object is part of a diagram."""
identified_object_mrid: Optional[str] = None
"""The domain object to which this diagram object is associated."""
style: DiagramObjectStyle = DiagramObjectStyle.NONE
"""A diagram object has a style associated that provides a reference for the style used in the originating system."""
rotation: float = 0.0
"""Sets the angle of rotation of the diagram object. Zero degrees is pointing to the top of the diagram. Rotation is clockwise."""
_diagram_object_points: Optional[List[DiagramObjectPoint]] = None
def __init__(self, diagram: Diagram = None, diagram_object_points: List[DiagramObjectPoint] = None):
self.diagram = diagram
if diagram_object_points:
for point in diagram_object_points:
self.add_point(point)
@property
def diagram(self):
return self._diagram
@diagram.setter
def diagram(self, diag):
if self._diagram is None or self._diagram is diag:
self._diagram = diag
else:
raise ValueError(f"diagram for {str(self)} has already been set to {self._diagram}, cannot reset this field to {diag}")
def num_points(self):
"""
Returns the number of `DiagramObjectPoint`s associated with this `DiagramObject`
"""
return nlen(self._diagram_object_points)
@property
def points(self) -> Generator[DiagramObjectPoint, None, None]:
"""
The `DiagramObjectPoint`s for this `DiagramObject`.
"""
return ngen(self._diagram_object_points)
def get_point(self, sequence_number: int) -> DiagramObjectPoint:
"""
Get the `DiagramObjectPoint` for this `DiagramObject` represented by `sequence_number` .
A diagram object can have 0 or more points to reflect its layout position, routing (for polylines) or boundary (for polygons).
Index in the underlying points collection corresponds to the sequence number
`sequence_number` The sequence number of the `DiagramObjectPoint` to get.
Returns The `DiagramObjectPoint` identified by `sequence_number`
Raises IndexError if this `DiagramObject` didn't contain `sequence_number` points.
"""
if self._diagram_object_points is not None:
return self._diagram_object_points[sequence_number]
else:
raise IndexError(sequence_number)
def __getitem__(self, item: int) -> DiagramObjectPoint:
return self.get_point(item)
def add_point(self, point: DiagramObjectPoint) -> DiagramObject:
"""
Associate a `DiagramObjectPoint` with this `DiagramObject`, assigning it a sequence_number of `num_points`.
`point` The `DiagramObjectPoint` to associate with this `DiagramObject`.
Returns A reference to this `DiagramObject` to allow fluent use.
"""
return self.insert_point(point)
def insert_point(self, point: DiagramObjectPoint, sequence_number: int = None) -> DiagramObject:
"""
Associate a `DiagramObjectPoint` with this `DiagramObject`
`point` The `DiagramObjectPoint` to associate with this `DiagramObject`.
`sequence_number` The sequence number of the `DiagramObjectPoint`.
Returns A reference to this `DiagramObject` to allow fluent use.
Raises `ValueError` if `sequence_number` < 0 or > `num_points()`.
"""
if sequence_number is None:
sequence_number = self.num_points()
require(0 <= sequence_number <= self.num_points(),
lambda: f"Unable to add DiagramObjectPoint to {str(self)}. Sequence number {sequence_number}"
f" is invalid. Expected a value between 0 and {self.num_points}. Make sure you are "
f"adding the points in the correct order and there are no missing sequence numbers.")
self._diagram_object_points = list() if self._diagram_object_points is None else self._diagram_object_points
self._diagram_object_points.insert(sequence_number, point)
return self
def __setitem__(self, key, value):
self.insert_point(value, key)
def remove_point(self, point: DiagramObjectPoint) -> DiagramObject:
"""
Disassociate `point` from this `DiagramObject`
`point` The `DiagramObjectPoint` to disassociate from this `DiagramObject`.
Returns A reference to this `DiagramObject` to allow fluent use.
Raises `ValueError` if `point` was not associated with this `DiagramObject`.
"""
self._diagram_object_points = safe_remove(self._diagram_object_points, point)
return self
def clear_points(self) -> DiagramObject:
"""
Clear all points.
Returns A reference to this `DiagramObject` to allow fluent use.
"""
self._diagram_object_points = None
return self
class Diagram(IdentifiedObject):
"""
The diagram being exchanged. The coordinate system is a standard Cartesian coordinate system and the orientation
attribute defines the orientation.
"""
diagram_style: DiagramStyle = DiagramStyle.SCHEMATIC
"""A Diagram may have a DiagramStyle."""
orientation_kind: OrientationKind = OrientationKind.POSITIVE
"""Coordinate system orientation of the diagram."""
_diagram_objects: Optional[Dict[str, DiagramObject]] = None
def __init__(self, diagram_objects: List[DiagramObject] = None):
if diagram_objects:
for obj in diagram_objects:
self.add_object(obj)
def num_objects(self):
"""
Returns The number of `DiagramObject`s associated with this `Diagram`
"""
return nlen(self._diagram_objects)
@property
def diagram_objects(self) -> Generator[DiagramObject, None, None]:
"""
The diagram objects belonging to this diagram.
"""
return ngen(self._diagram_objects.values() if self._diagram_objects is not None else None)
def get_object(self, mrid: str) -> DiagramObject:
"""
Get the `DiagramObject` for this `Diagram` identified by `mrid`
`mrid` the mRID of the required `DiagramObject`
Returns The `DiagramObject` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return self._diagram_objects[mrid]
def add_object(self, diagram_object: DiagramObject) -> DiagramObject:
"""
Associate a `DiagramObject` with this `Diagram`.
`diagram_object` the `DiagramObject` to associate with this `Diagram`.
Returns The previous `DiagramObject` stored by `diagram_object`s mrid, otherwise `diagram_object` is returned
if there was no previous value.
Raises `ValueError` if another `DiagramObject` with the same `mrid` already exists for this `Diagram`, or if `diagram_object.diagram` is not this
`Diagram`.
"""
require(diagram_object.diagram is self, lambda: f"{str(diagram_object)} references another Diagram "
f"{str(diagram_object.diagram)}, expected {str(self)}.")
require(not contains_mrid(self._diagram_objects, diagram_object.mrid),
lambda: f"A DiagramObject with mRID ${diagram_object.mrid} already exists in {str(self)}.")
self._diagram_objects = dict() if self._diagram_objects is None else self._diagram_objects
return self._diagram_objects.setdefault(diagram_object.mrid, diagram_object)
def remove_object(self, diagram_object: DiagramObject) -> Diagram:
"""
Disassociate `diagram_object` from this `Diagram`
`diagram_object` the `DiagramObject` to disassociate with this `Diagram`.
Returns A reference to this `Diagram` to allow fluent use.
Raises `KeyError` if `diagram_object` was not associated with this `Diagram`.
"""
if self._diagram_objects:
del self._equipment[diagram_object.mrid]
else:
raise KeyError(diagram_object)
if not self._diagram_objects:
self._diagram_objects = None
return self
def clear_objects(self) -> Diagram:
"""
Clear all `DiagramObject`s.
Returns A reference to this `Diagram` to allow fluent use.
"""
self._diagram_objects = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/diagramlayout/diagram_layout.py | diagram_layout.py |
from enum import Enum, auto
__all__ = ["DiagramObjectStyle"]
class DiagramObjectStyle(Enum):
"""
The diagram style refer to a style used by the originating system for a diagram. A diagram style describes
information such as schematic, geographic, bus-branch etc.
"""
NONE = (auto(), False)
"""No specific styling should be applied."""
DIST_TRANSFORMER = (auto(), False)
"""Diagram object should be styled as a distribution transformer."""
ISO_TRANSFORMER = (auto(), False)
"""Diagram object should be styled as an isolating transformer."""
REVERSIBLE_REGULATOR = (auto(), False)
"""Diagram object should be styled as a reversible regulator transformer."""
NON_REVERSIBLE_REGULATOR = (auto(), False)
"""Diagram object should be styled as a non-reversiable transformer."""
ZONE_TRANSFORMER = (auto(), False)
"""Diagram object should be styled as a zone transformer."""
FEEDER_CB = (auto(), False)
"""Diagram object should be styled as a feeder circuit breaker."""
CB = (auto(), False)
"""Diagram object should be styled as a circuit breaker."""
JUNCTION = (auto(), False)
"""Diagram object should be styled as a junction."""
DISCONNECTOR = (auto(), False)
"""Diagram object should be styled as a disconnector."""
FUSE = (auto(), False)
"""Diagram object should be styled as a fuse."""
RECLOSER = (auto(), False)
"""Diagram object should be styled as a recloser."""
FAULT_INDICATOR = (auto(), False)
"""Diagram object should be styled as a fault indicator."""
JUMPER = (auto(), False)
"""Diagram object should be styled as a jumper."""
ENERGY_SOURCE = (auto(), False)
"""Diagram object should be styled as a energy source."""
SHUNT_COMPENSATOR = (auto(), False)
"""Diagram object should be styled as a shunt compensator."""
USAGE_POINT = (auto(), False)
"""Diagram object should be styled as a usage point."""
CONDUCTOR_UNKNOWN = (auto(), True)
"""Diagram object should be styled as a conductor at unknown voltage."""
CONDUCTOR_LV = (auto(), True)
"""Diagram object should be styled as a conductor at low voltage."""
CONDUCTOR_6600 = (auto(), True)
"""Diagram object should be styled as a conductor at 6.6kV."""
CONDUCTOR_11000 = (auto(), True)
"""Diagram object should be styled as a conductor at 11kV."""
CONDUCTOR_12700 = (auto(), True)
"""Diagram object should be styled as a conductor at 12.7kV (SWER)."""
CONDUCTOR_22000 = (auto(), True)
"""Diagram object should be styled as a conductor at 22kV."""
CONDUCTOR_33000 = (auto(), True)
"""Diagram object should be styled as a conductor at 33kV."""
CONDUCTOR_66000 = (auto(), True)
"""Diagram object should be styled as a conductor at 66kV."""
CONDUCTOR_132000 = (auto(), True)
"""Diagram object should be styled as a conductor at 132kV."""
CONDUCTOR_220000 = (auto(), True)
"""Diagram object should be styled as a conductor at 220kV."""
CONDUCTOR_275000 = (auto(), True)
"""Diagram object should be styled as a conductor at 275kV."""
CONDUCTOR_500000 = (auto(), True)
"""Diagram object should be styled as a conductor at 500kV or above."""
def is_line_style(self) -> bool:
return self.value[1]
@property
def short_name(self):
return str(self)[19:] | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/diagramlayout/diagram_object_style.py | diagram_object_style.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61970.base.core.equipment_container import Feeder, Site
from zepben.cimbend.cim.iec61970.base.core.power_system_resource import PowerSystemResource
from zepben.cimbend.cim.iec61970.base.core.substation import Substation
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
__all__ = ['Equipment']
class Equipment(PowerSystemResource):
"""
Abstract class, should only be used through subclasses.
Any part of a power system that is a physical device, electronic or mechanical.
"""
in_service: bool = True
"""If True, the equipment is in service."""
normally_in_service: bool = True
"""If True, the equipment is _normally_ in service."""
_usage_points: Optional[List[UsagePoint]] = None
_equipment_containers: Optional[List[EquipmentContainer]] = None
_operational_restrictions: Optional[List[OperationalRestriction]] = None
_current_feeders: Optional[List[Feeder]] = None
def __init__(self, usage_points: List[UsagePoint] = None, equipment_containers: List[EquipmentContainer] = None,
operational_restrictions: List[OperationalRestriction] = None, current_feeders: List[Feeder] = None):
if usage_points:
for up in usage_points:
self.add_usage_point(up)
if equipment_containers:
for container in equipment_containers:
self.add_container(container)
if operational_restrictions:
for restriction in operational_restrictions:
self.add_restriction(restriction)
if current_feeders:
for cf in current_feeders:
self.add_current_feeder(cf)
@property
def equipment_containers(self) -> Generator[Equipment, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer`s this equipment belongs to.
"""
return ngen(self._equipment_containers)
@property
def current_feeders(self) -> Generator[Feeder, None, None]:
"""
The current `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`s this equipment belongs to.
"""
return ngen(self._current_feeders)
@property
def normal_feeders(self) -> Generator[Feeder, None, None]:
"""
The normal `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`s this equipment belongs to.
"""
for feeder in self._equipment_containers_of_type(Feeder):
yield feeder
@property
def sites(self) -> Generator[Site, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Site`s this equipment belongs to.
"""
for site in self._equipment_containers_of_type(Site):
yield site
@property
def substations(self) -> Generator[Substation, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.substation.Substation`s this equipment belongs to.
"""
for sub in self._equipment_containers_of_type(Substation):
yield sub
@property
def usage_points(self) -> Generator[UsagePoint, None, None]:
"""
The `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint`s for this equipment.
"""
return ngen(self._usage_points)
@property
def operational_restrictions(self) -> Generator[OperationalRestriction, None, None]:
"""
The `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction`s that this equipment is associated with.
"""
return ngen(self._operational_restrictions)
def num_equipment_containers(self) -> int:
"""
Returns The number of `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer`s associated with this `Equipment`
"""
return nlen(self._equipment_containers)
def num_substations(self) -> int:
"""
Returns The number of `zepben.cimbend.cim.iec61970.base.core.substation.Substation`s associated with this `Equipment`
"""
return len(self._equipment_containers_of_type(Substation))
def num_sites(self) -> int:
"""
Returns The number of `zepben.cimbend.cim.iec61970.base.core.equipment_container.Site`s associated with this `Equipment`
"""
return len(self._equipment_containers_of_type(Site))
def num_normal_feeders(self) -> int:
"""
Returns The number of normal `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`s associated with this `Equipment`
"""
return len(self._equipment_containers_of_type(Feeder))
def num_usage_points(self) -> int:
"""
Returns The number of `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint`s associated with this `Equipment`
"""
return nlen(self._usage_points)
def num_current_feeders(self) -> int:
"""
Returns The number of `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`s associated with this `Equipment`
"""
return nlen(self._current_feeders)
def num_restrictions(self) -> int:
"""
Returns The number of `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction`s associated with this `Equipment`
"""
return nlen(self._operational_restrictions)
def get_container(self, mrid: str) -> Equipment:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer` for this `Equipment` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer`
Returns The `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._equipment_containers, mrid)
def add_container(self, ec: EquipmentContainer) -> Equipment:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer` with this `Equipment`
`ec` The `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer` to associate with this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if another `EquipmentContainer` with the same `mrid` already exists for this `Equipment`.
"""
if self._validate_reference(ec, self.get_container, "An EquipmentContainer"):
return self
self._equipment_containers = list() if self._equipment_containers is None else self._equipment_containers
self._equipment_containers.append(ec)
return self
def remove_containers(self, ec: EquipmentContainer) -> Equipment:
"""
Disassociate `ec` from this `Equipment`.
`ec` The `zepben.cimbend.cim.iec61970.base.core.equipment_container.EquipmentContainer` to disassociate from this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if `ec` was not associated with this `Equipment`.
"""
self._equipment_containers = safe_remove(self._equipment_containers, ec)
return self
def clear_containers(self) -> Equipment:
"""
Clear all equipment.
Returns A reference to this `Equipment` to allow fluent use.
"""
self._equipment_containers = None
return self
def get_current_feeder(self, mrid: str) -> Equipment:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` for this `Equipment` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`
Returns The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._current_feeders, mrid)
def add_current_feeder(self, feeder: Feeder) -> Equipment:
"""
Associate `feeder` with this `Equipment`.
`feeder` The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` to associate with this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if another `Feeder` with the same `mrid` already exists for this `Equipment`.
"""
if self._validate_reference(feeder, self.get_current_feeder, "A Feeder"):
return self
self._current_feeders = list() if self._current_feeders is None else self._current_feeders
self._current_feeders.append(feeder)
return self
def remove_current_feeder(self, feeder: Feeder) -> Equipment:
"""
Disassociate `feeder` from this `Equipment`
`feeder` The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` to disassociate from this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if `feeder` was not associated with this `Equipment`.
"""
self._current_feeders = safe_remove(self._current_feeders, feeder)
return self
def clear_current_feeders(self) -> Equipment:
"""
Clear all current `Feeder`s.
Returns A reference to this `Equipment` to allow fluent use.
"""
self._current_feeders = None
return self
def get_usage_point(self, mrid: str) -> UsagePoint:
"""
Get the `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` for this `Equipment` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint`
Returns The `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._usage_points, mrid)
def add_usage_point(self, up: UsagePoint) -> Equipment:
"""
Associate `up` with this `Equipment`.
`up` the `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` to associate with this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if another `UsagePoint` with the same `mrid` already exists for this `Equipment`.
"""
if self._validate_reference(up, self.get_usage_point, "A UsagePoint"):
return self
self._usage_points = list() if self._usage_points is None else self._usage_points
self._usage_points.append(up)
return self
def remove_usage_point(self, up: UsagePoint) -> Equipment:
"""
Disassociate `up` from this `Equipment`.
`up` The `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` to disassociate from this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if `up` was not associated with this `Equipment`.
"""
self._usage_points = safe_remove(self._usage_points, up)
return self
def clear_usage_points(self) -> Equipment:
"""
Clear all usage_points.
Returns A reference to this `Equipment` to allow fluent use.
"""
self._usage_points = None
return self
def get_restriction(self, mrid: str) -> OperationalRestriction:
"""
Get the `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction` for this `Equipment` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction`
Returns The `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._operational_restrictions, mrid)
def add_restriction(self, op: OperationalRestriction) -> Equipment:
"""
Associate `op` with this `Equipment`.
`op` The `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction` to associate with this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if another `OperationalRestriction` with the same `mrid` already exists for this `Equipment`.
"""
if self._validate_reference(op, self.get_restriction, "An OperationalRestriction"):
return self
self._operational_restrictions = list() if self._operational_restrictions is None else self._operational_restrictions
self._operational_restrictions.append(op)
return self
def remove_restriction(self, op: OperationalRestriction) -> Equipment:
"""
Disassociate `up` from this `Equipment`.
`op` The `zepben.cimbend.cim.iec61968.operations.operational_restriction.OperationalRestriction` to disassociate from this `Equipment`.
Returns A reference to this `Equipment` to allow fluent use.
Raises `ValueError` if `op` was not associated with this `Equipment`.
"""
self._operational_restrictions = safe_remove(self._operational_restrictions, op)
return self
def clear_restrictions(self) -> Equipment:
"""
Clear all `OperationalRestrictions`.
Returns A reference to this `Equipment` to allow fluent use.
"""
self._operational_restrictions = None
return self
def _equipment_containers_of_type(self, ectype: type) -> List[EquipmentContainer]:
"""Get the `EquipmentContainer`s for this `Equipment` of type `ectype`"""
if self._equipment_containers:
return [ec for ec in self._equipment_containers if isinstance(ec, ectype)]
else:
return [] | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/equipment.py | equipment.py |
from __future__ import annotations
from typing import Optional
from weakref import ref, ReferenceType
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.cim.iec61970.base.core.phase_code import PhaseCode
from zepben.cimbend.model.phases import TracedPhases
__all__ = ["AcDcTerminal", "Terminal"]
class AcDcTerminal(IdentifiedObject):
"""
An electrical connection point (AC or DC) to a piece of conducting equipment. Terminals are connected at physical
connection points called connectivity nodes.
"""
pass
class Terminal(AcDcTerminal):
"""
An AC electrical connection point to a piece of conducting equipment. Terminals are connected at physical connection points called connectivity nodes.
"""
_conducting_equipment: Optional[ConductingEquipment] = None
"""The conducting equipment of the terminal. Conducting equipment have terminals that may be connected to other conducting equipment terminals via
connectivity nodes."""
phases: PhaseCode = PhaseCode.ABC
"""Represents the normal network phasing condition. If the attribute is missing three phases (ABC) shall be assumed."""
sequence_number: int = 0
"""The orientation of the terminal connections for a multiple terminal conducting equipment. The sequence numbering starts with 1 and additional
terminals should follow in increasing order. The first terminal is the "starting point" for a two terminal branch."""
traced_phases: TracedPhases = TracedPhases()
"""the phase object representing the traced phases in both the normal and current network. If properly configured you would expect the normal state phases
to match those in `phases`"""
_cn: ReferenceType = None
"""This is a weak reference to the connectivity node so if a Network object goes out of scope, holding a single conducting equipment
reference does not cause everything connected to it in the network to stay in memory."""
def __init__(self, conducting_equipment: ConductingEquipment = None, connectivity_node: ConnectivityNode = None):
self.conducting_equipment = conducting_equipment
if connectivity_node:
self.connectivity_node = connectivity_node
@property
def conducting_equipment(self):
"""
The conducting equipment of the terminal. Conducting equipment have terminals that may be connected to other conducting equipment terminals via
connectivity nodes.
"""
return self._conducting_equipment
@conducting_equipment.setter
def conducting_equipment(self, ce):
if self._conducting_equipment is None or self._conducting_equipment is ce:
self._conducting_equipment = ce
else:
raise ValueError(f"conducting_equipment for {str(self)} has already been set to {self._conducting_equipment}, cannot reset this field to {ce}")
@property
def connectivity_node(self):
try:
return self._cn()
except TypeError:
return None
@connectivity_node.setter
def connectivity_node(self, cn):
self._cn = ref(cn)
@property
def connected(self) -> bool:
if self.connectivity_node:
return True
return False
@property
def connectivity_node_id(self):
return self.connectivity_node.mrid if self.connectivity_node is not None else None
def __repr__(self):
return f"Terminal{{{self.mrid}}}"
def get_switch(self):
"""
Get any associated switch for this Terminal
Returns Switch if present in this terminals ConnectivityNode, else None
"""
return self.connectivity_node.get_switch()
@property
def base_voltage(self):
return self.conducting_equipment.get_base_voltage(self)
def get_other_terminals(self):
return [t for t in self.conducting_equipment.terminals if t is not self]
def connect(self, connectivity_node: ConnectivityNode):
self.connectivity_node = connectivity_node
def disconnect(self):
self.connectivity_node = None | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/terminal.py | terminal.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
__all__ = ["GeographicalRegion", "SubGeographicalRegion"]
class GeographicalRegion(IdentifiedObject):
"""
A geographical region of a power system network phases.
"""
_sub_geographical_regions: Optional[List[SubGeographicalRegion]] = None
def __init__(self, sub_geographical_regions: List[SubGeographicalRegion] = None):
if sub_geographical_regions:
for sgr in sub_geographical_regions:
self.add_sub_geographical_region(sgr)
def num_sub_geographical_regions(self) -> int:
"""
Returns The number of `SubGeographicalRegion`s associated with this `GeographicalRegion`
"""
return nlen(self._sub_geographical_regions)
@property
def sub_geographical_regions(self) -> Generator[SubGeographicalRegion, None, None]:
"""
The `SubGeographicalRegion`s of this `GeographicalRegion`.
"""
return ngen(self._sub_geographical_regions)
def get_sub_geographical_region(self, mrid: str) -> SubGeographicalRegion:
"""
Get the `SubGeographicalRegion` for this `GeographicalRegion` identified by `mrid`
`mrid` The mRID of the required `SubGeographicalRegion`
Returns The `SubGeographicalRegion` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._sub_geographical_regions, mrid)
def add_sub_geographical_region(self, sub_geographical_region: SubGeographicalRegion) -> GeographicalRegion:
"""
Associate a `SubGeographicalRegion` with this `GeographicalRegion`
`sub_geographical_region` The `SubGeographicalRegion` to associate with this `GeographicalRegion`.
Returns A reference to this `GeographicalRegion` to allow fluent use.
Raises `ValueError` if another `SubGeographicalRegion` with the same `mrid` already exists for this `GeographicalRegion`.
"""
if self._validate_reference(sub_geographical_region, self.get_sub_geographical_region, "A SubgeographicalRegion"):
return self
self._sub_geographical_regions = list() if self._sub_geographical_regions is None else self._sub_geographical_regions
self._sub_geographical_regions.append(sub_geographical_region)
return self
def remove_sub_geographical_region(self, sub_geographical_region: SubGeographicalRegion) -> GeographicalRegion:
"""
Disassociate `sub_geographical_region` from this `GeographicalRegion`
`sub_geographical_region` The `SubGeographicalRegion` to disassociate from this `GeographicalRegion`.
Returns A reference to this `GeographicalRegion` to allow fluent use.
Raises `ValueError` if `sub_geographical_region` was not associated with this `GeographicalRegion`.
"""
self._sub_geographical_regions = safe_remove(self._sub_geographical_regions, sub_geographical_region)
return self
def clear_sub_geographical_regions(self) -> GeographicalRegion:
"""
Clear all SubGeographicalRegions.
Returns A reference to this `GeographicalRegion` to allow fluent use.
"""
self._sub_geographical_regions = None
return self
class SubGeographicalRegion(IdentifiedObject):
"""
A subset of a geographical region of a power system network model.
"""
geographical_region: Optional[GeographicalRegion] = None
"""The geographical region to which this sub-geographical region is within."""
_substations: Optional[List[Substation]] = None
def __init__(self, substations: List[Substation] = None):
if substations:
for sub in substations:
self.add_substation(sub)
def num_substations(self) -> int:
"""
Returns The number of `zepben.cimbend.iec61970.base.core.substation.Substation`s associated with this `SubGeographicalRegion`
"""
return nlen(self._substations)
@property
def substations(self) -> Generator[Substation, None, None]:
"""
All substations belonging to this sub geographical region.
"""
return ngen(self._substations)
def get_substation(self, mrid: str) -> Substation:
"""
Get the `zepben.cimbend.iec61970.base.core.substation.Substation` for this `SubGeographicalRegion` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.iec61970.base.core.substation.Substation`
Returns The `zepben.cimbend.iec61970.base.core.substation.Substation` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._substations, mrid)
def add_substation(self, substation: Substation) -> SubGeographicalRegion:
"""
Associate a `Substation` with this `GeographicalRegion`
`substation` the `zepben.cimbend.iec61970.base.core.substation.Substation` to associate with this `SubGeographicalRegion`.
Returns A reference to this `SubGeographicalRegion` to allow fluent use.
Raises `ValueError` if another `zepben.cimbend.iec61970.base.core.substation.Substation` with the same `mrid` already exists for this `GeographicalRegion`.
"""
if self._validate_reference(substation, self.get_substation, "A Substation"):
return self
self._substations = list() if self._substations is None else self._substations
self._substations.append(substation)
return self
def remove_substation(self, substation: Substation) -> SubGeographicalRegion:
"""
Disassociate `substation` from this `GeographicalRegion`
`substation` The `zepben.cimbend.iec61970.base.core.substation.Substation` to disassociate from this `SubGeographicalRegion`.
Returns A reference to this `SubGeographicalRegion` to allow fluent use.
Raises `ValueError` if `substation` was not associated with this `SubGeographicalRegion`.
"""
self._substations = safe_remove(self._substations, substation)
return self
def clear_substations(self) -> SubGeographicalRegion:
"""
Clear all `Substations`.
Returns A reference to this `SubGeographicalRegion` to allow fluent use.
"""
self._substations = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/regions.py | regions.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61970.base.core.equipment_container import EquipmentContainer
from zepben.cimbend.cim.iec61970.base.core.regions import SubGeographicalRegion
from zepben.cimbend.util import nlen, get_by_mrid, contains_mrid, require, ngen, safe_remove
__all__ = ["Substation"]
class Substation(EquipmentContainer):
"""
A collection of equipment for purposes other than generation or utilization, through which electric energy in bulk
is passed for the purposes of switching or modifying its characteristics.
"""
sub_geographical_region: Optional[SubGeographicalRegion] = None
"""The SubGeographicalRegion containing the substation."""
_normal_energized_feeders: Optional[List[Feeder]] = None
_loops: Optional[List[Loop]] = None
_energized_loops: Optional[List[Loop]] = None
_circuits: Optional[List[Circuit]] = None
def __init__(self, equipment: List[Equipment] = None, normal_energized_feeders: List[Feeder] = None, loops: List[Loop] = None,
energized_loops: List[Loop] = None, circuits: List[Circuit] = None):
super(Substation, self).__init__(equipment)
if normal_energized_feeders:
for feeder in normal_energized_feeders:
self.add_feeder(feeder)
if loops:
for loop in loops:
self.add_loop(loop)
if energized_loops:
for loop in energized_loops:
self.add_energized_loop(loop)
if circuits:
for circuit in circuits:
self.add_circuit(circuit)
@property
def circuits(self) -> Generator[Circuit, None, None]:
"""
The `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit`s originating from this substation.
"""
return ngen(self._circuits)
@property
def loops(self) -> Generator[Loop, None, None]:
"""
The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` originating from this substation.
"""
return ngen(self._loops)
@property
def energized_loops(self) -> Generator[Loop, None, None]:
"""
The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop`s originating from this substation that are energised.
"""
return ngen(self._energized_loops)
@property
def feeders(self) -> Generator[Feeder, None, None]:
"""
The normal energized feeders of the substation. Also used for naming purposes.
"""
return ngen(self._normal_energized_feeders)
def num_feeders(self):
"""
Returns The number of `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`s associated with this `Substation`
"""
return nlen(self._normal_energized_feeders)
def get_feeder(self, mrid: str) -> Substation:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` for this `Substation` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder`
Returns The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._normal_energized_feeders, mrid)
def add_feeder(self, feeder: Feeder) -> Substation:
"""
Associate a `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` with this `Substation`
`feeder` The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` to associate with this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if another `Feeder` with the same `mrid` already exists for this `Substation`.
"""
if self._validate_reference(feeder, self.get_feeder, "A Feeder"):
return self
self._normal_energized_feeders = list() if self._normal_energized_feeders is None else self._normal_energized_feeders
self._normal_energized_feeders.append(feeder)
return self
def remove_feeder(self, feeder: Feeder) -> Substation:
"""
Disassociate `feeder` from this `Substation`
`feeder` The `zepben.cimbend.cim.iec61970.base.core.equipment_container.Feeder` to disassociate from this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if `feeder` was not associated with this `Substation`.
"""
self._normal_energized_feeders = safe_remove(self._normal_energized_feeders, feeder)
return self
def clear_feeders(self) -> Substation:
"""
Clear all current `Feeder`s.
Returns A reference to this `Substation` to allow fluent use.
"""
self._normal_energized_feeders = None
return self
def num_loops(self):
"""
Returns The number of `zepben.cimbend.cim.infiec61970.feeder.loop.Loop`s associated with this `Substation`
"""
return nlen(self._loops)
def get_loop(self, mrid: str) -> Substation:
"""
Get the `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` for this `Substation` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.infiec61970.feeder.loop.Loop`
Returns The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._loops, mrid)
def add_loop(self, loop: Loop) -> Substation:
"""
Associate a `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` with this `Substation`
`loop` The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` to associate with this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if another `Loop` with the same `mrid` already exists for this `Substation`.
"""
if self._validate_reference(loop, self.get_loop, "A Loop"):
return self
self._loops = list() if self._loops is None else self._loops
self._loops.append(loop)
return self
def remove_loop(self, loop: Loop) -> Substation:
"""
Disassociate `loop` from this `Substation`
`loop` The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` to disassociate from this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if `loop` was not associated with this `Substation`.
"""
self._loops = safe_remove(self._loops, loop)
return self
def clear_loops(self) -> Substation:
"""
Clear all current `Loop`s.
Returns A reference to this `Substation` to allow fluent use.
"""
self._loops = None
return self
def num_energized_loops(self):
"""
Returns The number of `zepben.cimbend.cim.infiec61970.feeder.loop.Loop`s associated with this `Substation`
"""
return nlen(self._energized_loops)
def get_energized_loop(self, mrid: str) -> Substation:
"""
Get the `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` for this `Substation` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.infiec61970.feeder.loop.Loop`
Returns The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._energized_loops, mrid)
def add_energized_loop(self, loop: Loop) -> Substation:
"""
Associate a `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` with this `Substation`
`loop` The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` to associate with this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if another `Loop` with the same `mrid` already exists for this `Substation`.
"""
if self._validate_reference(loop, self.get_energized_loop, "A Loop"):
return self
self._energized_loops = list() if self._energized_loops is None else self._energized_loops
self._energized_loops.append(loop)
return self
def remove_energized_loop(self, loop: Loop) -> Substation:
"""
Disassociate `loop` from this `Substation`
`loop` The `zepben.cimbend.cim.infiec61970.feeder.loop.Loop` to disassociate from this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if `loop` was not associated with this `Substation`.
"""
self._energized_loops = safe_remove(self._energized_loops, loop)
return self
def clear_energized_loops(self) -> Substation:
"""
Clear all current `Loop`s.
Returns A reference to this `Substation` to allow fluent use.
"""
self._energized_loops = None
return self
def num_circuits(self):
"""
Returns The number of `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit`s associated with this `Substation`
"""
return nlen(self._circuits)
def get_circuit(self, mrid: str) -> Substation:
"""
Get the `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit` for this `Substation` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit`
Returns The `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._circuits, mrid)
def add_circuit(self, circuit: Circuit) -> Substation:
"""
Associate a `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit` with this `Substation`
`circuit` The `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit` to associate with this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if another `Circuit` with the same `mrid` already exists for this `Substation`.
"""
if self._validate_reference(circuit, self.get_circuit, "A Circuit"):
return self
self._circuits = list() if self._circuits is None else self._circuits
self._circuits.append(circuit)
return self
def remove_circuit(self, circuit: Circuit) -> Substation:
"""
Disassociate `circuit` from this `Substation`
`circuit` The `zepben.cimbend.cim.infiec61970.feeder.circuit.Circuit` to disassociate from this `Substation`.
Returns A reference to this `Substation` to allow fluent use.
Raises `ValueError` if `circuit` was not associated with this `Substation`.
"""
self._circuits = safe_remove(self._circuits, circuit)
return self
def clear_circuits(self) -> Substation:
"""
Clear all current `Circuit`s.
Returns A reference to this `Substation` to allow fluent use.
"""
self._circuits = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/substation.py | substation.py |
from enum import Enum, unique
from zepben.cimbend.cim.iec61970.base.wires.single_phase_kind import SinglePhaseKind
__all__ = ["PhaseCode", "phasecode_by_id"]
def phasecode_by_id(id: int):
return _phasecode_members[id]
@unique
class PhaseCode(Enum):
"""
An unordered enumeration of phase identifiers. Allows designation of phases for both transmission and distribution equipment,
circuits and loads. The enumeration, by itself, does not describe how the phases are connected together or connected to ground.
Ground is not explicitly denoted as a phase.
Residential and small commercial loads are often served from single-phase, or split-phase, secondary circuits. For example of s12N,
phases 1 and 2 refer to hot wires that are 180 degrees out of phase, while N refers to the neutral wire. Through single-phase
transformer connections, these secondary circuits may be served from one or two of the primary phases A, B, and C. For three-phase
loads, use the A, B, C phase codes instead of s12N.
"""
NONE = (SinglePhaseKind.NONE,)
"""No phases specified"""
A = (SinglePhaseKind.A,)
"""Phase A"""
B = (SinglePhaseKind.B,)
"""Phase B"""
C = (SinglePhaseKind.C,)
"""Phase C"""
N = (SinglePhaseKind.N,)
"""Neutral Phase"""
AB = (SinglePhaseKind.A, SinglePhaseKind.B)
"""Phases A and B"""
AC = (SinglePhaseKind.A, SinglePhaseKind.C)
"""Phases A and C"""
AN = (SinglePhaseKind.A, SinglePhaseKind.N)
"""Phases A and N"""
BC = (SinglePhaseKind.B, SinglePhaseKind.C)
"""Phases B and C"""
BN = (SinglePhaseKind.B, SinglePhaseKind.N)
"""Phases B and N"""
CN = (SinglePhaseKind.C, SinglePhaseKind.N)
"""Phases C and N"""
ABC = (SinglePhaseKind.A, SinglePhaseKind.B, SinglePhaseKind.C)
"""Phases A, B and C"""
ABN = (SinglePhaseKind.A, SinglePhaseKind.B, SinglePhaseKind.N)
"""Phases A, B and neutral"""
ACN = (SinglePhaseKind.A, SinglePhaseKind.C, SinglePhaseKind.N)
"""Phases A, C and neutral"""
BCN = (SinglePhaseKind.B, SinglePhaseKind.C, SinglePhaseKind.N)
"""Phases B, C and neutral"""
ABCN = (SinglePhaseKind.A, SinglePhaseKind.B, SinglePhaseKind.C, SinglePhaseKind.N)
"""Phases A, B, C and neutral"""
X = (SinglePhaseKind.X,)
"""Unknown non-neutral phase"""
XN = (SinglePhaseKind.X, SinglePhaseKind.N)
"""Unknown non-neutral phase plus neutral"""
XY = (SinglePhaseKind.X, SinglePhaseKind.Y)
"""Two Unknown non-neutral phases"""
XYN = (SinglePhaseKind.X, SinglePhaseKind.Y, SinglePhaseKind.N)
"""Two Unknown non-neutral phases plus neutral"""
Y = (SinglePhaseKind.Y,)
"""Unknown non-neutral phase"""
YN = (SinglePhaseKind.Y, SinglePhaseKind.N)
"""Unknown non-neutral phase plus neutral"""
@property
def short_name(self):
return str(self)[10:]
@property
def single_phases(self):
return self.value[:1]
@property
def num_phases(self):
return len(self.value)
_phasecode_members = list(PhaseCode.__members__.values()) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/phase_code.py | phase_code.py |
from __future__ import annotations
from typing import List, Set, Optional, Generator, Tuple
from zepben.cimbend.cim.iec61970.base.core.base_voltage import BaseVoltage
from zepben.cimbend.cim.iec61970.base.core.equipment import Equipment
__all__ = ['ConductingEquipment']
from zepben.cimbend.util import get_by_mrid, require
class ConductingEquipment(Equipment):
"""
Abstract class, should only be used through subclasses.
The parts of the AC power system that are designed to carry current or that are conductively connected through
terminals.
ConductingEquipment are connected by `zepben.cimbend.cim.iec61970.base.core.Terminal`'s which are in turn associated with
`zepben.cimbend.cim.iec61970.base.connectivity_node.ConnectivityNode`'s. Each `zepben.cimbend.iec61970.base.core.terminal.Terminal` is associated with
_exactly one_ `ConnectivityNode`, and through that `ConnectivityNode` can be linked with many other `Terminals` and `ConductingEquipment`.
"""
base_voltage: Optional[BaseVoltage] = None
"""`zepben.cimbend.iec61970.base.core.base_voltage.BaseVoltage` of this `ConductingEquipment`. Use only when there is no voltage level container used and
only one base voltage applies. For example, not used for transformers."""
_terminals: List[Terminal] = []
def __init__(self, usage_points: List[UsagePoint] = None, equipment_containers: List[EquipmentContainer] = None,
operational_restrictions: List[OperationalRestriction] = None, current_feeders: List[Feeder] = None, terminals: List[Terminal] = None):
super(ConductingEquipment, self).__init__(usage_points, equipment_containers, operational_restrictions, current_feeders)
if terminals:
for term in terminals:
self.add_terminal(term)
def get_base_voltage(self, terminal: Terminal = None):
"""
Get the `zepben.cimbend.iec61970.base.core.base_voltage.BaseVoltage` of this `ConductingEquipment`.
Note `terminal` is not used here, but this method can be overridden in child classes (e.g PowerTransformer).
:param terminal: The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to get the voltage at.
:return: The BaseVoltage of this `ConductingEquipment` at `terminal`
"""
return self.base_voltage
@property
def terminals(self) -> Generator[Terminal, None, None]:
"""
`ConductingEquipment` have `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`s that may be connected to other `ConductingEquipment`
`zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`s via `ConnectivityNode`s.
"""
for term in self._terminals:
yield term
def num_terminals(self):
"""
Get the number of `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`s for this `ConductingEquipment`.
"""
return len(self._terminals)
def get_terminal_by_mrid(self, mrid: str) -> Terminal:
"""
Get the `zepben.cimbend.iec61970.base.core.terminal.Terminal` for this `ConductingEquipment` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`
Returns The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._terminals, mrid)
def get_terminal_by_sn(self, sequence_number: int):
"""
Get the `zepben.cimbend.iec61970.base.core.terminal.Terminal` on this `ConductingEquipment` by its `sequence_number`.
`sequence_number` The `sequence_number` of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` in relation to this `ConductingEquipment`.
Returns The `zepben.cimbend.iec61970.base.core.terminal.Terminal` on this `ConductingEquipment` with sequence number `sequence_number`
Raises IndexError if no `zepben.cimbend.iec61970.base.core.terminal.Terminal` was found with sequence_number `sequence_number`.
"""
for term in self._terminals:
if term.sequence_number == sequence_number:
return term
raise IndexError(f"No Terminal with sequence_number {sequence_number} was found in ConductingEquipment {str(self)}")
def __getitem__(self, item: int):
return self.get_terminal_by_sn(item)
def add_terminal(self, terminal: Terminal) -> ConductingEquipment:
"""
Associate `terminal` with this `ConductingEquipment`. If `terminal.sequence_number` == 0, the terminal will be assigned a sequence_number of
`self.num_terminals() + 1`.
`terminal` The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to associate with this `ConductingEquipment`.
Returns A reference to this `ConductingEquipment` to allow fluent use.
Raises `ValueError` if another `zepben.cimbend.iec61970.base.core.terminal.Terminal` with the same `mrid` already exists for this `ConductingEquipment`.
"""
if self._validate_terminal(terminal):
return self
if terminal.sequence_number == 0:
terminal.sequence_number = self.num_terminals() + 1
self._terminals.append(terminal)
self._terminals.sort(key=lambda t: t.sequence_number)
return self
def remove_terminal(self, terminal: Terminal) -> ConductingEquipment:
"""
Disassociate `terminal` from this `ConductingEquipment`
`terminal` the `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to disassociate from this `ConductingEquipment`.
Returns A reference to this `ConductingEquipment` to allow fluent use.
Raises `ValueError` if `terminal` was not associated with this `ConductingEquipment`.
"""
self._terminals.remove(terminal)
return self
def clear_terminals(self) -> ConductingEquipment:
"""
Clear all terminals.
Returns A reference to this `ConductingEquipment` to allow fluent use.
"""
self._terminals.clear()
return self
def __repr__(self):
return (f"{super(ConductingEquipment, self).__repr__()}, in_service={self.in_service}, "
f"normally_in_service={self.normally_in_service}, location={self.location}"
)
def _validate_terminal(self, terminal: Terminal) -> bool:
"""
Validate a terminal against this `ConductingEquipment`'s `zepben.cimbend.iec61970.base.core.terminal.Terminal`s.
`terminal` The `zepben.cimbend.iec61970.base.core.terminal.Terminal` to validate.
Returns True if `zepben.cimbend.iec61970.base.core.terminal.Terminal`` is already associated with this `ConductingEquipment`, otherwise False.
Raises `ValueError` if `zepben.cimbend.iec61970.base.core.terminal.Terminal`s `conducting_equipment` is not this `ConductingEquipment`,
or if this `ConductingEquipment` has a different `zepben.cimbend.iec61970.base.core.terminal.Terminal` with the same mRID.
"""
if self._validate_reference(terminal, self.get_terminal_by_mrid, "A Terminal"):
return True
if self._validate_reference_by_sn(terminal.sequence_number, terminal, self.get_terminal_by_sn, "A Terminal"):
return True
require(terminal.conducting_equipment is self,
lambda: f"Terminal {terminal} references another piece of conducting equipment {terminal.conducting_equipment}, expected {str(self)}.")
return False | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/conducting_equipment.py | conducting_equipment.py |
from __future__ import annotations
import logging
from abc import ABCMeta
from dataclassy import dataclass
from typing import Union, Callable, Any
from uuid import UUID
from zepben.cimbend.util import require, CopyableUUID
__all__ = ["IdentifiedObject"]
logger = logging.getLogger(__name__)
@dataclass(slots=True)
class IdentifiedObject(object, metaclass=ABCMeta):
"""
Root class to provide common identification for all classes needing identification and naming attributes.
Everything should extend this class, however it's not mandated that every subclass must use all the fields
defined here.
All names of attributes of classes extending this class *must* directly reflect CIM properties if they have a direct
relation, however must be in snake case to keep the phases PEP compliant.
"""
mrid: Union[str, UUID] = CopyableUUID()
"""Master resource identifier issued by a model authority. The mRID is unique within an exchange context.
Global uniqueness is easily achieved by using a UUID, as specified in RFC 4122, for the mRID. The use of UUID is strongly recommended."""
name: str = ""
"""The name is any free human readable and possibly non unique text naming the object."""
description: str = ""
"""a free human readable text describing or naming the object. It may be non unique and may not correlate to a naming hierarchy."""
def __str__(self):
return f"{self.__class__.__name__}{{{'|'.join(a for a in (str(self.mrid), self.name) if a)}}}"
def _validate_reference(self, other: IdentifiedObject, getter: Callable[[str], IdentifiedObject], type_descr: str) -> bool:
"""
Validate whether a given reference exists to `other` using the provided getter function.
`other` The object to look up with the getter using its mRID.
`getter` A function that takes an mRID and returns an object if it exists, and throws a ``KeyError`` if it couldn't be found.
`type_descr` The type description to use for the lazily generated error message. Should be of the form "A[n] type(other)"
Returns True if `other` was retrieved with `getter` and was equivalent, False otherwise.
Raises `ValueError` if the object retrieved from `getter` is not `other`.
"""
try:
get_result = getter(other.mrid)
require(get_result is other, lambda: f"{type_descr} with mRID {other.mrid} already exists in {str(self)}")
return True
except (KeyError, AttributeError):
return False
def _validate_reference_by_sn(self, field: Any, other: IdentifiedObject, getter: Callable[[Any], IdentifiedObject], type_descr: str, field_name: str = "sequence_number") -> bool:
"""
Validate whether a given reference exists to `other` using the provided getter function called with `field`.
`other` The object to compare against.
`getter` A function that takes `field` and returns an `IdentifiedObject` if it exists, and throws an `IndexError` if it couldn't be found.
`type_descr` The type description to use for the lazily generated error message. Should be of the form "A[n] type(other)"
Returns True if `other` was retrieved with a call to `getter(field)` and was equivalent, False otherwise.
Raises `ValueError` if an object is retrieved from `getter` and it is not `other`.
"""
try:
get_result = getter(field)
require(get_result is other, lambda: f"{type_descr} with {field_name} {field} already exists in {str(self)}")
return True
except IndexError:
return False | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/identified_object.py | identified_object.py |
from __future__ import annotations
from typing import Generator, List
from dataclassy import dataclass
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.util import get_by_mrid
__all__ = ["ConnectivityNode"]
@dataclass(slots=False)
class ConnectivityNode(IdentifiedObject):
"""
Connectivity nodes are points where terminals of AC conducting equipment are connected together with zero impedance.
"""
__slots__ = ["_terminals", "__weakref__"]
_terminals: List[Terminal] = []
def __init__(self, terminals: List[Terminal] = None):
if terminals:
for term in terminals:
self.add_terminal(term)
def __iter__(self):
return iter(self._terminals)
def num_terminals(self):
"""
Get the number of `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`s for this `ConnectivityNode`.
"""
return len(self._terminals)
@property
def terminals(self) -> Generator[Terminal, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`s attached to this `ConnectivityNode`
"""
for term in self._terminals:
yield term
def get_terminal_by_mrid(self, mrid: str) -> Terminal:
"""
Get the `zepben.cimbend.iec61970.base.core.terminal.Terminal` for this `ConnectivityNode` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`
Returns The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._terminals, mrid)
def add_terminal(self, terminal: Terminal) -> ConnectivityNode:
"""
Associate a `terminal.Terminal` with this `ConnectivityNode`
`terminal` The `zepben.cimbend.iec61970.base.core.terminal.Terminal` to add. Will only add to this object if it is not already associated.
Returns A reference to this `ConnectivityNode` to allow fluent use.
Raises `ValueError` if another `Terminal` with the same `mrid` already exists for this `ConnectivityNode`.
"""
if self._validate_reference(terminal, self.get_terminal_by_mrid, "A Terminal"):
return self
self._terminals.append(terminal)
return self
def remove_terminal(self, terminal: Terminal) -> ConnectivityNode:
"""
Disassociate `terminal` from this `ConnectivityNode`.
`terminal` The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to disassociate from this `ConnectivityNode`.
Returns A reference to this `ConnectivityNode` to allow fluent use.
Raises `ValueError` if `terminal` was not associated with this `ConnectivityNode`.
"""
self._terminals.remove(terminal)
return self
def clear_terminals(self) -> ConnectivityNode:
"""
Clear all terminals.
Returns A reference to this `ConnectivityNode` to allow fluent use.
"""
self._terminals.clear()
return self
def is_switched(self):
return self.get_switch() is not None
def get_switch(self):
for term in self._terminals:
try:
# All switches should implement is_open
_ = term.conducting_equipment.is_open()
return term.conducting_equipment
except AttributeError:
pass
return None | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/connectivity_node.py | connectivity_node.py |
from __future__ import annotations
from typing import Optional, Dict, Generator, List
from zepben.cimbend.cim.iec61970.base.core.connectivity_node_container import ConnectivityNodeContainer
from zepben.cimbend.util import nlen, ngen
__all__ = ['EquipmentContainer', 'Feeder', 'Site']
class EquipmentContainer(ConnectivityNodeContainer):
"""
A modeling construct to provide a root class for containing equipment.
"""
_equipment: Optional[Dict[str, Equipment]] = None
"""Map of Equipment in this EquipmentContainer by their mRID"""
def __init__(self, equipment: List[Equipment] = None):
if equipment:
for eq in equipment:
self.add_equipment(eq)
def num_equipment(self):
"""
Returns The number of `zepben.cimbend.iec61970.base.core.equipment.Equipment` associated with this `EquipmentContainer`
"""
return nlen(self._equipment)
@property
def equipment(self) -> Generator[Equipment, None, None]:
"""
The `zepben.cimbend.iec61970.base.core.equipment.Equipment` contained in this `EquipmentContainer`
"""
return ngen(self._equipment.values() if self._equipment is not None else None)
def get_equipment(self, mrid: str) -> Equipment:
"""
Get the `zepben.cimbend.iec61970.base.core.equipment.Equipment` for this `EquipmentContainer` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.iec61970.base.core.equipment.Equipment`
Returns The `zepben.cimbend.iec61970.base.core.equipment.Equipment` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
if not self._equipment:
raise KeyError(mrid)
try:
return self._equipment[mrid]
except AttributeError:
raise KeyError(mrid)
def add_equipment(self, equipment: Equipment) -> EquipmentContainer:
"""
Associate `equipment` with this `EquipmentContainer`.
`equipment` The `zepben.cimbend.iec61970.base.core.equipment.Equipment` to associate with this `EquipmentContainer`.
Returns A reference to this `EquipmentContainer` to allow fluent use.
Raises `ValueError` if another `Equipment` with the same `mrid` already exists for this `EquipmentContainer`.
"""
if self._validate_reference(equipment, self.get_equipment, "An Equipment"):
return self
self._equipment = dict() if self._equipment is None else self._equipment
self._equipment[equipment.mrid] = equipment
return self
def remove_equipment(self, equipment: Equipment) -> EquipmentContainer:
"""
Disassociate `equipment` from this `EquipmentContainer`
`equipment` The `zepben.cimbend.iec61970.base.core.equipment.Equipment` to disassociate with this `EquipmentContainer`.
Returns A reference to this `EquipmentContainer` to allow fluent use.
Raises `KeyError` if `equipment` was not associated with this `EquipmentContainer`.
"""
if self._equipment:
del self._equipment[equipment.mrid]
else:
raise KeyError(equipment)
if not self._equipment:
self._equipment = None
return self
def clear_equipment(self) -> EquipmentContainer:
"""
Clear all equipment.
Returns A reference to this `EquipmentContainer` to allow fluent use.
"""
self._equipment = None
return self
def current_feeders(self) -> Generator[Feeder, None, None]:
"""
Convenience function to find all of the current feeders of the equipment associated with this equipment container.
Returns the current feeders for all associated feeders
"""
seen = set()
for equip in self._equipment.values():
for f in equip.current_feeders:
if f not in seen:
seen.add(f.mrid)
yield f
def normal_feeders(self) -> Generator[Feeder, None, None]:
"""
Convenience function to find all of the normal feeders of the equipment associated with this equipment container.
Returns the normal feeders for all associated feeders
"""
seen = set()
for equip in self._equipment.values():
for f in equip.normal_feeders:
if f not in seen:
seen.add(f.mrid)
yield f
class Feeder(EquipmentContainer):
"""
A collection of equipment for organizational purposes, used for grouping distribution resources.
The organization of a feeder does not necessarily reflect connectivity or current operation state.
"""
_normal_head_terminal: Optional[Terminal] = None
"""The normal head terminal or terminals of the feeder."""
normal_energizing_substation: Optional[Substation] = None
"""The substation that nominally energizes the feeder. Also used for naming purposes."""
_current_equipment: Optional[Dict[str, Equipment]] = None
def __init__(self, normal_head_terminal: Terminal = None, equipment: List[Equipment] = None, current_equipment: List[Equipment] = None):
super(Feeder, self).__init__(equipment)
self.normal_head_terminal = normal_head_terminal
if current_equipment:
for eq in current_equipment:
self.add_current_equipment(eq)
@property
def normal_head_terminal(self):
"""The normal head terminal or terminals of the feeder."""
return self._normal_head_terminal
@normal_head_terminal.setter
def normal_head_terminal(self, term):
if self._normal_head_terminal is None or self._normal_head_terminal is term:
self._normal_head_terminal = term
else:
raise ValueError(f"normal_head_terminal for {str(self)} has already been set to {self._normal_head_terminal}, cannot reset this field to {term}")
@property
def current_equipment(self) -> Generator[Equipment, None, None]:
"""
Contained `zepben.cimbend.iec61970.base.core.equipment.Equipment` using the current state of the network.
"""
return ngen(self._current_equipment)
def num_current_equipment(self):
"""
Returns The number of `zepben.cimbend.iec61970.base.core.equipment.Equipment` associated with this `Feeder`
"""
return nlen(self._current_equipment)
def get_current_equipment(self, mrid: str) -> Equipment:
"""
Get the `zepben.cimbend.iec61970.base.core.equipment.Equipment` for this `Feeder` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.iec61970.base.core.equipment.Equipment`
Returns The `zepben.cimbend.iec61970.base.core.equipment.Equipment` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
try:
return self._current_equipment[mrid]
except AttributeError:
raise KeyError(mrid)
def add_current_equipment(self, equipment: Equipment) -> Feeder:
"""
Associate `equipment` with this `Feeder`.
`equipment` the `zepben.cimbend.iec61970.base.core.equipment.Equipment` to associate with this `Feeder`.
Returns A reference to this `Feeder` to allow fluent use.
Raises `ValueError` if another `Equipment` with the same `mrid` already exists for this `Feeder`.
"""
if self._validate_reference(equipment, self.get_current_equipment, "An Equipment"):
return self
self._current_equipment = dict() if self._current_equipment is None else self._current_equipment
self._equipment[equipment.mrid] = equipment
return self
def remove_current_equipment(self, equipment: Equipment) -> Feeder:
"""
Disassociate `equipment` from this `Feeder`
`equipment` The `equipment.Equipment` to disassociate from this `Feeder`.
Returns A reference to this `Feeder` to allow fluent use.
Raises `KeyError` if `equipment` was not associated with this `Feeder`.
"""
if self._current_equipment:
del self._current_equipment[equipment.mrid]
else:
raise KeyError(equipment)
if not self._current_equipment:
self._current_equipment = None
return self
def clear_current_equipment(self) -> Feeder:
"""
Clear all equipment.
Returns A reference to this `Feeder` to allow fluent use.
"""
self._current_equipment = None
return self
class Site(EquipmentContainer):
"""
A collection of equipment for organizational purposes, used for grouping distribution resources located at a site.
Note this is not a CIM concept - however represents an `EquipmentContainer` in CIM. This is to avoid the use of `EquipmentContainer` as a concrete class.
"""
pass | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/core/equipment_container.py | equipment_container.py |
from __future__ import annotations
from typing import Optional
from zepben.cimbend.cim.iec61970.base.core.phase_code import PhaseCode
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.cim.iec61970.base.domain.unit_symbol import UnitSymbol
__all__ = ["Measurement", "Accumulator", "Analog", "Discrete"]
class Measurement(IdentifiedObject):
"""
A Measurement represents any measured, calculated or non-measured non-calculated quantity. Any piece of equipment
may contain Measurements, e.g. a substation may have temperature measurements and door open indications,
a transformer may have oil temperature and tank pressure measurements, a bay may contain a number of power flow
measurements and a Breaker may contain a switch status measurement.
The PSR - Measurement association is intended to capture this use of Measurement and is included in the naming
hierarchy based on EquipmentContainer. The naming hierarchy typically has Measurements as leafs,
e.g. Substation-VoltageLevel-Bay-Switch-Measurement.
Some Measurements represent quantities related to a particular sensor location in the network, e.g. a voltage
transformer (PT) at a busbar or a current transformer (CT) at the bar between a breaker and an isolator. The
sensing position is not captured in the PSR - Measurement association. Instead it is captured by the Measurement
- Terminal association that is used to define the sensing location in the network topology. The location is
defined by the connection of the Terminal to ConductingEquipment.
If both a Terminal and PSR are associated, and the PSR is of type ConductingEquipment, the associated Terminal
should belong to that ConductingEquipment instance.
When the sensor location is needed both Measurement-PSR and Measurement-Terminal are used. The Measurement-Terminal
association is never used alone.
"""
power_system_resource_mrid: Optional[str] = None
"""The MRID of the power system resource that contains the measurement."""
remote_source: Optional[RemoteSource] = None
"""The `zepben.cimbend.cim.iec61970.base.scada.remote_source.RemoteSource` taking the `Measurement`"""
terminal_mrid: Optional[str] = None
"""A measurement may be associated with a terminal in the network."""
phases: PhaseCode = PhaseCode.ABC
"""Indicates to which phases the measurement applies and avoids the need to use 'measurementType' to also encode phase information
(which would explode the types). The phase information in Measurement, along with 'measurementType' and 'phases' uniquely defines a Measurement for a
device, based on normal network phase. Their meaning will not change when the computed energizing phasing is changed due to jumpers or other reasons.
If the attribute is missing three phases (ABC) shall be assumed."""
unitSymbol: UnitSymbol = UnitSymbol.NONE
"""Specifies the type of measurement. For example, this specifies if the measurement represents an indoor temperature, outdoor temperature, bus voltage,
line flow, etc. When the measurementType is set to "Specialization", the type of Measurement is defined in more detail by the specialized class which
inherits from Measurement."""
class Accumulator(Measurement):
"""Accumulator represents an accumulated (counted) Measurement, e.g. an energy value."""
pass
class Analog(Measurement):
"""Analog represents an analog Measurement."""
positive_flow_in: bool = False
"""If true then this measurement is an active power, reactive power or current with the convention that a positive value measured at the
Terminal means power is flowing into the related PowerSystemResource."""
class Discrete(Measurement):
"""Discrete represents a discrete Measurement, i.e. a Measurement representing discrete values, e.g. a Breaker position."""
pass | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/base/meas/measurement.py | measurement.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61970.base.wires.line import Line
from zepben.cimbend.util import ngen, get_by_mrid, safe_remove, nlen
__all__ = ["Circuit"]
class Circuit(Line):
"""Missing description"""
loop: Optional[Loop] = None
_end_terminals: Optional[List[Terminal]] = None
_end_substations: Optional[List[Substation]] = None
def __init__(self, equipment: List[Equipment] = None, end_terminals: List[Terminal] = None, end_substations: List[Substation] = None):
super(Circuit, self).__init__(equipment)
if end_terminals:
for term in end_terminals:
self.add_end_terminal(term)
if end_substations:
for sub in end_substations:
self.add_end_substation(sub)
@property
def end_terminals(self) -> Generator[Terminal, None, None]:
"""
The `Terminal`s representing the ends for this `Circuit`.
"""
return ngen(self._end_terminals)
@property
def end_substations(self) -> Generator[Substation, None, None]:
"""
The `Substations`s representing the ends for this `Circuit`.
"""
return ngen(self._end_substations)
def num_end_terminals(self):
"""Return the number of end `Terminal`s associated with this `Circuit`"""
return nlen(self._end_terminals)
def get_terminal(self, mrid: str) -> Circuit:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` for this `Circuit` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal`
Returns The `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._end_terminals, mrid)
def add_terminal(self, terminal: Terminal) -> Circuit:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` with this `Circuit`
`terminal` the `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to associate with this `Circuit`.
Returns A reference to this `Circuit` to allow fluent use.
Raises `ValueError` if another `Terminal` with the same `mrid` already exists for this `Circuit`.
"""
if self._validate_reference(terminal, self.get_terminal, "An Terminal"):
return self
self._end_terminals = list() if self._end_terminals is None else self._end_terminals
self._end_terminals.append(terminal)
return self
def remove_end_terminals(self, terminal: Terminal) -> Circuit:
"""
Disassociate `terminal` from this `Circuit`
`terminal` the `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to disassociate from this `Circuit`.
Returns A reference to this `Circuit` to allow fluent use.
Raises `ValueError` if `terminal` was not associated with this `Circuit`.
"""
self._end_terminals = safe_remove(self._end_terminals, terminal)
return self
def clear_end_terminals(self) -> Circuit:
"""
Clear all end terminals.
Returns A reference to this `Circuit` to allow fluent use.
"""
self._end_terminals = None
return self
def num_end_substations(self):
"""Return the number of end `Substation`s associated with this `Circuit`"""
return nlen(self._end_substations)
def get_substation(self, mrid: str) -> Circuit:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` for this `Circuit` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61970.base.core.substation.Substation`
Returns The `zepben.cimbend.cim.iec61970.base.core.substation.Substation` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._end_substations, mrid)
def add_substation(self, substation: Substation) -> Circuit:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.substation.Substation` with this `Circuit`
`substation` the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` to associate with this `Circuit`.
Returns A reference to this `Circuit` to allow fluent use.
Raises `ValueError` if another `Substation` with the same `mrid` already exists for this `Circuit`.
"""
if self._validate_reference(substation, self.get_substation, "An Substation"):
return self
self._end_substations = list() if self._end_substations is None else self._end_substations
self._end_substations.append(substation)
return self
def remove_end_substations(self, substation: Substation) -> Circuit:
"""
Disassociate `substation` from this `Circuit`
`substation` the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` to disassociate from this `Circuit`.
Returns A reference to this `Circuit` to allow fluent use.
Raises `ValueError` if `substation` was not associated with this `Circuit`.
"""
self._end_substations = safe_remove(self._end_substations, substation)
return self
def clear_end_substations(self) -> Circuit:
"""
Clear all end substations.
Returns A reference to this `Circuit` to allow fluent use.
"""
self._end_substations = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/infiec61970/feeder/circuit.py | circuit.py |
from __future__ import annotations
from typing import Optional, List, Generator
__all__ = ["Loop"]
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.util import safe_remove, ngen, nlen, get_by_mrid
class Loop(IdentifiedObject):
"""Missing description"""
loop: Optional[Loop] = None
_circuits: Optional[List[Circuit]] = None
_substations: Optional[List[Substation]] = None
_energizing_substations: Optional[List[Substation]] = None
def __init__(self, circuits: List[Circuit] = None, substations: List[Substation] = None, energizing_substations: List[Substation] = None):
if circuits:
for term in circuits:
self.add_circuit(term)
if substations:
for sub in substations:
self.add_substation(sub)
if substations:
for sub in energizing_substations:
self.add_energizing_substation(sub)
@property
def circuits(self) -> Generator[Circuit, None, None]:
"""
Sub-transmission `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit`s that form part of this loop.
"""
return ngen(self._circuits)
@property
def substations(self) -> Generator[Substation, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.substation.Substation`s that are powered by this `Loop`.
"""
return ngen(self._substations)
@property
def energizing_substations(self) -> Generator[Substation, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.substation.Substation`s that normally energize this `Loop`.
"""
return ngen(self._energizing_substations)
def num_circuits(self):
"""Return the number of end `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit`s associated with this `Loop`"""
return nlen(self._circuits)
def get_circuit(self, mrid: str) -> Loop:
"""
Get the `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit` for this `Loop` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit`
Returns The `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._circuits, mrid)
def add_circuit(self, circuit: Circuit) -> Loop:
"""
Associate an `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit` with this `Loop`
`circuit` the `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit` to associate with this `Loop`.
Returns A reference to this `Loop` to allow fluent use.
Raises `ValueError` if another `Circuit` with the same `mrid` already exists for this `Loop`.
"""
if self._validate_reference(circuit, self.get_circuit, "An Circuit"):
return self
self._circuits = list() if self._circuits is None else self._circuits
self._circuits.append(circuit)
return self
def remove_circuits(self, circuit: Circuit) -> Loop:
"""
Disassociate `circuit` from this `Loop`
`circuit` the `zepben.cimbend.cim.infiec61970.base.core.circuit.Circuit` to disassociate from this `Loop`.
Returns A reference to this `Loop` to allow fluent use.
Raises `ValueError` if `circuit` was not associated with this `Loop`.
"""
self._circuits = safe_remove(self._circuits, circuit)
return self
def clear_circuits(self) -> Loop:
"""
Clear all end circuits.
Returns A reference to this `Loop` to allow fluent use.
"""
self._circuits = None
return self
def num_substations(self):
"""Return the number of end `zepben.cimbend.cim.iec61970.base.core.substation.Substation`s associated with this `Loop`"""
return nlen(self._substations)
def get_substation(self, mrid: str) -> Loop:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` for this `Loop` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61970.base.core.substation.Substation`
Returns The `zepben.cimbend.cim.iec61970.base.core.substation.Substation` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._substations, mrid)
def add_substation(self, substation: Substation) -> Loop:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.substation.Substation` with this `Loop`
`substation` the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` to associate with this `Loop`.
Returns A reference to this `Loop` to allow fluent use.
Raises `ValueError` if another `Substation` with the same `mrid` already exists for this `Loop`.
"""
if self._validate_reference(substation, self.get_substation, "An Substation"):
return self
self._substations = list() if self._substations is None else self._substations
self._substations.append(substation)
return self
def remove_substations(self, substation: Substation) -> Loop:
"""
Disassociate `substation` from this `Loop`
`substation` the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` to disassociate from this `Loop`.
Returns A reference to this `Loop` to allow fluent use.
Raises `ValueError` if `substation` was not associated with this `Loop`.
"""
self._substations = safe_remove(self._substations, substation)
return self
def clear_substations(self) -> Loop:
"""
Clear all end substations.
Returns A reference to this `Loop` to allow fluent use.
"""
self._substations = None
return self
def num_energizing_substations(self):
"""Return the number of end `zepben.cimbend.cim.iec61970.base.core.substation.Substation`s associated with this `Loop`"""
return nlen(self._energizing_substations)
def get_energizing_substation(self, mrid: str) -> Loop:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` for this `Loop` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61970.base.core.substation.Substation`
Returns The `zepben.cimbend.cim.iec61970.base.core.substation.Substation` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._energizing_substations, mrid)
def add_energizing_substation(self, substation: Substation) -> Loop:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.substation.Substation` with this `Loop`
`substation` the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` to associate with this `Loop`.
Returns A reference to this `Loop` to allow fluent use.
Raises `ValueError` if another `Substation` with the same `mrid` already exists for this `Loop`.
"""
if self._validate_reference(substation, self.get_energizing_substation, "An Substation"):
return self
self._energizing_substations = list() if self._energizing_substations is None else self._energizing_substations
self._energizing_substations.append(substation)
return self
def remove_energizing_substations(self, substation: Substation) -> Loop:
"""
Disassociate `substation` from this `Loop`
`substation` the `zepben.cimbend.cim.iec61970.base.core.substation.Substation` to disassociate from this `Loop`.
Returns A reference to this `Loop` to allow fluent use.
Raises `ValueError` if `substation` was not associated with this `Loop`.
"""
self._energizing_substations = safe_remove(self._energizing_substations, substation)
return self
def clear_energizing_substations(self) -> Loop:
"""
Clear all end energizing_substations.
Returns A reference to this `Loop` to allow fluent use.
"""
self._energizing_substations = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61970/infiec61970/feeder/loop.py | loop.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61968.common.organisation_role import OrganisationRole
from zepben.cimbend.cim.iec61968.customers.customer_kind import CustomerKind
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
__all__ = ["Customer"]
class Customer(OrganisationRole):
"""
Organisation receiving services from service supplier.
"""
kind: CustomerKind = CustomerKind.UNKNOWN
"""Kind of customer"""
_customer_agreements: Optional[List[CustomerAgreement]] = None
def __init__(self, customer_agreements: List[CustomerAgreement] = None):
if customer_agreements:
for agreement in customer_agreements:
self.add_agreement(agreement)
def num_agreements(self) -> int:
"""
Get the number of `zepben.cimbend.iec61968.customers.customer_agreement.CustomerAgreement`s associated with this `Customer`.
"""
return nlen(self._customer_agreements)
@property
def agreements(self) -> Generator[CustomerAgreement, None, None]:
"""
The `zepben.cimbend.cim.iec61968.customers.customer_agreement.CustomerAgreement`s for this `Customer`.
"""
return ngen(self._customer_agreements)
def get_agreement(self, mrid: str) -> CustomerAgreement:
"""
Get the `zepben.cimbend.cim.iec61968.customers.customer_agreement.CustomerAgreement` for this `Customer` identified by `mrid`.
`mrid` the mRID of the required `customer_agreement.CustomerAgreement`
Returns the `zepben.cimbend.cim.iec61968.customers.customer_agreement.CustomerAgreement` with the specified `mrid`.
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._customer_agreements, mrid)
def add_agreement(self, customer_agreement: CustomerAgreement) -> Customer:
"""
Associate a `CustomerAgreement` with this `Customer`.
`customer_agreement` The `customer_agreement.CustomerAgreement` to associate with this `Customer`.
Returns A reference to this `Customer` to allow fluent use.
Raises `ValueError` if another `CustomerAgreement` with the same `mrid` already exists for this `Customer`
"""
if self._validate_reference(customer_agreement, self.get_agreement, "A CustomerAgreement"):
return self
self._customer_agreements = list() if self._customer_agreements is None else self._customer_agreements
self._customer_agreements.append(customer_agreement)
return self
def remove_agreement(self, customer_agreement: CustomerAgreement) -> Customer:
"""
Disassociate `customer_agreement` from this `Customer`.
`customer_agreement` the `customer_agreement.CustomerAgreement` to disassociate with this `Customer`.
Returns A reference to this `Customer` to allow fluent use.
Raises `ValueError` if `customer_agreement` was not associated with this `Customer`.
"""
self._customer_agreements = safe_remove(self._customer_agreements, customer_agreement)
return self
def clear_agreements(self) -> Customer:
"""
Clear all customer agreements.
Returns self
"""
self._customer_agreements = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/customers/customer.py | customer.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61968.common.document import Agreement
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
__all__ = ["CustomerAgreement"]
class CustomerAgreement(Agreement):
"""
Agreement between the customer and the service supplier to pay for service at a specific service location. It
records certain billing information about the type of service provided at the service location and is used
during charge creation to determine the type of service.
"""
_customer: Optional[Customer] = None
"""The `zepben.cimbend.cim.iec61968.customers.customer.Customer` that has this `CustomerAgreement`."""
_pricing_structures: Optional[List[PricingStructure]] = None
def __init__(self, customer: Customer = None, pricing_structures: List[PricingStructure] = None):
self.customer = customer
if pricing_structures:
for ps in pricing_structures:
self.add_pricing_structure(ps)
@property
def customer(self):
"""The `zepben.cimbend.cim.iec61968.customers.customer.Customer` that has this `CustomerAgreement`."""
return self._customer
@customer.setter
def customer(self, cust):
if self._customer is None or self._customer is cust:
self._customer = cust
else:
raise ValueError(f"customer for {str(self)} has already been set to {self._customer}, cannot reset this field to {cust}")
def num_pricing_structures(self):
"""
The number of `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure`s associated with this `CustomerAgreement`
"""
return nlen(self._pricing_structures)
@property
def pricing_structures(self) -> Generator[PricingStructure, None, None]:
"""
The `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure`s of this `CustomerAgreement`.
"""
return ngen(self._pricing_structures)
def get_pricing_structure(self, mrid: str) -> PricingStructure:
"""
Get the `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure` for this `CustomerAgreement` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure`
Returns the `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._pricing_structures, mrid)
def add_pricing_structure(self, ps: PricingStructure) -> CustomerAgreement:
"""
Associate `ps` with this `CustomerAgreement`
`ps` the `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure` to associate with this `CustomerAgreement`.
Returns A reference to this `CustomerAgreement` to allow fluent use.
Raises `ValueError` if another `PricingStructure` with the same `mrid` already exists for this `CustomerAgreement`
"""
if self._validate_reference(ps, self.get_pricing_structure, "A PricingStructure"):
return self
self._pricing_structures = list() if self._pricing_structures is None else self._pricing_structures
self._pricing_structures.append(ps)
return self
def remove_pricing_structure(self, ps: PricingStructure) -> CustomerAgreement:
"""
Disassociate `ps` from this `CustomerAgreement`
`ps` the `zepben.cimbend.cim.iec61968.customers.pricing_structure.PricingStructure` to disassociate from this `CustomerAgreement`.
Returns A reference to this `CustomerAgreement` to allow fluent use.
Raises `ValueError` if `ps` was not associated with this `CustomerAgreement`.
"""
self._pricing_structures = safe_remove(self._pricing_structures, ps)
return self
def clear_pricing_structures(self) -> CustomerAgreement:
"""
Clear all pricing structures.
Returns a reference to this `CustomerAgreement` to allow fluent use.
"""
self._pricing_structures = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/customers/customer_agreement.py | customer_agreement.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61968.common.document import Document
from zepben.cimbend.util import get_by_mrid, nlen, ngen, safe_remove
__all__ = ["PricingStructure"]
class PricingStructure(Document):
"""
Grouping of pricing components and prices used in the creation of customer charges and the eligibility
criteria under which these terms may be offered to a customer. The reasons for grouping include state,
customer classification, site characteristics, classification (i.e. fee price structure, deposit price
structure, electric service price structure, etc.) and accounting requirements.
"""
_tariffs: Optional[List[Tariff]] = None
def __init__(self, tariffs: List[Tariff] = None):
if tariffs:
for tariff in tariffs:
self.add_tariff(tariff)
def num_tariffs(self):
"""
Returns The number of `zepben.cimbend.cim.iec61968.customers.tariff.Tariff`s associated with this `PricingStructure`
"""
return nlen(self._tariffs)
@property
def tariffs(self) -> Generator[Tariff, None, None]:
"""
The `zepben.cimbend.cim.iec61968.customers.tariff.Tariff`s of this `PricingStructure`.
"""
return ngen(self._tariffs)
def get_tariff(self, mrid: str) -> Tariff:
"""
Get the `zepben.cimbend.cim.iec61968.customers.tariff.Tariff` for this `PricingStructure` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61968.customers.tariff.Tariff`
Returns The `zepben.cimbend.cim.iec61968.customers.tariff.Tariff` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._tariffs, mrid)
def add_tariff(self, tariff: Tariff) -> PricingStructure:
"""
Associate a `zepben.cimbend.cim.iec61968.customers.tariff.Tariff` with this `PricingStructure`.
`tariff` the `zepben.cimbend.cim.iec61968.customers.tariff.Tariff` to associate with this `PricingStructure`.
Returns A reference to this `PricingStructure` to allow fluent use.
Raises `ValueError` if another `Tariff` with the same `mrid` already exists for this `PricingStructure`.
"""
if self._validate_reference(tariff, self.get_tariff, "A Tariff"):
return self
self._tariffs = list() if self._tariffs is None else self._tariffs
self._tariffs.append(tariff)
return self
def remove_tariff(self, tariff: Tariff) -> PricingStructure:
"""
Disassociate `tariff` from this `PricingStructure`.
`tariff` the `zepben.cimbend.cim.iec61968.customers.tariff.Tariff` to disassociate from this `PricingStructure`.
Returns A reference to this `PricingStructure` to allow fluent use.
Raises `ValueError` if `tariff` was not associated with this `PricingStructure`.
"""
self._tariffs = safe_remove(self._tariffs, tariff)
return self
def clear_tariffs(self) -> PricingStructure:
"""
Clear all tariffs.
Returns A reference to this `PricingStructure` to allow fluent use.
"""
self._tariffs = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/customers/pricing_structure.py | pricing_structure.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61968.common.location import Location
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.util import get_by_mrid, nlen, ngen, safe_remove
__all__ = ["Asset", "AssetContainer"]
class Asset(IdentifiedObject):
"""
Tangible resource of the utility, including power system equipment, various end devices, cabinets, buildings,
etc. For electrical network equipment, the role of the asset is defined through PowerSystemResource and its
subclasses, defined mainly in the Wires model (refer to IEC61970-301 and model package IEC61970::Wires). Asset
description places emphasis on the physical characteristics of the equipment fulfilling that role.
"""
location: Optional[Location] = None
"""`zepben.cimbend.cim.iec61968.common.location.Location` of this asset"""
_organisation_roles: Optional[List[AssetOrganisationRole]] = None
def __init__(self, organisation_roles: List[AssetOrganisationRole] = None):
if organisation_roles:
for role in organisation_roles:
self.add_organisation_role(role)
def num_organisation_roles(self) -> int:
"""
Get the number of `zepben.cimbend.cim.iec61968.assets.asset_organisation_role.AssetOrganisationRole`s associated with this `Asset`.
"""
return nlen(self._organisation_roles)
@property
def organisation_roles(self) -> Generator[AssetOrganisationRole, None, None]:
"""
The `zepben.cimbend.cim.iec61968.assets.asset_organisation_role.AssetOrganisationRole`s of this `Asset`.
"""
return ngen(self._organisation_roles)
def get_organisation_role(self, mrid: str) -> AssetOrganisationRole:
"""
Get the `AssetOrganisationRole` for this asset identified by `mrid`.
`mrid` the mRID of the required `zepben.cimbend.cim.iec61968.assets.asset_organisation_role.AssetOrganisationRole`
Returns The `zepben.cimbend.cim.iec61968.assets.asset_organisation_role.AssetOrganisationRole` with the specified `mrid`.
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._organisation_roles, mrid)
def add_organisation_role(self, role: AssetOrganisationRole) -> Asset:
"""
`role` The `zepben.cimbend.cim.iec61968.assets.asset_organisation_role.AssetOrganisationRole` to
associate with this `Asset`.
Returns A reference to this `Asset` to allow fluent use.
Raises `ValueError` if another `AssetOrganisationRole` with the same `mrid` already exists in this `Asset`
"""
if self._validate_reference(role, self.get_organisation_role, "An AssetOrganisationRole"):
return self
self._organisation_roles = list() if self._organisation_roles is None else self._organisation_roles
self._organisation_roles.append(role)
return self
def remove_organisation_role(self, role: AssetOrganisationRole) -> Asset:
"""
Disassociate an `AssetOrganisationRole` from this `Asset`.
`role` the `zepben.cimbend.cim.iec61968.assets.asset_organisation_role.AssetOrganisationRole` to
disassociate with this `Asset`.
Raises `ValueError` if `role` was not associated with this `Asset`.
Returns A reference to this `Asset` to allow fluent use.
"""
self._organisation_roles = safe_remove(self._organisation_roles, role)
return self
def clear_organisation_roles(self) -> Asset:
"""
Clear all organisation roles.
Returns self
"""
self._organisation_roles = None
return self
class AssetContainer(Asset):
"""
Asset that is aggregation of other assets such as conductors, transformers, switchgear, land, fences, buildings,
equipment, vehicles, etc.
"""
pass | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/assets/asset.py | asset.py |
from __future__ import annotations
from typing import List, Optional, Generator
from zepben.cimbend.cim.iec61968.assets.structure import Structure
from zepben.cimbend.util import get_by_mrid, ngen, nlen, safe_remove
__all__ = ["Pole"]
class Pole(Structure):
"""A Pole Asset"""
classification: str = ""
"""Pole class: 1, 2, 3, 4, 5, 6, 7, H1, H2, Other, Unknown."""
_streetlights: Optional[List[Streetlight]] = None
def __init__(self, organisation_roles: List[AssetOrganisationRole] = None, streetlights: List[Streetlight] = None):
super(Pole, self).__init__(organisation_roles=organisation_roles)
if streetlights:
for light in streetlights:
self.add_streetlight(light)
@property
def num_streetlights(self) -> int:
"""
Get the number of `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight`s associated with this `Pole`.
"""
return nlen(self._streetlights)
@property
def streetlights(self) -> Generator[Streetlight, None, None]:
"""
The `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight`s of this `Pole`.
"""
return ngen(self._streetlights)
def get_streetlight(self, mrid: str) -> Streetlight:
"""
Get the `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight` for this asset identified by `mrid`.
`mrid` the mRID of the required `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight`
Returns The `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight` with the specified `mrid`.
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._streetlights, mrid)
def add_streetlight(self, streetlight: Streetlight) -> Pole:
"""
Associate a `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight` with this `Pole`
`streetlight` the `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight` to associate with this `Pole`.
Returns A reference to this `Pole` to allow fluent use.
Raises `ValueError` if another `Streetlight` with the same `mrid` already exists in this `Pole`
"""
if self._validate_reference(streetlight, self.get_streetlight, "A Streetlight"):
return self
self._streetlights = list() if self._streetlights is None else self._streetlights
self._streetlights.append(streetlight)
return self
def remove_streetlight(self, streetlight: Streetlight) -> Pole:
"""
Disassociate `streetlight` from this `Pole`
`streetlight` the `zepben.cimbend.cim.iec61968.assets.streetlight.Streetlight` to disassociate from this `Pole`.
Raises `ValueError` if `streetlight` was not associated with this `Pole`.
Returns A reference to this `Pole` to allow fluent use.
"""
self._streetlights = safe_remove(self._streetlights, streetlight)
return self
def clear_streetlights(self) -> Pole:
"""
Clear all Streetlights.
Returns self
"""
self._streetlights = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/assets/pole.py | pole.py |
from __future__ import annotations
from typing import Optional, Generator, List
from zepben.cimbend.cim.iec61968.common.document import Document
from zepben.cimbend.util import get_by_mrid, nlen, ngen, safe_remove
__all__ = ["OperationalRestriction"]
class OperationalRestriction(Document):
"""
A document that can be associated with equipment to describe any sort of restrictions compared with the
original manufacturer's specification or with the usual operational practice e.g.
temporary maximum loadings, maximum switching current, do not operate if bus couplers are open, etc.
In the UK, for example, if a breaker or switch ever mal-operates, this is reported centrally and utilities
use their asset systems to identify all the installed devices of the same manufacturer's type.
They then apply operational restrictions in the operational systems to warn operators of potential problems.
After appropriate inspection and maintenance, the operational restrictions may be removed.
"""
_equipment: Optional[List[Equipment]] = None
def __init__(self, equipment: List[Equipment] = None):
if equipment:
for eq in equipment:
self.add_equipment(eq)
@property
def num_equipment(self):
"""
Returns the number of `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` associated with this `OperationalRestriction`
"""
return nlen(self._equipment)
@property
def equipment(self) -> Generator[Equipment, None, None]:
"""
The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` to which this `OperationalRestriction` applies.
"""
return ngen(self._equipment)
def get_equipment(self, mrid: str) -> Equipment:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` for this `OperationalRestriction` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment`
Returns The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._equipment, mrid)
def add_equipment(self, equipment: Equipment) -> OperationalRestriction:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` with this `OperationalRestriction`
`equipment` The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` to associate with this `OperationalRestriction`.
Returns A reference to this `OperationalRestriction` to allow fluent use.
Raises `ValueError` if another `Equipment` with the same `mrid` already exists for this `OperationalRestriction`.
"""
if self._validate_reference(equipment, self.get_equipment, "An Equipment"):
return self
self._equipment = list() if self._equipment is None else self._equipment
self._equipment.append(equipment)
return self
def remove_equipment(self, equipment: Equipment) -> OperationalRestriction:
"""
Disassociate `equipment` from this `OperationalRestriction`.
`equipment` The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` to disassociate from this `OperationalRestriction`.
Returns A reference to this `OperationalRestriction` to allow fluent use.
Raises `ValueError` if `equipment` was not associated with this `OperationalRestriction`.
"""
self._equipment = safe_remove(self._equipment, equipment)
return self
def clear_equipment(self) -> OperationalRestriction:
"""
Clear all equipment.
Returns A reference to this `OperationalRestriction` to allow fluent use.
"""
self._equipment = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/operations/operational_restriction.py | operational_restriction.py |
from __future__ import annotations
import logging
from typing import Optional, Generator
from typing import List
from zepben.cimbend.cim.iec61968.assets.asset import AssetContainer
from zepben.cimbend.cim.iec61968.common.location import Location
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.util import nlen, get_by_mrid, ngen, safe_remove
__all__ = ["Meter", "EndDevice", "UsagePoint"]
logger = logging.getLogger(__name__)
class EndDevice(AssetContainer):
"""
Asset container that performs one or more end device functions. One type of end device is a meter which can perform
metering, load management, connect/disconnect, accounting functions, etc. Some end devices, such as ones monitoring
and controlling air conditioners, refrigerators, pool pumps may be connected to a meter. All end devices may have
communication capability defined by the associated communication function(s).
An end device may be owned by a consumer, a service provider, utility or otherwise.
There may be a related end device function that identifies a sensor or control point within a metering application
or communications systems (e.g., water, gas, electricity).
Some devices may use an optical port that conforms to the ANSI C12.18 standard for communications.
"""
customer_mrid: Optional[str] = None
"""The `zepben.cimbend.cim.iec61968.customers.customer.Customer` owning this `EndDevice`."""
service_location: Optional[Location] = None
"""Service `zepben.cimbend.cim.iec61968.common.location.Location` whose service delivery is measured by this `EndDevice`."""
_usage_points: Optional[List[UsagePoint]] = None
def __init__(self, organisation_roles: List[AssetOrganisationRole] = None, usage_points: List[UsagePoint] = None):
super(EndDevice, self).__init__(organisation_roles=organisation_roles)
if usage_points:
for up in usage_points:
self.add_usage_point(up)
def num_usage_points(self):
"""
Returns The number of `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint`s associated with this `EndDevice`
"""
return nlen(self._usage_points)
@property
def usage_points(self) -> Generator[UsagePoint, None, None]:
"""
The `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint`s associated with this `EndDevice`
"""
return ngen(self._usage_points)
def get_usage_point(self, mrid: str) -> UsagePoint:
"""
Get the `UsagePoint` for this `EndDevice` identified by `mrid`
`mrid` the mRID of the required `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint`
Returns The `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._usage_points, mrid)
def add_usage_point(self, up: UsagePoint) -> EndDevice:
"""
Associate `up` to this `zepben.cimbend.cim.iec61968.metering.metering.EndDevice`.
`up` the `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` to associate with this `EndDevice`.
Returns A reference to this `EndDevice` to allow fluent use.
Raises `ValueError` if another `UsagePoint` with the same `mrid` already exists for this `EndDevice`.
"""
if self._validate_reference(up, self.get_usage_point, "A UsagePoint"):
return self
self._usage_points = list() if self._usage_points is None else self._usage_points
self._usage_points.append(up)
return self
def remove_usage_point(self, up: UsagePoint) -> EndDevice:
"""
Disassociate `up` from this `EndDevice`
`up` the `zepben.cimbend.cim.iec61968.metering.metering.UsagePoint` to disassociate from this `EndDevice`.
Returns A reference to this `EndDevice` to allow fluent use.
Raises `ValueError` if `up` was not associated with this `EndDevice`.
"""
self._usage_points = safe_remove(self._usage_points, up)
return self
def clear_usage_points(self) -> EndDevice:
"""
Clear all usage_points.
Returns A reference to this `EndDevice` to allow fluent use.
"""
self._usage_points = None
return self
class UsagePoint(IdentifiedObject):
"""
Logical or physical point in the network to which readings or events may be attributed.
Used at the place where a physical or virtual meter may be located; however, it is not required that a meter be present.
"""
usage_point_location: Optional[Location] = None
"""Service `zepben.cimbend.cim.iec61968.common.location.Location` where the service delivered by this `UsagePoint` is consumed."""
_equipment: Optional[List[Equipment]] = None
_end_devices: Optional[List[EndDevice]] = None
def __init__(self, equipment: List[Equipment] = None, end_devices: List[EndDevice] = None):
if equipment:
for eq in equipment:
self.add_equipment(eq)
if end_devices:
for ed in end_devices:
self.add_end_device(ed)
def num_equipment(self):
"""
Returns The number of `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment`s associated with this `UsagePoint`
"""
return nlen(self._equipment)
def num_end_devices(self):
"""
Returns The number of `zepben.cimbend.cim.iec61968.metering.metering.EndDevice`s associated with this `UsagePoint`
"""
return nlen(self._end_devices)
@property
def end_devices(self) -> Generator[EndDevice, None, None]:
"""
The `EndDevice`'s (Meter's) associated with this `UsagePoint`.
"""
return ngen(self._end_devices)
@property
def equipment(self) -> Generator[Equipment, None, None]:
"""
The `zepben.model.Equipment` associated with this `UsagePoint`.
"""
return ngen(self._equipment)
def get_equipment(self, mrid: str) -> Equipment:
"""
Get the `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` for this `UsagePoint` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment`
Returns The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._equipment, mrid)
def add_equipment(self, equipment: Equipment) -> UsagePoint:
"""
Associate an `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` with this `UsagePoint`
`equipment` The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` to associate with this `UsagePoint`.
Returns A reference to this `UsagePoint` to allow fluent use.
Raises `ValueError` if another `Equipment` with the same `mrid` already exists for this `UsagePoint`.
"""
if self._validate_reference(equipment, self.get_equipment, "An Equipment"):
return self
self._equipment = list() if self._equipment is None else self._equipment
self._equipment.append(equipment)
return self
def remove_equipment(self, equipment: Equipment) -> UsagePoint:
"""
Disassociate an `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` from this `UsagePoint`
`equipment` The `zepben.cimbend.cim.iec61970.base.core.equipment.Equipment` to disassociate with this `UsagePoint`.
Returns A reference to this `UsagePoint` to allow fluent use.
Raises `ValueError` if `equipment` was not associated with this `UsagePoint`.
"""
self._equipment = safe_remove(self._equipment, equipment)
return self
def clear_equipment(self) -> UsagePoint:
"""
Clear all equipment.
Returns A reference to this `UsagePoint` to allow fluent use.
"""
self._equipment = None
return self
def get_end_device(self, mrid: str) -> EndDevice:
"""
Get the `EndDevice` for this `UsagePoint` identified by `mrid`
`mrid` The mRID of the required `zepben.cimbend.cim.iec61968.metering.metering.EndDevice`
Returns The `zepben.cimbend.cim.iec61968.metering.metering.EndDevice` with the specified `mrid` if it exists
Raises `KeyError` if `mrid` wasn't present.
"""
return get_by_mrid(self._end_devices, mrid)
def add_end_device(self, end_device: EndDevice) -> UsagePoint:
"""
Associate an `EndDevice` with this `UsagePoint`
`end_device` The `zepben.cimbend.cim.iec61968.metering.metering.EndDevice` to associate with this `UsagePoint`.
Returns A reference to this `UsagePoint` to allow fluent use.
Raises `ValueError` if another `EndDevice` with the same `mrid` already exists for this `UsagePoint`.
"""
if self._validate_reference(end_device, self.get_end_device, "An EndDevice"):
return self
self._end_devices = list() if self._end_devices is None else self._end_devices
self._end_devices.append(end_device)
return self
def remove_end_device(self, end_device: EndDevice) -> UsagePoint:
"""
Disassociate `end_device` from this `UsagePoint`.
`end_device` The `zepben.cimbend.cim.iec61968.metering.metering.EndDevice` to disassociate from this `UsagePoint`.
Returns A reference to this `UsagePoint` to allow fluent use.
Raises `ValueError` if `end_device` was not associated with this `UsagePoint`.
"""
self._end_devices = safe_remove(self._end_devices, end_device)
return self
def clear_end_devices(self) -> UsagePoint:
"""
Clear all end_devices.
Returns A reference to this `UsagePoint` to allow fluent use.
"""
self._end_devices = None
return self
def is_metered(self):
"""
Check whether this `UsagePoint` is metered. A `UsagePoint` is metered if it's associated with at least one `EndDevice`.
Returns True if this `UsagePoint` has an `EndDevice`, False otherwise.
"""
return nlen(self._end_devices) > 0
class Meter(EndDevice):
"""
Physical asset that performs the metering role of the usage point. Used for measuring consumption and detection of events.
"""
@property
def company_meter_id(self):
""" Returns this `Meter`s ID. Currently stored in `zepben.cimbend.cim.iec61970.base.core.identified_object.IdentifiedObject.name` """
return self.name
@company_meter_id.setter
def company_meter_id(self, meter_id):
"""
`meter_id` The ID to set for this Meter. Will use `zepben.cimbend.cim.iec61970.base.core.identified_object.IdentifiedObject.name` as a backing field.
"""
self.name = meter_id | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/metering/metering.py | metering.py |
from __future__ import annotations
from dataclassy import dataclass
from typing import List, Optional, Generator, Tuple
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.util import require, nlen, ngen, safe_remove
__all__ = ["PositionPoint", "Location", "StreetAddress", "TownDetail"]
@dataclass(slots=True, frozen=True)
class PositionPoint(object):
"""
Set of spatial coordinates that determine a point, defined in WGS84 (latitudes and longitudes).
Use a single position point instance to desribe a point-oriented location.
Use a sequence of position points to describe a line-oriented object (physical location of non-point oriented
objects like cables or lines), or area of an object (like a substation or a geographical zone - in this case,
have first and last position point with the same values).
"""
x_position: float
"""X axis position - longitude"""
y_position: float
"""Y axis position - latitude"""
def __init__(self):
require(-90.0 <= self.y_position <= 90.0,
lambda: f"Latitude is out of range. Expected -90 to 90, got {self.y_position}.")
require(-180.0 <= self.x_position <= 180.0,
lambda: f"Longitude is out of range. Expected -180 to 180, got {self.x_position}.")
def __str__(self):
return f"{self.x_position}:{self.y_position}"
@property
def longitude(self):
return self.x_position
@property
def latitude(self):
return self.y_position
@dataclass(slots=True)
class TownDetail(object):
"""
Town details, in the context of address.
"""
name: str = ""
"""Town name."""
state_or_province: str = ""
"""Name of the state or province."""
@dataclass(slots=True)
class StreetAddress(object):
"""
General purpose street and postal address information.
"""
postal_code: str = ""
"""Postal code for the address."""
town_detail: Optional[TownDetail] = None
"""Optional `TownDetail` for this address."""
class Location(IdentifiedObject):
"""
The place, scene, or point of something where someone or something has been, is, and/or will be at a given moment in time.
It can be defined with one or more `PositionPoint`'s.
"""
main_address: Optional[StreetAddress] = None
"""Main address of the location."""
_position_points: Optional[List[PositionPoint]] = None
def __init__(self, position_points: List[PositionPoint] = None):
"""
`position_points` A list of `PositionPoint`s to associate with this `Location`.
"""
if position_points:
for point in position_points:
self.add_point(point)
def num_points(self):
"""
Returns The number of `PositionPoint`s in this `Location`
"""
return nlen(self._position_points)
@property
def points(self) -> Generator[Tuple[int, PositionPoint], None, None]:
"""
Returns Generator over the `PositionPoint`s of this `Location`.
"""
for i, point in enumerate(ngen(self._position_points)):
yield i, point
def get_point(self, sequence_number: int) -> Optional[PositionPoint]:
"""
Get the `sequence_number` `PositionPoint` for this `DiagramObject`.
`sequence_number` The sequence number of the `PositionPoint` to get.
Returns The `PositionPoint` identified by `sequence_number`
Raises IndexError if this `Location` didn't contain `sequence_number` points.
"""
return self._position_points[sequence_number] if 0 < nlen(self._position_points) < sequence_number else None
def __getitem__(self, item):
return self.get_point(item)
def add_point(self, point: PositionPoint, sequence_number: int = None) -> Location:
"""
Associate a `PositionPoint` with this `Location`
`point` The `PositionPoint` to associate with this `Location`.
`sequence_number` The sequence number of the `PositionPoint`.
Returns A reference to this `Location` to allow fluent use.
Raises `ValueError` if `sequence_number` is set and not between 0 and `num_points()`
"""
if sequence_number is None:
sequence_number = self.num_points()
require(0 <= sequence_number <= self.num_points(),
lambda: f"Unable to add PositionPoint to Location {str(self)}. Sequence number {sequence_number} is invalid. "
f"Expected a value between 0 and {self.num_points()}. Make sure you are adding the points in order and there are no gaps in the numbering.")
self._position_points = [] if self._position_points is None else self._position_points
self._position_points.insert(sequence_number, point)
return self
def __setitem__(self, key, value):
return self.add_point(value, key)
def remove_point(self, point: PositionPoint) -> Location:
"""
Remove a `PositionPoint` from this `Location`
`point` The `PositionPoint` to remove.
Raises `ValueError` if `point` was not part of this `Location`
Returns A reference to this `Location` to allow fluent use.
"""
self._position_points = safe_remove(self._position_points, point)
return self
def clear_points(self) -> Location:
self._position_points = None
return self | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/cim/iec61968/common/location.py | location.py |
from __future__ import annotations
import logging
from enum import Enum
from typing import Dict, List
from zepben.cimbend.cim.iec61970.base.meas.measurement import Measurement
from zepben.cimbend.common.base_service import BaseService
from zepben.cimbend.cim.iec61970.base.core.connectivity_node import ConnectivityNode
from zepben.cimbend.cim.iec61970.base.wires import EnergySource
from zepben.cimbend.tracing.phasing import SetPhases
from pathlib import Path
__all__ = ["connect", "NetworkService"]
logger = logging.getLogger(__name__)
TRACED_NETWORK_FILE = str(Path.home().joinpath(Path("traced.json")))
class ProcessStatus(Enum):
PROCESSED = 0
INVALID = 1
SKIPPED = 2
def connect(terminal: Terminal, connectivity_node: ConnectivityNode):
"""
Connect a `zepben.cimbend.iec61970.base.core.terminal.Terminal`` to a `ConnectivityNode`
`terminal` The `zepben.cimbend.iec61970.base.core.terminal.Terminal` to connect.
`connectivity_node` The `ConnectivityNode` to connect ``zepben.cimbend.iec61970.base.core.terminal.Terminal` to.
"""
terminal.connect(connectivity_node)
connectivity_node.add_terminal(terminal)
def _attempt_to_reuse_connection(terminal1: Terminal, terminal2: Terminal) -> ProcessStatus:
"""
Attempt to connect two `zepben.cimbend.iec61970.base.core.terminal.Terminal`s.
Returns `ProcessStatus` reflecting whether the connection was reused. PROCESSED if a connection was
established, INVALID if it couldn't be, and SKIPPED if neither terminal had an existing `ConnectivityNode`.
"""
cn1 = terminal1.connectivity_node
cn2 = terminal2.connectivity_node
if cn1 is not None:
if cn2 is not None:
if cn1 is cn2:
return ProcessStatus.PROCESSED
elif connect(terminal2, cn1.mrid):
return ProcessStatus.PROCESSED
return ProcessStatus.INVALID
elif cn2 is not None:
return ProcessStatus.PROCESSED if connect(terminal1, cn2.mrid) else ProcessStatus.INVALID
return ProcessStatus.SKIPPED
class NetworkService(BaseService):
"""
A full representation of the power network.
Contains a map of equipment (string ID's -> Equipment/Nodes/etc)
**All** `IdentifiedObject's` submitted to this Network **MUST** have unique mRID's!
Attributes -
metrics_store : Storage for meter measurement data associated with this network.
"""
name: str = "network"
_connectivity_nodes: Dict[str, ConnectivityNode] = dict()
_auto_cn_index: int = 0
_measurements: Dict[str, List[Measurement]] = []
def __init__(self):
self._objectsByType[ConnectivityNode] = self._connectivity_nodes
def get_measurements(self, mrid: str, t: type) -> List[Measurement]:
"""
Get all measurements of type `t` associated with the given `mrid`.
The `mrid` should be either a `zepben.cimbend.iec61970.base.core.power_system_resource.PowerSystemResource` or a
`zepben.cimbend.iec61970.base.core.terminal.Terminal` MRID that is assigned to the corresponding fields on the measurements.
Returns all `Measurement`s indexed by `mrid` in this service.
Raises `KeyError` if `mrid` isn't present in this service.
"""
return [meas for meas in self._measurements[mrid] if isinstance(meas, t)]
def add_measurement(self, measurement: Measurement) -> bool:
"""
Add a `zepben.cimbend.cim.iec61970.base.meas.measurement.Measurement` to this `NetworkService`
`measurement` The `Measurement` to add.
Returns `True` if `measurement` was added, `False` otherwise
"""
return self._index_measurement(measurement) and self.add(measurement)
def remove_measurement(self, measurement) -> bool:
"""
Remove a `zepben.cimbend.cim.iec61970.base.meas.measurement.Measurement` from this `NetworkService`
`measurement` The `Measurement` to remove.
Returns `True` if `measurement` was removed, `False` otherwise
"""
self._remove_measurement_index(measurement)
return self.remove(measurement)
def connect_by_mrid(self, terminal: Terminal, connectivity_node_mrid: str) -> bool:
"""
Connect a `zepben.cimbend.iec61970.base.core.terminal.Terminal` to the `ConnectivityNode` with mRID `connectivity_node_mrid`
`terminal` The `zepben.cimbend.iec61970.base.core.terminal.Terminal` to connect.
`connectivity_node_mrid` The mRID of the `ConnectivityNode`. Will be created in the `Network` if it
doesn't already exist.
Returns True if the connection was made or already existed, False if `zepben.cimbend.iec61970.base.core.terminal.Terminal` was already connected to a
different `ConnectivityNode`
"""
if not connectivity_node_mrid:
return False
if terminal.connectivity_node:
return connectivity_node_mrid == terminal.connectivity_node.mrid
cn = self.add_connectivitynode(connectivity_node_mrid)
connect(terminal, cn)
return True
def connect_terminals(self, terminal1: Terminal, terminal2: Terminal) -> bool:
"""
Connect two `zepben.cimbend.iec61970.base.core.terminal.Terminal`s
Returns True if the `zepben.cimbend.iec61970.base.core.terminal.Terminal`s could be connected, False otherwise.
"""
status = _attempt_to_reuse_connection(terminal1, terminal2)
if status == ProcessStatus.PROCESSED:
return True
elif status == ProcessStatus.INVALID:
return False
cn = self.add_connectivitynode(self._generate_cn_mrid())
connect(terminal2, cn)
connect(terminal1, cn)
return True
def _generate_cn_mrid(self):
mrid = f"generated_cn_{self._auto_cn_index}"
while mrid in self._connectivity_nodes:
self._auto_cn_index += 1
mrid = f"generated_cn_{self._auto_cn_index}"
return mrid
def disconnect(self, terminal: Terminal):
"""
Disconnect a `zepben.cimbend.iec61970.base.core.terminal.Terminal`` from its `ConnectivityNode`. Will also remove the `ConnectivityNode` from this
`Network` if it no longer has any terminals.
`terminal` The `zepben.cimbend.iec61970.base.core.terminal.Terminal` to disconnect.
"""
cn = terminal.connectivity_node
if cn is None:
return
cn.remove_terminal(terminal)
terminal.disconnect()
if cn.num_terminals() == 0:
del self._connectivity_nodes[cn.mrid]
def disconnect_by_mrid(self, connectivity_node_mrid: str):
"""
Disconnect a `ConnectivityNode` from this `Network`. Will disconnect all ``zepben.cimbend.iec61970.base.core.terminal.Terminal`s from the
`ConnectivityNode`
`connectivity_node_mrid` The mRID of the `ConnectivityNode` to disconnect.
Raises `KeyError` if there is no `ConnectivityNode` for `connectivity_node_mrid`
"""
cn = self._connectivity_nodes[connectivity_node_mrid]
if cn is not None:
for term in cn.terminals:
term.disconnect()
cn.clear_terminals()
del self._connectivity_nodes[connectivity_node_mrid]
def get_primary_sources(self):
"""
Get the primary source for this network. All directions are applied relative to this EnergySource
Returns The primary EnergySource
"""
return [source for source in self._objectsByType[EnergySource].values() if source.has_phases()]
def add_connectivitynode(self, mrid: str):
"""
Add a connectivity node to the network.
`mrid` mRID of the ConnectivityNode
Returns A new ConnectivityNode with `mrid` if it doesn't already exist, otherwise the existing
ConnectivityNode represented by `mrid`
"""
if mrid not in self._connectivity_nodes:
self._connectivity_nodes[mrid] = ConnectivityNode(mrid=mrid)
return self._connectivity_nodes[mrid]
else:
return self._connectivity_nodes[mrid]
async def set_phases(self):
set_phases = SetPhases()
await set_phases.run(self)
def _index_measurement(self, measurement: Measurement, mrid: str) -> bool:
if not mrid:
return False
if mrid in self._measurements:
for meas in self._measurements[mrid]:
if meas.mrid == measurement.mrid:
return False
else:
self._measurements[mrid].append(measurement)
return True
else:
self._measurements[mrid] = [measurement]
return True
def _remove_measurement_index(self, measurement: Measurement):
try:
self._measurements[measurement.terminal_mrid].remove(measurement)
except KeyError:
pass
try:
self._measurements[measurement.power_system_resource_mrid].remove(measurement)
except KeyError:
pass | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/network/network.py | network.py |
from zepben.cimbend.cim.iec61968.assetinfo.wire_info import CableInfo, OverheadWireInfo, WireInfo
from zepben.cimbend.cim.iec61968.assets.asset import Asset, AssetContainer
from zepben.cimbend.cim.iec61968.assets.asset_info import AssetInfo
from zepben.cimbend.cim.iec61968.assets.asset_organisation_role import AssetOwner, AssetOrganisationRole
from zepben.cimbend.cim.iec61968.assets.pole import Pole
from zepben.cimbend.cim.iec61968.assets.streetlight import Streetlight
from zepben.cimbend.cim.iec61968.assets.structure import Structure
from zepben.cimbend.cim.iec61968.common.location import StreetAddress, TownDetail, PositionPoint, Location
from zepben.cimbend.cim.iec61968.metering import EndDevice, UsagePoint, Meter
from zepben.cimbend.cim.iec61968.operations.operational_restriction import OperationalRestriction
from zepben.cimbend.cim.iec61970.base.auxiliaryequipment.auxiliary_equipment import AuxiliaryEquipment, FaultIndicator
from zepben.cimbend.cim.iec61970.base.core import BaseVoltage, ConductingEquipment, PowerSystemResource, Substation
from zepben.cimbend.cim.iec61970.base.core.connectivity_node import ConnectivityNode
from zepben.cimbend.cim.iec61970.base.core.connectivity_node_container import ConnectivityNodeContainer
from zepben.cimbend.cim.iec61970.base.core.equipment import Equipment
from zepben.cimbend.cim.iec61970.base.core.equipment_container import EquipmentContainer, Feeder, Site
from zepben.cimbend.cim.iec61970.base.core.regions import GeographicalRegion, SubGeographicalRegion
from zepben.cimbend.cim.iec61970.base.core.terminal import Terminal, AcDcTerminal
from zepben.cimbend.cim.iec61970.base.wires import Conductor, AcLineSegment, Line, EnergyConnection, RegulatingCondEq, EnergyConsumer, EnergyConsumerPhase, \
EnergySource, EnergySourcePhase, Junction, Connector, LinearShuntCompensator, ShuntCompensator, PerLengthSequenceImpedance, PerLengthLineParameter, \
PerLengthImpedance, PowerTransformer, PowerTransformerEnd, RatioTapChanger, TapChanger, TransformerEnd, Breaker, Disconnector, Fuse, Jumper, \
ProtectedSwitch, Recloser, Switch
from zepben.cimbend.cim.iec61970.base.scada import RemoteControl, RemotePoint, RemoteSource
from zepben.cimbend.cim.iec61970.base.meas import Control, IoPoint, Accumulator, Analog, Discrete, Measurement
from zepben.cimbend.cim.iec61970.infiec61970.feeder import Circuit, Loop
from zepben.cimbend.common.translator.util import mrid_or_empty
from zepben.cimbend.common.translator.base_cim2proto import *
from zepben.cimbend.model.phases import TracedPhases
from zepben.protobuf.cim.iec61968.assetinfo.CableInfo_pb2 import CableInfo as PBCableInfo
from zepben.protobuf.cim.iec61968.assetinfo.OverheadWireInfo_pb2 import OverheadWireInfo as PBOverheadWireInfo
from zepben.protobuf.cim.iec61968.assetinfo.WireInfo_pb2 import WireInfo as PBWireInfo
from zepben.protobuf.cim.iec61968.assetinfo.WireMaterialKind_pb2 import WireMaterialKind as PBWireMaterialKind
from zepben.protobuf.cim.iec61968.assets.AssetContainer_pb2 import AssetContainer as PBAssetContainer
from zepben.protobuf.cim.iec61968.assets.AssetInfo_pb2 import AssetInfo as PBAssetInfo
from zepben.protobuf.cim.iec61968.assets.AssetOrganisationRole_pb2 import AssetOrganisationRole as PBAssetOrganisationRole
from zepben.protobuf.cim.iec61968.assets.AssetOwner_pb2 import AssetOwner as PBAssetOwner
from zepben.protobuf.cim.iec61968.assets.Asset_pb2 import Asset as PBAsset
from zepben.protobuf.cim.iec61968.assets.Pole_pb2 import Pole as PBPole
from zepben.protobuf.cim.iec61968.assets.StreetlightLampKind_pb2 import StreetlightLampKind as PBStreetlightLampKind
from zepben.protobuf.cim.iec61968.assets.Streetlight_pb2 import Streetlight as PBStreetlight
from zepben.protobuf.cim.iec61968.assets.Structure_pb2 import Structure as PBStructure
from zepben.protobuf.cim.iec61968.common.Location_pb2 import Location as PBLocation
from zepben.protobuf.cim.iec61968.common.PositionPoint_pb2 import PositionPoint as PBPositionPoint
from zepben.protobuf.cim.iec61968.common.StreetAddress_pb2 import StreetAddress as PBStreetAddress
from zepben.protobuf.cim.iec61968.common.TownDetail_pb2 import TownDetail as PBTownDetail
from zepben.protobuf.cim.iec61968.metering.EndDevice_pb2 import EndDevice as PBEndDevice
from zepben.protobuf.cim.iec61968.metering.Meter_pb2 import Meter as PBMeter
from zepben.protobuf.cim.iec61968.metering.UsagePoint_pb2 import UsagePoint as PBUsagePoint
from zepben.protobuf.cim.iec61968.operations.OperationalRestriction_pb2 import OperationalRestriction as PBOperationalRestriction
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.AuxiliaryEquipment_pb2 import AuxiliaryEquipment as PBAuxiliaryEquipment
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.FaultIndicator_pb2 import FaultIndicator as PBFaultIndicator
from zepben.protobuf.cim.iec61970.base.core.AcDcTerminal_pb2 import AcDcTerminal as PBAcDcTerminal
from zepben.protobuf.cim.iec61970.base.core.BaseVoltage_pb2 import BaseVoltage as PBBaseVoltage
from zepben.protobuf.cim.iec61970.base.core.ConductingEquipment_pb2 import ConductingEquipment as PBConductingEquipment
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNodeContainer_pb2 import ConnectivityNodeContainer as PBConnectivityNodeContainer
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNode_pb2 import ConnectivityNode as PBConnectivityNode
from zepben.protobuf.cim.iec61970.base.core.EquipmentContainer_pb2 import EquipmentContainer as PBEquipmentContainer
from zepben.protobuf.cim.iec61970.base.core.Equipment_pb2 import Equipment as PBEquipment
from zepben.protobuf.cim.iec61970.base.core.Feeder_pb2 import Feeder as PBFeeder
from zepben.protobuf.cim.iec61970.base.core.GeographicalRegion_pb2 import GeographicalRegion as PBGeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.PhaseCode_pb2 import PhaseCode as PBPhaseCode
from zepben.protobuf.cim.iec61970.base.core.PowerSystemResource_pb2 import PowerSystemResource as PBPowerSystemResource
from zepben.protobuf.cim.iec61970.base.core.Site_pb2 import Site as PBSite
from zepben.protobuf.cim.iec61970.base.core.SubGeographicalRegion_pb2 import SubGeographicalRegion as PBSubGeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.Substation_pb2 import Substation as PBSubstation
from zepben.protobuf.cim.iec61970.base.core.Terminal_pb2 import Terminal as PBTerminal
from zepben.protobuf.cim.iec61970.base.domain.UnitSymbol_pb2 import UnitSymbol as PBUnitSymbol
from zepben.protobuf.cim.iec61970.base.meas.Accumulator_pb2 import Accumulator as PBAccumulator
from zepben.protobuf.cim.iec61970.base.meas.Analog_pb2 import Analog as PBAnalog
from zepben.protobuf.cim.iec61970.base.meas.Control_pb2 import Control as PBControl
from zepben.protobuf.cim.iec61970.base.meas.Discrete_pb2 import Discrete as PBDiscrete
from zepben.protobuf.cim.iec61970.base.meas.IoPoint_pb2 import IoPoint as PBIoPoint
from zepben.protobuf.cim.iec61970.base.meas.Measurement_pb2 import Measurement as PBMeasurement
from zepben.protobuf.cim.iec61970.base.scada.RemoteControl_pb2 import RemoteControl as PBRemoteControl
from zepben.protobuf.cim.iec61970.base.scada.RemoteSource_pb2 import RemoteSource as PBRemoteSource
from zepben.protobuf.cim.iec61970.base.scada.RemotePoint_pb2 import RemotePoint as PBRemotePoint
from zepben.protobuf.cim.iec61970.base.wires.AcLineSegment_pb2 import AcLineSegment as PBAcLineSegment
from zepben.protobuf.cim.iec61970.base.wires.Breaker_pb2 import Breaker as PBBreaker
from zepben.protobuf.cim.iec61970.base.wires.Conductor_pb2 import Conductor as PBConductor
from zepben.protobuf.cim.iec61970.base.wires.Connector_pb2 import Connector as PBConnector
from zepben.protobuf.cim.iec61970.base.wires.Disconnector_pb2 import Disconnector as PBDisconnector
from zepben.protobuf.cim.iec61970.base.wires.EnergyConnection_pb2 import EnergyConnection as PBEnergyConnection
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumerPhase_pb2 import EnergyConsumerPhase as PBEnergyConsumerPhase
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumer_pb2 import EnergyConsumer as PBEnergyConsumer
from zepben.protobuf.cim.iec61970.base.wires.EnergySourcePhase_pb2 import EnergySourcePhase as PBEnergySourcePhase
from zepben.protobuf.cim.iec61970.base.wires.EnergySource_pb2 import EnergySource as PBEnergySource
from zepben.protobuf.cim.iec61970.base.wires.Fuse_pb2 import Fuse as PBFuse
from zepben.protobuf.cim.iec61970.base.wires.Jumper_pb2 import Jumper as PBJumper
from zepben.protobuf.cim.iec61970.base.wires.Junction_pb2 import Junction as PBJunction
from zepben.protobuf.cim.iec61970.base.wires.Line_pb2 import Line as PBLine
from zepben.protobuf.cim.iec61970.base.wires.LinearShuntCompensator_pb2 import LinearShuntCompensator as PBLinearShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.PerLengthImpedance_pb2 import PerLengthImpedance as PBPerLengthImpedance
from zepben.protobuf.cim.iec61970.base.wires.PerLengthLineParameter_pb2 import PerLengthLineParameter as PBPerLengthLineParameter
from zepben.protobuf.cim.iec61970.base.wires.PerLengthSequenceImpedance_pb2 import PerLengthSequenceImpedance as PBPerLengthSequenceImpedance
from zepben.protobuf.cim.iec61970.base.wires.PhaseShuntConnectionKind_pb2 import PhaseShuntConnectionKind as PBPhaseShuntConnectionKind
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformerEnd_pb2 import PowerTransformerEnd as PBPowerTransformerEnd
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformer_pb2 import PowerTransformer as PBPowerTransformer
from zepben.protobuf.cim.iec61970.base.wires.ProtectedSwitch_pb2 import ProtectedSwitch as PBProtectedSwitch
from zepben.protobuf.cim.iec61970.base.wires.RatioTapChanger_pb2 import RatioTapChanger as PBRatioTapChanger
from zepben.protobuf.cim.iec61970.base.wires.Recloser_pb2 import Recloser as PBRecloser
from zepben.protobuf.cim.iec61970.base.wires.RegulatingCondEq_pb2 import RegulatingCondEq as PBRegulatingCondEq
from zepben.protobuf.cim.iec61970.base.wires.ShuntCompensator_pb2 import ShuntCompensator as PBShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind_pb2 import SinglePhaseKind as PBSinglePhaseKind
from zepben.protobuf.cim.iec61970.base.wires.Switch_pb2 import Switch as PBSwitch
from zepben.protobuf.cim.iec61970.base.wires.TapChanger_pb2 import TapChanger as PBTapChanger
from zepben.protobuf.cim.iec61970.base.wires.TransformerEnd_pb2 import TransformerEnd as PBTransformerEnd
from zepben.protobuf.cim.iec61970.base.wires.VectorGroup_pb2 import VectorGroup as PBVectorGroup
from zepben.protobuf.cim.iec61970.base.wires.WindingConnection_pb2 import WindingConnection as PBWindingConnection
from zepben.protobuf.cim.iec61970.infiec61970.feeder.Loop_pb2 import Loop as PBLoop
from zepben.protobuf.cim.iec61970.infiec61970.feeder.Circuit_pb2 import Circuit as PBCircuit
from zepben.protobuf.network.model.TracedPhases_pb2 import TracedPhases as PBTracedPhases
__all__ = ["CimTranslationException", "cableinfo_to_pb", "overheadwireinfo_to_pb", "wireinfo_to_pb", "asset_to_pb",
"assetcontainer_to_pb", "assetinfo_to_pb",
"assetorganisationrole_to_pb", "assetowner_to_pb", "pole_to_pb", "streetlight_to_pb", "structure_to_pb",
"positionpoint_to_pb", "towndetail_to_pb", "streetaddress_to_pb",
"location_to_pb", "enddevice_to_pb", "meter_to_pb", "usagepoint_to_pb", "operationalrestriction_to_pb",
"auxiliaryequipment_to_pb", "faultindicator_to_pb", "acdcterminal_to_pb", "basevoltage_to_pb",
"conductingequipment_to_pb", "connectivitynode_to_pb", "connectivitynodecontainer_to_pb", "equipment_to_pb",
"equipmentcontainer_to_pb", "feeder_to_pb", "geographicalregion_to_pb", "powersystemresource_to_pb", "site_to_pb",
"subgeographicalregion_to_pb", "substation_to_pb", "terminal_to_pb", "perlengthlineparameter_to_pb",
"perlengthimpedance_to_pb", "aclinesegment_to_pb", "breaker_to_pb", "conductor_to_pb", "connector_to_pb",
"disconnector_to_pb", "energyconnection_to_pb", "energyconsumer_to_pb", "energyconsumerphase_to_pb",
"energysource_to_pb", "energysourcephase_to_pb", "fuse_to_pb", "jumper_to_pb", "junction_to_pb",
"linearshuntcompensator_to_pb", "perlengthsequenceimpedance_to_pb", "powertransformer_to_pb",
"powertransformerend_to_pb", "protectedswitch_to_pb", "ratiotapchanger_to_pb", "recloser_to_pb",
"regulatingcondeq_to_pb", "shuntcompensator_to_pb", "switch_to_pb", "tapchanger_to_pb", "transformerend_to_pb",
"tracedphases_to_pb"]
def get_or_none(getter, obj) -> object:
return getter(obj) if obj else None
class CimTranslationException(Exception):
pass
# IEC61968 ASSET INFO #
def cableinfo_to_pb(cim: CableInfo) -> PBCableInfo:
return PBCableInfo(wi=wireinfo_to_pb(cim))
def overheadwireinfo_to_pb(cim: OverheadWireInfo) -> PBOverheadWireInfo:
return PBOverheadWireInfo(wi=wireinfo_to_pb(cim))
def wireinfo_to_pb(cim: WireInfo) -> PBWireInfo:
return PBWireInfo(ai=assetinfo_to_pb(cim),
ratedCurrent=cim.rated_current,
material=PBWireMaterialKind.Value(cim.material.short_name))
# IEC61968 ASSETS #
def asset_to_pb(cim: Asset) -> PBAsset:
return PBAsset(io=identifiedobject_to_pb(cim),
locationMRID=cim.location.mrid if cim.location else None,
organisationRoleMRIDs=[str(io.mrid) for io in cim.organisation_roles])
def assetcontainer_to_pb(cim: AssetContainer) -> PBAssetContainer:
return PBAssetContainer(at=asset_to_pb(cim))
def assetinfo_to_pb(cim: AssetInfo) -> PBAssetInfo:
return PBAssetInfo(io=identifiedobject_to_pb(cim))
def assetorganisationrole_to_pb(cim: AssetOrganisationRole) -> PBAssetOrganisationRole:
pb = PBAssetOrganisationRole()
getattr(pb, "or").CopyFrom(organisationrole_to_pb(cim))
return pb
def assetowner_to_pb(cim: AssetOwner) -> PBAssetOwner:
return PBAssetOwner(aor=assetorganisationrole_to_pb(cim))
def pole_to_pb(cim: Pole) -> PBPole:
return PBPole(st=structure_to_pb(cim), streetlightMRIDs=[str(io.mrid) for io in cim.streetlights], classification=cim.classification)
def streetlight_to_pb(cim: Streetlight) -> PBStreetlight:
return PBStreetlight(at=asset_to_pb(cim),
poleMRID=str(cim.pole.mrid),
lightRating=cim.light_rating,
lampKind=PBStreetlightLampKind.Value(cim.lamp_kind.short_name))
def structure_to_pb(cim: Structure) -> PBStructure:
return PBStructure(ac=assetcontainer_to_pb(cim))
# IEC61968 COMMON #
def location_to_pb(cim: Location) -> PBLocation:
return PBLocation(io=identifiedobject_to_pb(cim),
mainAddress=get_or_none(streetaddress_to_pb, cim.main_address),
positionPoints=[positionpoint_to_pb(point) for _, point in cim.points])
def positionpoint_to_pb(cim: PositionPoint) -> PBPositionPoint:
return PBPositionPoint(xPosition=cim.x_position, yPosition=cim.y_position)
def streetaddress_to_pb(cim: StreetAddress) -> PBStreetAddress:
return PBStreetAddress(postalCode=cim.postal_code, townDetail=get_or_none(towndetail_to_pb, cim.town_detail))
def towndetail_to_pb(cim: TownDetail) -> PBTownDetail:
return PBTownDetail(name=cim.name, stateOrProvince=cim.state_or_province)
# IEC61968 METERING #
def enddevice_to_pb(cim: EndDevice) -> PBEndDevice:
return PBEndDevice(ac=assetcontainer_to_pb(cim),
usagePointMRIDs=[str(io.mrid) for io in cim.usage_points],
customerMRID=cim.customer_mrid,
serviceLocationMRID=mrid_or_empty(cim.service_location))
def meter_to_pb(cim: Meter) -> PBMeter:
return PBMeter(ed=enddevice_to_pb(cim))
def usagepoint_to_pb(cim: UsagePoint) -> PBUsagePoint:
return PBUsagePoint(io=identifiedobject_to_pb(cim),
usagePointLocationMRID=mrid_or_empty(cim.usage_point_location),
equipmentMRIDs=[str(io.mrid) for io in cim.equipment],
endDeviceMRIDs=[str(io.mrid) for io in cim.end_devices])
# IEC61968 OPERATIONS #
def operationalrestriction_to_pb(cim: OperationalRestriction) -> PBOperationalRestriction:
return PBOperationalRestriction(doc=document_to_pb(cim),
equipmentMRIDs=[str(io.mrid) for io in cim.equipment])
# IEC61970 AUXILIARY EQUIPMENT #
def auxiliaryequipment_to_pb(cim: AuxiliaryEquipment) -> PBAuxiliaryEquipment:
return PBAuxiliaryEquipment(eq=equipment_to_pb(cim),
terminalMRID=mrid_or_empty(cim.terminal))
def faultindicator_to_pb(cim: FaultIndicator) -> PBFaultIndicator:
return PBFaultIndicator(ae=auxiliaryequipment_to_pb(cim))
# IEC61970 CORE #
def acdcterminal_to_pb(cim: AcDcTerminal) -> PBAcDcTerminal:
return PBAcDcTerminal(io=identifiedobject_to_pb(cim))
def basevoltage_to_pb(cim: BaseVoltage) -> PBBaseVoltage:
return PBBaseVoltage(io=identifiedobject_to_pb(cim),
nominalVoltage=cim.nominal_voltage)
def conductingequipment_to_pb(cim: ConductingEquipment) -> PBConductingEquipment:
return PBConductingEquipment(eq=equipment_to_pb(cim),
baseVoltageMRID=mrid_or_empty(cim.base_voltage),
terminalMRIDs=[str(io.mrid) for io in cim.terminals])
def connectivitynode_to_pb(cim: ConnectivityNode) -> PBConnectivityNode:
return PBConnectivityNode(io=identifiedobject_to_pb(cim), terminalMRIDs=[str(io.mrid) for io in cim.terminals])
def connectivitynodecontainer_to_pb(cim: ConnectivityNodeContainer) -> PBConnectivityNodeContainer:
return PBConnectivityNodeContainer(psr=powersystemresource_to_pb(cim))
def equipment_to_pb(cim: Equipment) -> PBEquipment:
pb = PBEquipment(psr=powersystemresource_to_pb(cim),
inService=cim.in_service,
normallyInService=cim.normally_in_service,
equipmentContainerMRIDs=[str(io.mrid) for io in cim.equipment_containers],
usagePointMRIDs=[str(io.mrid) for io in cim.usage_points],
operationalRestrictionMRIDs=[str(io.mrid) for io in cim.operational_restrictions],
currentFeederMRIDs=[str(io.mrid) for io in cim.current_feeders])
return pb
def equipmentcontainer_to_pb(cim: EquipmentContainer) -> PBEquipmentContainer:
return PBEquipmentContainer(cnc=connectivitynodecontainer_to_pb(cim),
equipmentMRIDs=[str(io.mrid) for io in cim.equipment])
def feeder_to_pb(cim: Feeder) -> PBFeeder:
return PBFeeder(ec=equipmentcontainer_to_pb(cim),
normalHeadTerminalMRID=mrid_or_empty(cim.normal_head_terminal),
normalEnergizingSubstationMRID=mrid_or_empty(cim.normal_energizing_substation),
currentEquipmentMRIDs=[str(io.mrid) for io in cim.current_equipment])
def geographicalregion_to_pb(cim: GeographicalRegion) -> PBGeographicalRegion:
return PBGeographicalRegion(io=identifiedobject_to_pb(cim),
subGeographicalRegionMRIDs=[str(io.mrid) for io in cim.sub_geographical_regions])
def powersystemresource_to_pb(cim: PowerSystemResource) -> PBPowerSystemResource:
return PBPowerSystemResource(io=identifiedobject_to_pb(cim),
assetInfoMRID=mrid_or_empty(cim.asset_info),
locationMRID=mrid_or_empty(cim.location))
def site_to_pb(cim: Site) -> PBSite:
return PBSite(ec=equipmentcontainer_to_pb(cim))
def subgeographicalregion_to_pb(cim: SubGeographicalRegion) -> PBSubGeographicalRegion:
return PBSubGeographicalRegion(io=identifiedobject_to_pb(cim),
geographicalRegionMRID=mrid_or_empty(cim.geographical_region),
substationMRIDs=[str(io.mrid) for io in cim.substations])
def substation_to_pb(cim: Substation) -> PBSubstation:
return PBSubstation(ec=equipmentcontainer_to_pb(cim),
subGeographicalRegionMRID=mrid_or_empty(cim.sub_geographical_region),
normalEnergizedFeederMRIDs=[str(io.mrid) for io in cim.feeders],
loopMRIDs=[str(io.mrid) for io in cim.loops],
normalEnergizedLoopMRIDs=[str(io.mrid) for io in cim.energized_loops],
circuitMRIDs=[str(io.mrid) for io in cim.circuits])
def terminal_to_pb(cim: Terminal) -> PBTerminal:
return PBTerminal(ad=acdcterminal_to_pb(cim),
conductingEquipmentMRID=mrid_or_empty(cim.conducting_equipment),
connectivityNodeMRID=mrid_or_empty(cim.connectivity_node),
tracedPhases=get_or_none(tracedphases_to_pb, cim.traced_phases),
phases=PBPhaseCode.Value(cim.phases.short_name),
sequenceNumber=cim.sequence_number)
# IEC61970 WIRES #
def aclinesegment_to_pb(cim: AcLineSegment) -> PBAcLineSegment:
return PBAcLineSegment(cd=conductor_to_pb(cim), perLengthSequenceImpedanceMRID=mrid_or_empty(cim.per_length_sequence_impedance))
def breaker_to_pb(cim: Breaker) -> PBBreaker:
return PBBreaker(sw=protectedswitch_to_pb(cim))
def conductor_to_pb(cim: Conductor) -> PBConductor:
return PBConductor(ce=conductingequipment_to_pb(cim), length=cim.length)
def connector_to_pb(cim: Connector) -> PBConnector:
return PBConnector(ce=conductingequipment_to_pb(cim))
def disconnector_to_pb(cim: Disconnector) -> PBDisconnector:
return PBDisconnector(sw=switch_to_pb(cim))
def energyconnection_to_pb(cim: EnergyConnection) -> PBEnergyConnection:
return PBEnergyConnection(ce=conductingequipment_to_pb(cim))
def energyconsumer_to_pb(cim: EnergyConsumer) -> PBEnergyConsumer:
return PBEnergyConsumer(ec=energyconnection_to_pb(cim),
energyConsumerPhasesMRIDs=[str(io.mrid) for io in cim.phases],
customerCount=cim.customer_count,
grounded=cim.grounded,
p=cim.p,
pFixed=cim.p_fixed,
phaseConnection=PBPhaseShuntConnectionKind.Enum.Value(cim.phase_connection.short_name),
q=cim.q,
qFixed=cim.q_fixed)
def energyconsumerphase_to_pb(cim: EnergyConsumerPhase) -> PBEnergyConsumerPhase:
return PBEnergyConsumerPhase(psr=powersystemresource_to_pb(cim),
energyConsumerMRID=mrid_or_empty(cim.energy_consumer),
phase=PBSinglePhaseKind.Value(cim.phase.short_name),
p=cim.p,
pFixed=cim.p_fixed,
q=cim.q,
qFixed=cim.q_fixed)
def energysource_to_pb(cim: EnergySource) -> PBEnergySource:
return PBEnergySource(ec=energyconnection_to_pb(cim),
energySourcePhasesMRIDs=[str(io.mrid) for io in cim.phases],
activePower=cim.active_power,
reactivePower=cim.reactive_power,
voltageAngle=cim.voltage_angle,
voltageMagnitude=cim.voltage_magnitude,
r=cim.r,
x=cim.x,
pMax=cim.p_max,
pMin=cim.p_min,
r0=cim.r0,
rn=cim.rn,
x0=cim.x0,
xn=cim.xn)
def energysourcephase_to_pb(cim: EnergySourcePhase) -> PBEnergySourcePhase:
return PBEnergySourcePhase(psr=powersystemresource_to_pb(cim),
energySourceMRID=mrid_or_empty(cim.energy_source),
phase=PBSinglePhaseKind.Value(cim.phase.short_name))
def fuse_to_pb(cim: Fuse) -> PBFuse:
return PBFuse(sw=switch_to_pb(cim))
def jumper_to_pb(cim: Jumper) -> PBJumper:
return PBJumper(sw=switch_to_pb(cim))
def junction_to_pb(cim: Junction) -> PBJunction:
return PBJunction(cn=connector_to_pb(cim))
def line_to_pb(cim: Line) -> PBLine:
return PBLine(ec=equipmentcontainer_to_pb(cim))
def linearshuntcompensator_to_pb(cim: LinearShuntCompensator) -> PBLinearShuntCompensator:
return PBLinearShuntCompensator(sc=shuntcompensator_to_pb(cim),
b0PerSection=cim.b0_per_section,
bPerSection=cim.b_per_section,
g0PerSection=cim.g0_per_section,
gPerSection=cim.g_per_section)
def perlengthlineparameter_to_pb(cim: PerLengthLineParameter) -> PBPerLengthLineParameter:
return PBPerLengthLineParameter(io=identifiedobject_to_pb(cim))
def perlengthimpedance_to_pb(cim: PerLengthImpedance) -> PBPerLengthImpedance:
return PBPerLengthImpedance(lp=perlengthlineparameter_to_pb(cim))
def perlengthsequenceimpedance_to_pb(cim: PerLengthSequenceImpedance) -> PBPerLengthSequenceImpedance:
return PBPerLengthSequenceImpedance(pli=perlengthimpedance_to_pb(cim),
r=cim.r,
x=cim.x,
r0=cim.r0,
x0=cim.x0,
bch=cim.bch,
gch=cim.gch,
b0ch=cim.b0ch,
g0ch=cim.g0ch)
def powertransformer_to_pb(cim: PowerTransformer) -> PBPowerTransformer:
return PBPowerTransformer(ce=conductingequipment_to_pb(cim),
powerTransformerEndMRIDs=[str(io.mrid) for io in cim.ends],
vectorGroup=PBVectorGroup.Value(cim.vector_group.short_name))
def powertransformerend_to_pb(cim: PowerTransformerEnd) -> PBPowerTransformerEnd:
return PBPowerTransformerEnd(te=transformerend_to_pb(cim),
powerTransformerMRID=mrid_or_empty(cim.power_transformer),
ratedS=cim.rated_s,
ratedU=cim.rated_u,
r=cim.r,
r0=cim.r0,
x=cim.x,
x0=cim.x0,
connectionKind=PBWindingConnection.Value(cim.connection_kind.short_name),
b=cim.b,
b0=cim.b0,
g=cim.g,
g0=cim.g0,
phaseAngleClock=cim.phase_angle_clock)
def protectedswitch_to_pb(cim: ProtectedSwitch) -> PBProtectedSwitch:
return PBProtectedSwitch(sw=switch_to_pb(cim))
def ratiotapchanger_to_pb(cim: RatioTapChanger) -> PBRatioTapChanger:
return PBRatioTapChanger(tc=tapchanger_to_pb(cim),
transformerEndMRID=mrid_or_empty(cim.transformer_end),
stepVoltageIncrement=cim.step_voltage_increment)
def recloser_to_pb(cim: Recloser) -> PBRecloser:
return PBRecloser(sw=protectedswitch_to_pb(cim))
def regulatingcondeq_to_pb(cim: RegulatingCondEq) -> PBRegulatingCondEq:
return PBRegulatingCondEq(ec=energyconnection_to_pb(cim), controlEnabled=cim.control_enabled)
def shuntcompensator_to_pb(cim: ShuntCompensator) -> PBShuntCompensator:
return PBShuntCompensator(rce=regulatingcondeq_to_pb(cim),
sections=cim.sections,
grounded=cim.grounded,
nomU=cim.nom_u,
phaseConnection=PBPhaseShuntConnectionKind.Value(cim.phase_connection))
def switch_to_pb(cim: Switch) -> PBSwitch:
return PBSwitch(ce=conductingequipment_to_pb(cim),
normalOpen=cim.get_normal_state(),
open=cim.get_state())
def tapchanger_to_pb(cim: TapChanger) -> PBTapChanger:
return PBTapChanger(psr=powersystemresource_to_pb(cim),
highStep=cim.high_step,
lowStep=cim.low_step,
step=cim.step,
neutralStep=cim.neutral_step,
neutralU=cim.neutral_u,
normalStep=cim.normal_step,
controlEnabled=cim.control_enabled)
def transformerend_to_pb(cim: TransformerEnd) -> PBTransformerEnd:
return PBTransformerEnd(io=identifiedobject_to_pb(cim),
terminalMRID=mrid_or_empty(cim.terminal),
baseVoltageMRID=mrid_or_empty(cim.base_voltage),
ratioTapChangerMRID=mrid_or_empty(cim.ratio_tap_changer),
endNumber=cim.end_number,
grounded=cim.grounded,
rGround=cim.r_ground,
xGround=cim.x_ground)
def circuit_to_pb(cim: Circuit) -> PBCircuit:
return PBCircuit(l=line_to_pb(cim),
loopMRID=mrid_or_empty(cim.loop.mrid),
endTerminalMRIDs=[str(io.mrid) for io in cim.end_terminals],
endSubstationMRIDs=[str(io.mrid) for io in cim.end_substations])
def loop_to_pb(cim: Loop) -> PBLoop:
return PBLoop(io=identifiedobject_to_pb(cim),
circuitMRIDs=[str(io.mrid) for io in cim.circuits],
substationMRIDs=[str(io.mrid) for io in cim.substations],
normalEnergizingSubstationMRIDs=[str(io.mrid) for io in cim.energizing_substations])
# IEC61970 MEAS #
def control_to_pb(cim: Control) -> PBControl:
return PBControl(ip=iopoint_to_pb(cim),
remoteControlMRID=mrid_or_empty(cim.remote_control),
powerSystemResourceMRID=cim.power_system_resource_mrid)
def iopoint_to_pb(cim: IoPoint) -> PBIoPoint:
return PBIoPoint(io=identifiedobject_to_pb(cim))
def accumulator_to_pb(cim: Accumulator) -> PBAccumulator:
return PBAccumulator(measurement=measurement_to_pb(cim))
def analog_to_pb(cim: Analog) -> PBAnalog:
return PBAnalog(measurement=measurement_to_pb(cim), positiveFlowIn=cim.positive_flow_in)
def discrete_to_pb(cim: Discrete) -> PBDiscrete:
return PBDiscrete(measurement=measurement_to_pb(cim))
def measurement_to_pb(cim: Measurement) -> PBMeasurement:
return PBMeasurement(io=identifiedobject_to_pb(cim),
remoteSourceMRID=mrid_or_empty(cim.remote_source),
powerSystemResourceMRID=cim.power_system_resource_mrid,
terminalMRID=cim.terminal_mrid,
phases=PBPhaseCode.Value(cim.phases.short_name),
unitSymbol=PBUnitSymbol.Value(cim.unitSymbol.short_name))
# IEC61970 SCADA #
def remotecontrol_to_pb(cim: RemoteControl) -> PBRemoteControl:
return PBRemoteControl(rp=remotepoint_to_pb(cim), controlMRID=mrid_or_empty(cim.control))
def remotepoint_to_pb(cim: RemotePoint) -> PBRemotePoint:
return PBRemotePoint(io=identifiedobject_to_pb(cim))
def remotesource_to_pb(cim: RemoteSource) -> PBRemoteSource:
return PBRemoteSource(rp=remotepoint_to_pb(cim), measurementMRID=mrid_or_empty(cim.measurement))
# MODEL #
def tracedphases_to_pb(cim: TracedPhases) -> PBTracedPhases:
return PBTracedPhases(normalStatus=cim._normal_status, currentStatus=cim._current_status)
# Extension functions for each CIM type.
CableInfo.to_pb = lambda self: cableinfo_to_pb(self)
OverheadWireInfo.to_pb = lambda self: overheadwireinfo_to_pb(self)
WireInfo.to_pb = lambda self: wireinfo_to_pb(self)
Asset.to_pb = lambda self: asset_to_pb(self)
AssetContainer.to_pb = lambda self: assetcontainer_to_pb(self)
AssetInfo.to_pb = lambda self: assetinfo_to_pb(self)
AssetOrganisationRole.to_pb = lambda self: assetorganisationrole_to_pb(self)
AssetOwner.to_pb = lambda self: assetowner_to_pb(self)
Pole.to_pb = lambda self: pole_to_pb(self)
Streetlight.to_pb = lambda self: streetlight_to_pb(self)
Structure.to_pb = lambda self: structure_to_pb(self)
PositionPoint.to_pb = lambda self: positionpoint_to_pb(self)
TownDetail.to_pb = lambda self: towndetail_to_pb(self)
StreetAddress.to_pb = lambda self: streetaddress_to_pb(self)
Location.to_pb = lambda self: location_to_pb(self)
EndDevice.to_pb = lambda self: enddevice_to_pb(self)
Meter.to_pb = lambda self: meter_to_pb(self)
UsagePoint.to_pb = lambda self: usagepoint_to_pb(self)
OperationalRestriction.to_pb = lambda self: operationalrestriction_to_pb(self)
AuxiliaryEquipment.to_pb = lambda self: auxiliaryequipment_to_pb(self)
FaultIndicator.to_pb = lambda self: faultindicator_to_pb(self)
AcDcTerminal.to_pb = lambda self: acdcterminal_to_pb(self)
BaseVoltage.to_pb = lambda self: basevoltage_to_pb(self)
ConductingEquipment.to_pb = lambda self: conductingequipment_to_pb(self)
ConnectivityNode.to_pb = lambda self: connectivitynode_to_pb(self)
ConnectivityNodeContainer.to_pb = lambda self: connectivitynodecontainer_to_pb(self)
Equipment.to_pb = lambda self: equipment_to_pb(self)
EquipmentContainer.to_pb = lambda self: equipmentcontainer_to_pb(self)
Feeder.to_pb = lambda self: feeder_to_pb(self)
GeographicalRegion.to_pb = lambda self: geographicalregion_to_pb(self)
PowerSystemResource.to_pb = lambda self: powersystemresource_to_pb(self)
Site.to_pb = lambda self: site_to_pb(self)
SubGeographicalRegion.to_pb = lambda self: subgeographicalregion_to_pb(self)
Substation.to_pb = lambda self: substation_to_pb(self)
Terminal.to_pb = lambda self: terminal_to_pb(self)
PerLengthLineParameter.to_pb = lambda self: perlengthlineparameter_to_pb(self)
PerLengthImpedance.to_pb = lambda self: perlengthimpedance_to_pb(self)
AcLineSegment.to_pb = lambda self: aclinesegment_to_pb(self)
Breaker.to_pb = lambda self: breaker_to_pb(self)
Conductor.to_pb = lambda self: conductor_to_pb(self)
Connector.to_pb = lambda self: connector_to_pb(self)
Disconnector.to_pb = lambda self: disconnector_to_pb(self)
EnergyConnection.to_pb = lambda self: energyconnection_to_pb(self)
EnergyConsumer.to_pb = lambda self: energyconsumer_to_pb(self)
EnergyConsumerPhase.to_pb = lambda self: energyconsumerphase_to_pb(self)
EnergySource.to_pb = lambda self: energysource_to_pb(self)
EnergySourcePhase.to_pb = lambda self: energysourcephase_to_pb(self)
Fuse.to_pb = lambda self: fuse_to_pb(self)
Jumper.to_pb = lambda self: jumper_to_pb(self)
Junction.to_pb = lambda self: junction_to_pb(self)
Line.to_pb = line_to_pb
LinearShuntCompensator.to_pb = lambda self: linearshuntcompensator_to_pb(self)
PerLengthSequenceImpedance.to_pb = lambda self: perlengthsequenceimpedance_to_pb(self)
PowerTransformer.to_pb = lambda self: powertransformer_to_pb(self)
PowerTransformerEnd.to_pb = lambda self: powertransformerend_to_pb(self)
ProtectedSwitch.to_pb = lambda self: protectedswitch_to_pb(self)
RatioTapChanger.to_pb = lambda self: ratiotapchanger_to_pb(self)
Recloser.to_pb = lambda self: recloser_to_pb(self)
RegulatingCondEq.to_pb = lambda self: regulatingcondeq_to_pb(self)
ShuntCompensator.to_pb = lambda self: shuntcompensator_to_pb(self)
Switch.to_pb = lambda self: switch_to_pb(self)
TapChanger.to_pb = lambda self: tapchanger_to_pb(self)
TransformerEnd.to_pb = lambda self: transformerend_to_pb(self)
Circuit.to_pb = circuit_to_pb
Loop.to_pb = loop_to_pb
Control.to_pb = control_to_pb
IoPoint.to_pb = iopoint_to_pb
Accumulator.to_pb = accumulator_to_pb
Analog.to_pb = analog_to_pb
Discrete.to_pb = discrete_to_pb
Measurement.to_pb = measurement_to_pb
RemoteControl.to_pb = remotecontrol_to_pb
RemotePoint.to_pb = remotepoint_to_pb
RemoteSource.to_pb = remotesource_to_pb
TracedPhases.to_pb = tracedphases_to_pb | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/network/translator/network_cim2proto.py | network_cim2proto.py |
from __future__ import annotations
from typing import Optional
from zepben.cimbend import UnitSymbol, unit_symbol_from_id
from zepben.protobuf.cim.iec61968.assetinfo.CableInfo_pb2 import CableInfo as PBCableInfo
from zepben.protobuf.cim.iec61968.assetinfo.OverheadWireInfo_pb2 import OverheadWireInfo as PBOverheadWireInfo
from zepben.protobuf.cim.iec61968.assetinfo.WireInfo_pb2 import WireInfo as PBWireInfo
from zepben.protobuf.cim.iec61968.assets.AssetContainer_pb2 import AssetContainer as PBAssetContainer
from zepben.protobuf.cim.iec61968.assets.AssetInfo_pb2 import AssetInfo as PBAssetInfo
from zepben.protobuf.cim.iec61968.assets.AssetOrganisationRole_pb2 import AssetOrganisationRole as PBAssetOrganisationRole
from zepben.protobuf.cim.iec61968.assets.AssetOwner_pb2 import AssetOwner as PBAssetOwner
from zepben.protobuf.cim.iec61968.assets.Asset_pb2 import Asset as PBAsset
from zepben.protobuf.cim.iec61968.assets.Pole_pb2 import Pole as PBPole
from zepben.protobuf.cim.iec61968.assets.Streetlight_pb2 import Streetlight as PBStreetlight
from zepben.protobuf.cim.iec61968.assets.Structure_pb2 import Structure as PBStructure
from zepben.protobuf.cim.iec61968.common.Location_pb2 import Location as PBLocation
from zepben.protobuf.cim.iec61968.common.PositionPoint_pb2 import PositionPoint as PBPositionPoint
from zepben.protobuf.cim.iec61968.common.StreetAddress_pb2 import StreetAddress as PBStreetAddress
from zepben.protobuf.cim.iec61968.common.TownDetail_pb2 import TownDetail as PBTownDetail
from zepben.protobuf.cim.iec61968.metering.EndDevice_pb2 import EndDevice as PBEndDevice
from zepben.protobuf.cim.iec61968.metering.Meter_pb2 import Meter as PBMeter
from zepben.protobuf.cim.iec61968.metering.UsagePoint_pb2 import UsagePoint as PBUsagePoint
from zepben.protobuf.cim.iec61968.operations.OperationalRestriction_pb2 import OperationalRestriction as PBOperationalRestriction
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.AuxiliaryEquipment_pb2 import AuxiliaryEquipment as PBAuxiliaryEquipment
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.FaultIndicator_pb2 import FaultIndicator as PBFaultIndicator
from zepben.protobuf.cim.iec61970.base.core.AcDcTerminal_pb2 import AcDcTerminal as PBAcDcTerminal
from zepben.protobuf.cim.iec61970.base.core.BaseVoltage_pb2 import BaseVoltage as PBBaseVoltage
from zepben.protobuf.cim.iec61970.base.core.ConductingEquipment_pb2 import ConductingEquipment as PBConductingEquipment
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNodeContainer_pb2 import ConnectivityNodeContainer as PBConnectivityNodeContainer
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNode_pb2 import ConnectivityNode as PBConnectivityNode
from zepben.protobuf.cim.iec61970.base.core.EquipmentContainer_pb2 import EquipmentContainer as PBEquipmentContainer
from zepben.protobuf.cim.iec61970.base.core.Equipment_pb2 import Equipment as PBEquipment
from zepben.protobuf.cim.iec61970.base.core.Feeder_pb2 import Feeder as PBFeeder
from zepben.protobuf.cim.iec61970.base.core.GeographicalRegion_pb2 import GeographicalRegion as PBGeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.PowerSystemResource_pb2 import PowerSystemResource as PBPowerSystemResource
from zepben.protobuf.cim.iec61970.base.core.Site_pb2 import Site as PBSite
from zepben.protobuf.cim.iec61970.base.core.SubGeographicalRegion_pb2 import SubGeographicalRegion as PBSubGeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.Substation_pb2 import Substation as PBSubstation
from zepben.protobuf.cim.iec61970.base.core.Terminal_pb2 import Terminal as PBTerminal
from zepben.protobuf.cim.iec61970.base.wires.AcLineSegment_pb2 import AcLineSegment as PBAcLineSegment
from zepben.protobuf.cim.iec61970.base.wires.Breaker_pb2 import Breaker as PBBreaker
from zepben.protobuf.cim.iec61970.base.wires.Conductor_pb2 import Conductor as PBConductor
from zepben.protobuf.cim.iec61970.base.wires.Connector_pb2 import Connector as PBConnector
from zepben.protobuf.cim.iec61970.base.wires.Disconnector_pb2 import Disconnector as PBDisconnector
from zepben.protobuf.cim.iec61970.base.wires.EnergyConnection_pb2 import EnergyConnection as PBEnergyConnection
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumerPhase_pb2 import EnergyConsumerPhase as PBEnergyConsumerPhase
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumer_pb2 import EnergyConsumer as PBEnergyConsumer
from zepben.protobuf.cim.iec61970.base.wires.EnergySourcePhase_pb2 import EnergySourcePhase as PBEnergySourcePhase
from zepben.protobuf.cim.iec61970.base.wires.EnergySource_pb2 import EnergySource as PBEnergySource
from zepben.protobuf.cim.iec61970.base.wires.Fuse_pb2 import Fuse as PBFuse
from zepben.protobuf.cim.iec61970.base.wires.Jumper_pb2 import Jumper as PBJumper
from zepben.protobuf.cim.iec61970.base.wires.Junction_pb2 import Junction as PBJunction
from zepben.protobuf.cim.iec61970.base.wires.Line_pb2 import Line as PBLine
from zepben.protobuf.cim.iec61970.base.wires.LinearShuntCompensator_pb2 import LinearShuntCompensator as PBLinearShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.PerLengthImpedance_pb2 import PerLengthImpedance as PBPerLengthImpedance
from zepben.protobuf.cim.iec61970.base.wires.PerLengthLineParameter_pb2 import PerLengthLineParameter as PBPerLengthLineParameter
from zepben.protobuf.cim.iec61970.base.wires.PerLengthSequenceImpedance_pb2 import PerLengthSequenceImpedance as PBPerLengthSequenceImpedance
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformerEnd_pb2 import PowerTransformerEnd as PBPowerTransformerEnd
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformer_pb2 import PowerTransformer as PBPowerTransformer
from zepben.protobuf.cim.iec61970.base.wires.ProtectedSwitch_pb2 import ProtectedSwitch as PBProtectedSwitch
from zepben.protobuf.cim.iec61970.base.wires.RatioTapChanger_pb2 import RatioTapChanger as PBRatioTapChanger
from zepben.protobuf.cim.iec61970.base.wires.Recloser_pb2 import Recloser as PBRecloser
from zepben.protobuf.cim.iec61970.base.wires.RegulatingCondEq_pb2 import RegulatingCondEq as PBRegulatingCondEq
from zepben.protobuf.cim.iec61970.base.wires.ShuntCompensator_pb2 import ShuntCompensator as PBShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.Switch_pb2 import Switch as PBSwitch
from zepben.protobuf.cim.iec61970.base.wires.TapChanger_pb2 import TapChanger as PBTapChanger
from zepben.protobuf.cim.iec61970.base.wires.TransformerEnd_pb2 import TransformerEnd as PBTransformerEnd
from zepben.protobuf.cim.iec61970.base.meas.Control_pb2 import Control as PBControl
from zepben.protobuf.cim.iec61970.base.meas.IoPoint_pb2 import IoPoint as PBIoPoint
from zepben.protobuf.cim.iec61970.base.meas.Measurement_pb2 import Measurement as PBMeasurement
from zepben.protobuf.cim.iec61970.base.meas.Accumulator_pb2 import Accumulator as PBAccumulator
from zepben.protobuf.cim.iec61970.base.meas.Analog_pb2 import Analog as PBAnalog
from zepben.protobuf.cim.iec61970.base.meas.Discrete_pb2 import Discrete as PBDiscrete
from zepben.protobuf.cim.iec61970.base.scada.RemoteControl_pb2 import RemoteControl as PBRemoteControl
from zepben.protobuf.cim.iec61970.base.scada.RemotePoint_pb2 import RemotePoint as PBRemotePoint
from zepben.protobuf.cim.iec61970.base.scada.RemoteSource_pb2 import RemoteSource as PBRemoteSource
from zepben.protobuf.cim.iec61970.infiec61970.feeder.Circuit_pb2 import Circuit as PBCircuit
from zepben.protobuf.cim.iec61970.infiec61970.feeder.Loop_pb2 import Loop as PBLoop
from zepben.cimbend.common.translator.base_proto2cim import *
from zepben.cimbend.cim.iec61968.assetinfo import WireMaterialKind, CableInfo, OverheadWireInfo, WireInfo
from zepben.cimbend.cim.iec61968.assets import Asset, AssetContainer, AssetInfo, AssetOwner, AssetOrganisationRole, Pole, Streetlight, StreetlightLampKind, Structure
from zepben.cimbend.cim.iec61968.common.location import StreetAddress, TownDetail, PositionPoint, Location
from zepben.cimbend.cim.iec61968.metering import EndDevice, UsagePoint, Meter
from zepben.cimbend.cim.iec61968.operations.operational_restriction import OperationalRestriction
from zepben.cimbend.cim.iec61970.base.auxiliaryequipment.auxiliary_equipment import AuxiliaryEquipment, FaultIndicator
from zepben.cimbend.cim.iec61970.base.core import Substation, Terminal, AcDcTerminal, GeographicalRegion, SubGeographicalRegion, PowerSystemResource, \
PhaseCode, phasecode_by_id, EquipmentContainer, Feeder, Site, Equipment, ConnectivityNodeContainer, ConductingEquipment, BaseVoltage, ConnectivityNode
from zepben.cimbend.cim.iec61970.base.meas import IoPoint, Control, Measurement, Accumulator, Analog, Discrete
from zepben.cimbend.cim.iec61970.base.scada import RemoteControl, RemotePoint, RemoteSource
from zepben.cimbend.cim.iec61970.base.wires import Conductor, AcLineSegment, Junction, Connector, EnergyConnection, RegulatingCondEq, EnergyConsumer, \
EnergyConsumerPhase, EnergySource, EnergySourcePhase, PerLengthSequenceImpedance, PerLengthLineParameter, PerLengthImpedance, PhaseShuntConnectionKind, \
PowerTransformer, PowerTransformerEnd, RatioTapChanger, TapChanger, TransformerEnd, Line, LinearShuntCompensator, ShuntCompensator, Breaker, Disconnector, \
Fuse, Jumper, ProtectedSwitch, Recloser, Switch, VectorGroup, WindingConnection, phasekind_by_id
from zepben.cimbend.cim.iec61970.infiec61970.feeder import Loop, Circuit
from zepben.cimbend.common.translator.base_proto2cim import BaseProtoToCim
from zepben.cimbend.network.network import NetworkService
from zepben.cimbend.common import resolver
__all__ = ["cableinfo_to_cim", "overheadwireinfo_to_cim", "wireinfo_to_cim", "asset_to_cim", "assetcontainer_to_cim", "assetinfo_to_cim",
"assetorganisationrole_to_cim", "assetowner_to_cim", "pole_to_cim", "streetlight_to_cim", "structure_to_cim", "location_to_cim",
"positionpoint_to_cim", "streetaddress_to_cim", "towndetail_to_cim", "enddevice_to_cim", "meter_to_cim", "usagepoint_to_cim",
"operationalrestriction_to_cim", "auxiliaryequipment_to_cim", "faultindicator_to_cim", "acdcterminal_to_cim", "basevoltage_to_cim",
"conductingequipment_to_cim", "connectivitynode_to_cim", "connectivitynodecontainer_to_cim", "equipment_to_cim", "equipmentcontainer_to_cim",
"feeder_to_cim", "geographicalregion_to_cim", "powersystemresource_to_cim", "site_to_cim", "subgeographicalregion_to_cim", "substation_to_cim",
"terminal_to_cim", "accumulator_to_cim", "analog_to_cim", "control_to_cim", "discrete_to_cim", "iopoint_to_cim", "measurement_to_cim",
"remotecontrol_to_cim", "remotepoint_to_cim", "remotesource_to_cim", "aclinesegment_to_cim", "breaker_to_cim", "conductor_to_cim",
"connector_to_cim", "disconnector_to_cim", "energyconnection_to_cim", "energyconsumer_to_cim", "energyconsumerphase_to_cim", "energysource_to_cim",
"energysourcephase_to_cim", "fuse_to_cim", "jumper_to_cim", "junction_to_cim", "line_to_cim", "linearshuntcompensator_to_cim",
"perlengthlineparameter_to_cim", "perlengthimpedance_to_cim", "perlengthsequenceimpedance_to_cim", "powertransformer_to_cim",
"powertransformerend_to_cim", "protectedswitch_to_cim", "ratiotapchanger_to_cim", "recloser_to_cim", "regulatingcondeq_to_cim",
"shuntcompensator_to_cim", "switch_to_cim", "tapchanger_to_cim", "transformerend_to_cim", "PBPerLengthImpedance", "circuit_to_cim", "loop_to_cim",
"_add_from_pb", "NetworkProtoToCim"]
### IEC61968 ASSET INFO
def cableinfo_to_cim(pb: PBCableInfo, network_service: NetworkService) -> Optional[CableInfo]:
cim = CableInfo(mrid=pb.mrid())
wireinfo_to_cim(pb.wi, cim, network_service)
return cim if network_service.add(cim) else None
def overheadwireinfo_to_cim(pb: PBOverheadWireInfo, network_service: NetworkService) -> Optional[OverheadWireInfo]:
cim = OverheadWireInfo(mrid=pb.mrid())
wireinfo_to_cim(pb.wi, cim, network_service)
return cim if network_service.add(cim) else None
def wireinfo_to_cim(pb: PBWireInfo, cim: WireInfo, network_service: NetworkService):
cim.rated_current = pb.ratedCurrent
cim.material = WireMaterialKind(pb.material)
assetinfo_to_cim(pb.ai, cim, network_service)
PBCableInfo.to_cim = cableinfo_to_cim
PBOverheadWireInfo.to_cim = overheadwireinfo_to_cim
PBWireInfo.to_cim = wireinfo_to_cim
### IEC61968 ASSETS
def asset_to_cim(pb: PBAsset, cim: Asset, network_service: NetworkService):
network_service.resolve_or_defer_reference(resolver.at_location(cim), pb.locationMRID)
for mrid in pb.organisationRoleMRIDs:
network_service.resolve_or_defer_reference(resolver.organisation_roles(cim), mrid)
identifiedobject_to_cim(pb.io, cim, network_service)
def assetcontainer_to_cim(pb: PBAssetContainer, cim: AssetContainer, network_service: NetworkService):
asset_to_cim(pb.at, cim, network_service)
def assetinfo_to_cim(pb: PBAssetInfo, cim: AssetInfo, network_service: NetworkService):
identifiedobject_to_cim(pb.io, cim, network_service)
def assetorganisationrole_to_cim(pb: PBAssetOrganisationRole, cim: AssetOrganisationRole,
network_service: NetworkService):
organisationrole_to_cim(getattr(pb, 'or'), cim, network_service)
def assetowner_to_cim(pb: PBAssetOwner, network_service: NetworkService) -> Optional[AssetOwner]:
cim = AssetOwner(mrid=pb.mrid())
assetorganisationrole_to_cim(pb.aor, cim, network_service)
return cim if network_service.add(cim) else None
def pole_to_cim(pb: PBPole, network_service: NetworkService) -> Optional[Pole]:
cim = Pole(mrid=pb.mrid(), classification=pb.classification)
for mrid in pb.streetlightMRIDs:
network_service.resolve_or_defer_reference(resolver.streetlights(cim), mrid)
structure_to_cim(pb.st, cim, network_service)
return cim if network_service.add(cim) else None
def streetlight_to_cim(pb: PBStreetlight, network_service: NetworkService) -> Optional[Streetlight]:
cim = Streetlight(mrid=pb.mrid(), light_rating=pb.lightRating, lamp_kind=StreetlightLampKind(pb.lampKind))
network_service.resolve_or_defer_reference(resolver.pole(cim), pb.poleMRID)
asset_to_cim(pb.at, cim, network_service)
return cim if network_service.add(cim) else None
def structure_to_cim(pb: PBStructure, cim: Structure, network_service: NetworkService):
assetcontainer_to_cim(pb.ac, cim, network_service)
PBAsset.to_cim = asset_to_cim
PBAssetContainer.to_cim = assetcontainer_to_cim
PBAssetInfo.to_cim = assetinfo_to_cim
PBAssetOrganisationRole.to_cim = assetorganisationrole_to_cim
PBAssetOwner.to_cim = assetowner_to_cim
PBPole.to_cim = pole_to_cim
PBStreetlight.to_cim = streetlight_to_cim
PBStructure.to_cim = structure_to_cim
### IEC61968 COMMON
def location_to_cim(pb: PBLocation, network_service: NetworkService) -> Optional[Location]:
cim = Location(mrid=pb.mrid(), main_address=streetaddress_to_cim(pb.mainAddress) if pb.HasField('mainAddress') else None)
for point in pb.positionPoints:
cim.add_point(positionpoint_to_cim(point))
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
def positionpoint_to_cim(pb: PBPositionPoint) -> Optional[PositionPoint]:
return PositionPoint(pb.xPosition, pb.yPosition)
def streetaddress_to_cim(pb: PBStreetAddress) -> Optional[StreetAddress]:
return StreetAddress(postal_code=pb.postalCode, town_detail=towndetail_to_cim(pb.townDetail) if pb.HasField('townDetail') else None)
def towndetail_to_cim(pb: PBTownDetail) -> Optional[TownDetail]:
return TownDetail(name=pb.name, state_or_province=pb.stateOrProvince)
PBLocation.to_cim = location_to_cim
PBPositionPoint.to_cim = positionpoint_to_cim
PBTownDetail.to_cim = towndetail_to_cim
PBStreetAddress.to_cim = streetaddress_to_cim
### IEC61968 METERING
def enddevice_to_cim(pb: PBEndDevice, cim: EndDevice, network_service: NetworkService):
for mrid in pb.usagePointMRIDs:
network_service.resolve_or_defer_reference(resolver.ed_usage_points(cim), mrid)
cim.customer_mrid = pb.customerMRID if pb.customerMRID else None
network_service.resolve_or_defer_reference(resolver.service_location(cim), pb.serviceLocationMRID)
assetcontainer_to_cim(pb.ac, cim, network_service)
def meter_to_cim(pb: PBMeter, network_service: NetworkService) -> Optional[Meter]:
cim = Meter(mrid=pb.mrid())
enddevice_to_cim(pb.ed, cim, network_service)
return cim if network_service.add(cim) else None
def usagepoint_to_cim(pb: PBUsagePoint, network_service: NetworkService) -> Optional[UsagePoint]:
cim = UsagePoint(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.usage_point_location(cim), pb.usagePointLocationMRID)
for mrid in pb.equipmentMRIDs:
network_service.resolve_or_defer_reference(resolver.up_equipment(cim), mrid)
for mrid in pb.endDeviceMRIDs:
network_service.resolve_or_defer_reference(resolver.end_devices(cim), mrid)
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
PBEndDevice.to_cim = enddevice_to_cim
PBMeter.to_cim = meter_to_cim
PBUsagePoint.to_cim = usagepoint_to_cim
### IEC61968 OPERATIONS
def operationalrestriction_to_cim(pb: PBOperationalRestriction, network_service: NetworkService) -> Optional[OperationalRestriction]:
cim = OperationalRestriction(mrid=pb.mrid())
for mrid in pb.equipmentMRIDs:
network_service.resolve_or_defer_reference(resolver.or_equipment(cim), mrid)
document_to_cim(pb.doc, cim, network_service)
return cim if network_service.add(cim) else None
PBOperationalRestriction.to_cim = operationalrestriction_to_cim
### IEC61970 AUXILIARY EQUIPMENT
def auxiliaryequipment_to_cim(pb: PBAuxiliaryEquipment, cim: AuxiliaryEquipment, network_service: NetworkService):
network_service.resolve_or_defer_reference(resolver.ae_terminal(cim), pb.terminalMRID)
equipment_to_cim(pb.eq, cim, network_service)
def faultindicator_to_cim(pb: PBFaultIndicator, network_service: NetworkService) -> Optional[FaultIndicator]:
cim = FaultIndicator(mrid=pb.mrid())
auxiliaryequipment_to_cim(pb.ae, cim, network_service)
return cim if network_service.add(cim) else None
PBAuxiliaryEquipment.to_cim = auxiliaryequipment_to_cim
PBFaultIndicator.to_cim = faultindicator_to_cim
### IEC61970 CORE
def acdcterminal_to_cim(pb: PBAcDcTerminal, cim: AcDcTerminal, network_service: NetworkService):
identifiedobject_to_cim(pb.io, cim, network_service)
def basevoltage_to_cim(pb: PBBaseVoltage, network_service: NetworkService) -> Optional[BaseVoltage]:
cim = BaseVoltage(mrid=pb.mrid())
cim.nominal_voltage = pb.nominalVoltage
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
def conductingequipment_to_cim(pb: PBConductingEquipment, cim: ConductingEquipment, network_service: NetworkService):
network_service.resolve_or_defer_reference(resolver.ce_base_voltage(cim), pb.baseVoltageMRID)
for mrid in pb.terminalMRIDs:
network_service.resolve_or_defer_reference(resolver.ce_terminals(cim), mrid)
equipment_to_cim(pb.eq, cim, network_service)
def connectivitynode_to_cim(pb: PBConnectivityNode, network_service: NetworkService) -> Optional[ConnectivityNode]:
cim = ConnectivityNode(mrid=pb.mrid())
for mrid in pb.terminalMRIDs:
network_service.resolve_or_defer_reference(resolver.cn_terminals(cim), mrid)
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
def connectivitynodecontainer_to_cim(pb: PBConnectivityNodeContainer, cim: ConnectivityNodeContainer,
network_service: NetworkService):
powersystemresource_to_cim(pb.psr, cim, network_service)
def equipment_to_cim(pb: PBEquipment, cim: Equipment, network_service: NetworkService):
cim.in_service = pb.inService
cim.normally_in_service = pb.normallyInService
for mrid in pb.equipmentContainerMRIDs:
network_service.resolve_or_defer_reference(resolver.containers(cim), mrid)
for mrid in pb.usagePointMRIDs:
network_service.resolve_or_defer_reference(resolver.eq_usage_points(cim), mrid)
for mrid in pb.operationalRestrictionMRIDs:
network_service.resolve_or_defer_reference(resolver.operational_restrictions(cim), mrid)
for mrid in pb.currentFeederMRIDs:
network_service.resolve_or_defer_reference(resolver.current_feeders(cim), mrid)
powersystemresource_to_cim(pb.psr, cim, network_service)
def equipmentcontainer_to_cim(pb: PBEquipmentContainer, cim: EquipmentContainer, network_service: NetworkService):
for mrid in pb.equipmentMRIDs:
network_service.resolve_or_defer_reference(resolver.ec_equipment(cim), mrid)
connectivitynodecontainer_to_cim(pb.cnc, cim, network_service)
def feeder_to_cim(pb: PBFeeder, network_service: NetworkService) -> Optional[Feeder]:
cim = Feeder(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.normal_head_terminal(cim), pb.normalHeadTerminalMRID)
network_service.resolve_or_defer_reference(resolver.normal_energizing_substation(cim), pb.normalEnergizingSubstationMRID)
for mrid in pb.currentEquipmentMRIDs:
network_service.resolve_or_defer_reference(resolver.current_equipment(cim), mrid)
equipmentcontainer_to_cim(pb.ec, cim, network_service)
return cim if network_service.add(cim) else None
def geographicalregion_to_cim(pb: PBGeographicalRegion, network_service: NetworkService) -> Optional[GeographicalRegion]:
cim = GeographicalRegion(mrid=pb.mrid())
for mrid in pb.subGeographicalRegionMRIDs:
network_service.resolve_or_defer_reference(resolver.sub_geographical_regions(cim), mrid)
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
def powersystemresource_to_cim(pb: PBPowerSystemResource, cim: PowerSystemResource, network_service: NetworkService):
network_service.resolve_or_defer_reference(resolver.psr_location(cim), pb.locationMRID)
identifiedobject_to_cim(pb.io, cim, network_service)
def site_to_cim(pb: PBSite, network_service: NetworkService) -> Optional[Site]:
cim = Site(mrid=pb.mrid())
equipmentcontainer_to_cim(pb.ec, cim, network_service)
return cim if network_service.add(cim) else None
def subgeographicalregion_to_cim(pb: PBSubGeographicalRegion, network_service: NetworkService) -> Optional[SubGeographicalRegion]:
cim = SubGeographicalRegion(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.geographical_region(cim), pb.geographicalRegionMRID)
for mrid in pb.substationMRIDs:
network_service.resolve_or_defer_reference(resolver.substations(cim), mrid)
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
def substation_to_cim(pb: PBSubstation, network_service: NetworkService) -> Optional[Substation]:
cim = Substation(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.sub_geographical_region(cim), pb.subGeographicalRegionMRID)
for mrid in pb.normalEnergizedFeederMRIDs:
network_service.resolve_or_defer_reference(resolver.normal_energizing_feeders(cim), mrid)
for mrid in pb.loopMRIDs:
network_service.resolve_or_defer_reference(resolver.loops(cim), mrid)
for mrid in pb.normalEnergizedLoopMRIDs:
network_service.resolve_or_defer_reference(resolver.normal_energized_loops(cim), mrid)
for mrid in pb.circuitMRIDs:
network_service.resolve_or_defer_reference(resolver.circuits(cim), mrid)
equipmentcontainer_to_cim(pb.ec, cim, network_service)
return cim if network_service.add(cim) else None
def terminal_to_cim(pb: PBTerminal, network_service: NetworkService) -> Optional[Terminal]:
cim = Terminal(mrid=pb.mrid(), phases=phasecode_by_id(pb.phases), sequence_number=pb.sequenceNumber)
network_service.resolve_or_defer_reference(resolver.conducting_equipment(cim), pb.conductingEquipmentMRID)
cim.traced_phases._normal_status = pb.tracedPhases.normalStatus
cim.traced_phases._current_status = pb.tracedPhases.currentStatus
network_service.resolve_or_defer_reference(resolver.connectivity_node(cim), pb.connectivityNodeMRID)
acdcterminal_to_cim(pb.ad, cim, network_service)
return cim if network_service.add(cim) else None
PBAcDcTerminal.to_cim = acdcterminal_to_cim
PBBaseVoltage.to_cim = basevoltage_to_cim
PBConductingEquipment.to_cim = conductingequipment_to_cim
PBConnectivityNode.to_cim = connectivitynode_to_cim
PBConnectivityNodeContainer.to_cim = connectivitynodecontainer_to_cim
PBEquipment.to_cim = equipment_to_cim
PBEquipmentContainer.to_cim = equipmentcontainer_to_cim
PBFeeder.to_cim = feeder_to_cim
PBGeographicalRegion.to_cim = geographicalregion_to_cim
PBPowerSystemResource.to_cim = powersystemresource_to_cim
PBSite.to_cim = site_to_cim
PBSubGeographicalRegion.to_cim = subgeographicalregion_to_cim
PBSubstation.to_cim = substation_to_cim
PBTerminal.to_cim = terminal_to_cim
### IEC61970 MEAS ###
def accumulator_to_cim(pb: PBAccumulator, network_service: NetworkService) -> Optional[Accumulator]:
cim = Accumulator(mrid=pb.mrid())
measurement_to_cim(pb.measurement, cim, network_service)
return cim if network_service.add(cim) else None
def analog_to_cim(pb: PBAnalog, network_service: NetworkService) -> Optional[Analog]:
cim = Analog(mrid=pb.mrid(), positive_flow_in=pb.positiveFlowIn)
measurement_to_cim(pb.measurement, cim, network_service)
return cim if network_service.add(cim) else None
def control_to_cim(pb: PBControl, network_service: NetworkService) -> Optional[Control]:
cim = Control(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.remote_control(cim), pb.remoteControlMRID)
iopoint_to_cim(pb.ip, cim, network_service)
return cim if network_service.add(cim) else None
def discrete_to_cim(pb: PBDiscrete, network_service: NetworkService) -> Optional[Discrete]:
cim = Discrete(mrid=pb.mrid())
measurement_to_cim(pb.measurement, cim, network_service)
return cim if network_service.add(cim) else None
def iopoint_to_cim(pb: PBIoPoint, cim: IoPoint, service: NetworkService):
identifiedobject_to_cim(pb.io, cim, service)
def measurement_to_cim(pb: PBMeasurement, cim: Measurement, service: NetworkService):
cim.power_system_resource_mrid = pb.powerSystemResourceMRID
cim.terminal_mrid = pb.terminalMRID
cim.phases = phasecode_by_id(pb.phases)
cim.unitSymbol = unit_symbol_from_id(pb.unitSymbol)
service.resolve_or_defer_reference(resolver.remote_source(cim), pb.remoteSourceMRID)
identifiedobject_to_cim(pb.io, cim, service)
PBAccumulator.to_cim = accumulator_to_cim
PBAnalog.to_cim = analog_to_cim
PBControl.to_cim = control_to_cim
PBDiscrete.to_cim = discrete_to_cim
PBIoPoint.to_cim = iopoint_to_cim
PBMeasurement.to_cim = measurement_to_cim
# IEC61970 SCADA #
def remotecontrol_to_cim(pb: PBRemoteControl, network_service: NetworkService) -> Optional[RemoteControl]:
cim = RemoteControl(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.control(cim), pb.controlMRID)
remotepoint_to_cim(pb.rp, cim, network_service)
return cim if network_service.add(cim) else None
def remotepoint_to_cim(pb: PBRemotePoint, cim: RemotePoint, service: NetworkService):
identifiedobject_to_cim(pb.io, cim, service)
def remotesource_to_cim(pb: PBRemoteSource, network_service: NetworkService) -> Optional[RemoteSource]:
cim = RemoteSource(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.measurement(cim), pb.measurementMRID)
remotepoint_to_cim(pb.rp, cim, network_service)
return cim if network_service.add(cim) else None
PBRemoteControl.to_cim = remotecontrol_to_cim
PBRemotePoint.to_cim = remotepoint_to_cim
PBRemoteSource.to_cim = remotesource_to_cim
### IEC61970 WIRES
def aclinesegment_to_cim(pb: PBAcLineSegment, network_service: NetworkService) -> Optional[AcLineSegment]:
cim = AcLineSegment(mrid=pb.mrid())
network_service.resolve_or_defer_reference(resolver.per_length_sequence_impedance(cim), pb.perLengthSequenceImpedanceMRID)
conductor_to_cim(pb.cd, cim, network_service)
return cim if network_service.add(cim) else None
def breaker_to_cim(pb: PBBreaker, network_service: NetworkService) -> Optional[Breaker]:
cim = Breaker(mrid=pb.mrid())
protectedswitch_to_cim(pb.sw, cim, network_service)
return cim if network_service.add(cim) else None
def conductor_to_cim(pb: PBConductor, cim: Conductor, network_service: NetworkService):
cim.length = pb.length
network_service.resolve_or_defer_reference(resolver.asset_info(cim), pb.asset_info_mrid())
conductingequipment_to_cim(pb.ce, cim, network_service)
def connector_to_cim(pb: PBConnector, cim: Connector, network_service: NetworkService):
conductingequipment_to_cim(pb.ce, cim, network_service)
def disconnector_to_cim(pb: PBDisconnector, network_service: NetworkService) -> Optional[Disconnector]:
cim = Disconnector(mrid=pb.mrid())
switch_to_cim(pb.sw, cim, network_service)
return cim if network_service.add(cim) else None
def energyconnection_to_cim(pb: PBEnergyConnection, cim: EnergyConnection, network_service: NetworkService):
conductingequipment_to_cim(pb.ce, cim, network_service)
def energyconsumer_to_cim(pb: PBEnergyConsumer, network_service: NetworkService) -> Optional[EnergyConsumer]:
cim = EnergyConsumer(mrid=pb.mrid(), customer_count=pb.customerCount, grounded=pb.grounded, p=pb.p, p_fixed=pb.pFixed, q=pb.q, q_fixed=pb.qFixed,
phase_connection=PhaseShuntConnectionKind(pb.phaseConnection))
for mrid in pb.energyConsumerPhasesMRIDs:
network_service.resolve_or_defer_reference(resolver.ec_phases(cim), mrid)
energyconnection_to_cim(pb.ec, cim, network_service)
return cim if network_service.add(cim) else None
def energyconsumerphase_to_cim(pb: PBEnergyConsumerPhase, network_service: NetworkService) -> Optional[EnergyConsumerPhase]:
cim = EnergyConsumerPhase(mrid=pb.mrid(), phase=phasekind_by_id(pb.phase), p=pb.p, p_fixed=pb.pFixed, q=pb.q, q_fixed=pb.qFixed)
network_service.resolve_or_defer_reference(resolver.energy_consumer(cim), pb.energyConsumerMRID)
powersystemresource_to_cim(pb.psr, cim, network_service)
return cim if network_service.add(cim) else None
def energysource_to_cim(pb: PBEnergySource, network_service: NetworkService) -> Optional[EnergySource]:
cim = EnergySource(mrid=pb.mrid(), active_power=pb.activePower, reactive_power=pb.reactivePower, voltage_angle=pb.voltageAngle,
voltage_magnitude=pb.voltageMagnitude, r=pb.r, x=pb.x, p_max=pb.pMax, p_min=pb.pMin, r0=pb.r0, rn=pb.rn, x0=pb.x0, xn=pb.xn)
for mrid in pb.energySourcePhasesMRIDs:
network_service.resolve_or_defer_reference(resolver.es_phases(cim), mrid)
energyconnection_to_cim(pb.ec, cim, network_service)
return cim if network_service.add(cim) else None
def energysourcephase_to_cim(pb: PBEnergySourcePhase, network_service: NetworkService) -> Optional[EnergySourcePhase]:
cim = EnergySourcePhase(mrid=pb.mrid(), phase=phasekind_by_id(pb.phase))
network_service.resolve_or_defer_reference(resolver.energy_source(cim), pb.energySourceMRID)
powersystemresource_to_cim(pb.psr, cim, network_service)
return cim if network_service.add(cim) else None
def fuse_to_cim(pb: PBFuse, network_service: NetworkService) -> Optional[Fuse]:
cim = Fuse(mrid=pb.mrid())
switch_to_cim(pb.sw, cim, network_service)
return cim if network_service.add(cim) else None
def jumper_to_cim(pb: PBJumper, network_service: NetworkService) -> Optional[Jumper]:
cim = Jumper(mrid=pb.mrid())
switch_to_cim(pb.sw, cim, network_service)
return cim if network_service.add(cim) else None
def junction_to_cim(pb: PBJunction, network_service: NetworkService) -> Optional[Junction]:
cim = Junction(mrid=pb.mrid())
connector_to_cim(pb.cn, cim, network_service)
return cim if network_service.add(cim) else None
def line_to_cim(pb: PBLine, cim: Line, network_service: NetworkService):
equipmentcontainer_to_cim(pb.ec, cim, network_service)
def linearshuntcompensator_to_cim(pb: PBLinearShuntCompensator, network_service: NetworkService) -> Optional[LinearShuntCompensator]:
cim = LinearShuntCompensator(mrid=pb.mrid(), b0_per_section=pb.b0PerSection, b_per_section=pb.bPerSection, g0_per_section=pb.g0PerSection,
g_per_section=pb.gPerSection)
shuntcompensator_to_cim(pb.sc, cim, network_service)
return cim if network_service.add(cim) else None
def perlengthlineparameter_to_cim(pb: PBPerLengthLineParameter, cim: PerLengthLineParameter,
network_service: NetworkService):
identifiedobject_to_cim(pb.io, cim, network_service)
def perlengthimpedance_to_cim(pb: PBPerLengthImpedance, cim: PerLengthImpedance, network_service: NetworkService):
perlengthlineparameter_to_cim(pb.lp, cim, network_service)
def perlengthsequenceimpedance_to_cim(pb: PBPerLengthSequenceImpedance, network_service: NetworkService) -> Optional[PerLengthSequenceImpedance]:
cim = PerLengthSequenceImpedance(mrid=pb.mrid(), r=pb.r, x=pb.x, r0=pb.r0, x0=pb.x0, bch=pb.bch, gch=pb.gch, b0ch=pb.b0ch, g0ch=pb.g0ch)
perlengthimpedance_to_cim(pb.pli, cim, network_service)
return cim if network_service.add(cim) else None
def powertransformer_to_cim(pb: PBPowerTransformer, network_service: NetworkService) -> Optional[PowerTransformer]:
cim = PowerTransformer(mrid=pb.mrid(), vector_group=VectorGroup(pb.vectorGroup))
for mrid in pb.powerTransformerEndMRIDs:
network_service.resolve_or_defer_reference(resolver.ends(cim), mrid)
conductingequipment_to_cim(pb.ce, cim, network_service)
return cim if network_service.add(cim) else None
def powertransformerend_to_cim(pb: PBPowerTransformerEnd, network_service: NetworkService) -> Optional[PowerTransformerEnd]:
cim = PowerTransformerEnd(mrid=pb.mrid(), rated_s=pb.ratedS, rated_u=pb.ratedU, r=pb.r, r0=pb.r0, x=pb.x, x0=pb.x0, b=pb.b, b0=pb.b0, g=pb.g, g0=pb.g0,
connection_kind=WindingConnection(pb.connectionKind), phase_angle_clock=pb.phaseAngleClock)
network_service.resolve_or_defer_reference(resolver.power_transformer(cim), pb.powerTransformerMRID)
transformerend_to_cim(pb.te, cim, network_service)
return cim if network_service.add(cim) else None
def protectedswitch_to_cim(pb: PBProtectedSwitch, cim: ProtectedSwitch, network_service: NetworkService):
switch_to_cim(pb.sw, cim, network_service)
def ratiotapchanger_to_cim(pb: PBRatioTapChanger, network_service: NetworkService) -> Optional[RatioTapChanger]:
cim = RatioTapChanger(mrid=pb.mrid(), step_voltage_increment=pb.stepVoltageIncrement)
tapchanger_to_cim(pb.tc, cim, network_service)
return cim if network_service.add(cim) else None
def recloser_to_cim(pb: PBRecloser, network_service: NetworkService) -> Optional[Recloser]:
cim = Recloser(mrid=pb.mrid())
protectedswitch_to_cim(pb.sw, cim, network_service)
return cim if network_service.add(cim) else None
def regulatingcondeq_to_cim(pb: PBRegulatingCondEq, cim: RegulatingCondEq, network_service: NetworkService):
cim.control_enabled = pb.controlEnabled
energyconnection_to_cim(pb.ec, cim, network_service)
def shuntcompensator_to_cim(pb: PBShuntCompensator, cim: ShuntCompensator, network_service: NetworkService):
cim.sections = pb.sections
cim.grounded = pb.grounded
cim.nom_u = pb.nomU
cim.phase_connection = PhaseShuntConnectionKind(pb.phaseConnection)
regulatingcondeq_to_cim(pb.rce, cim, network_service)
def switch_to_cim(pb: PBSwitch, cim: Switch, network_service: NetworkService):
cim.set_normally_open(pb.normalOpen)
cim.set_open(pb.open)
conductingequipment_to_cim(pb.ce, cim, network_service)
def tapchanger_to_cim(pb: PBTapChanger, cim: TapChanger, network_service: NetworkService):
cim.high_step = pb.highStep
cim.step = pb.step
cim.neutral_step = pb.neutralStep
cim.normal_step = pb.normalStep
cim.low_step = pb.lowStep
cim.neutral_u = pb.neutralU
cim.control_enabled = pb.controlEnabled
powersystemresource_to_cim(pb.psr, cim, network_service)
def transformerend_to_cim(pb: PBTransformerEnd, cim: TransformerEnd, network_service: NetworkService):
network_service.resolve_or_defer_reference(resolver.te_terminal(cim), pb.terminalMRID)
network_service.resolve_or_defer_reference(resolver.te_base_voltage(cim), pb.baseVoltageMRID)
network_service.resolve_or_defer_reference(resolver.ratio_tap_changer(cim), pb.ratioTapChangerMRID)
cim.end_number = pb.endNumber
cim.grounded = pb.grounded
cim.r_ground = pb.rGround
cim.x_ground = pb.xGround
identifiedobject_to_cim(pb.io, cim, network_service)
PBAcLineSegment.to_cim = aclinesegment_to_cim
PBBreaker.to_cim = breaker_to_cim
PBConductor.to_cim = conductor_to_cim
PBConnector.to_cim = connector_to_cim
PBDisconnector.to_cim = disconnector_to_cim
PBEnergyConnection.to_cim = energyconnection_to_cim
PBEnergyConsumer.to_cim = energyconsumer_to_cim
PBEnergyConsumerPhase.to_cim = energyconsumerphase_to_cim
PBEnergySource.to_cim = energysource_to_cim
PBEnergySourcePhase.to_cim = energysourcephase_to_cim
PBFuse.to_cim = fuse_to_cim
PBJumper.to_cim = jumper_to_cim
PBJunction.to_cim = junction_to_cim
PBLine.to_cim = line_to_cim
PBLinearShuntCompensator.to_cim = linearshuntcompensator_to_cim
PBPerLengthSequenceImpedance.to_cim = perlengthsequenceimpedance_to_cim
PBPerLengthLineParameter.to_cim = perlengthlineparameter_to_cim
PBPerLengthImpedance = perlengthimpedance_to_cim
PBPowerTransformer.to_cim = powertransformer_to_cim
PBPowerTransformerEnd.to_cim = powertransformerend_to_cim
PBProtectedSwitch.to_cim = protectedswitch_to_cim
PBRatioTapChanger.to_cim = ratiotapchanger_to_cim
PBRecloser.to_cim = recloser_to_cim
PBRegulatingCondEq.to_cim = regulatingcondeq_to_cim
PBShuntCompensator.to_cim = shuntcompensator_to_cim
PBSwitch.to_cim = switch_to_cim
PBTapChanger.to_cim = tapchanger_to_cim
PBTransformerEnd.to_cim = transformerend_to_cim
def circuit_to_cim(pb: PBCircuit, network_service: NetworkService) -> Optional[Circuit]:
cim = Circuit(mrid=pb.mrid())
for mrid in pb.endTerminalMRIDs:
network_service.resolve_or_defer_reference(resolver.end_terminal(cim), mrid)
for mrid in pb.endSubstationMRIDs:
network_service.resolve_or_defer_reference(resolver.end_substation(cim), mrid)
line_to_cim(pb.l, cim, network_service)
return cim if network_service.add(cim) else None
def loop_to_cim(pb: PBLoop, network_service: NetworkService) -> Optional[Loop]:
cim = Loop(mrid=pb.mrid())
for mrid in pb.circuitMRIDs:
network_service.resolve_or_defer_reference(resolver.loop_circuits(cim), mrid)
for mrid in pb.substationMRIDs:
network_service.resolve_or_defer_reference(resolver.loop_substations(cim), mrid)
for mrid in pb.normalEnergizingSubstationMRIDs:
network_service.resolve_or_defer_reference(resolver.loop_energizing_substations(cim), mrid)
identifiedobject_to_cim(pb.io, cim, network_service)
return cim if network_service.add(cim) else None
PBCircuit.to_cim = circuit_to_cim
PBLoop.to_cim = loop_to_cim
# Extensions
def _add_from_pb(network_service: NetworkService, pb) -> Optional[IdentifiedObject]:
"""Must only be called by objects for which .to_cim() takes themselves and the network service."""
try:
return pb.to_cim(network_service)
except AttributeError:
raise TypeError(f"Type {pb.__class__.__name__} is not supported by NetworkService")
NetworkService.add_from_pb = _add_from_pb
# Convenience class for adding to the service
class NetworkProtoToCim(BaseProtoToCim):
service: NetworkService
def add_from_pb(self, pb) -> Optional[IdentifiedObject]:
"""Must only be called by objects for which .to_cim() takes themselves and the network."""
return pb.to_cim(self.service) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/network/translator/network_proto2cim.py | network_proto2cim.py |
from zepben.protobuf.cim.iec61968.assetinfo.CableInfo_pb2 import CableInfo
from zepben.protobuf.cim.iec61968.assetinfo.WireInfo_pb2 import WireInfo
from zepben.protobuf.cim.iec61968.assetinfo.OverheadWireInfo_pb2 import OverheadWireInfo
from zepben.protobuf.cim.iec61968.assets.AssetContainer_pb2 import AssetContainer
from zepben.protobuf.cim.iec61968.assets.AssetInfo_pb2 import AssetInfo
from zepben.protobuf.cim.iec61968.assets.AssetOrganisationRole_pb2 import AssetOrganisationRole
from zepben.protobuf.cim.iec61968.assets.AssetOwner_pb2 import AssetOwner
from zepben.protobuf.cim.iec61968.assets.Asset_pb2 import Asset
from zepben.protobuf.cim.iec61968.assets.Pole_pb2 import Pole
from zepben.protobuf.cim.iec61968.assets.Streetlight_pb2 import Streetlight
from zepben.protobuf.cim.iec61968.assets.Structure_pb2 import Structure
from zepben.protobuf.cim.iec61968.common.Location_pb2 import Location
from zepben.protobuf.cim.iec61968.metering.EndDevice_pb2 import EndDevice
from zepben.protobuf.cim.iec61968.metering.Meter_pb2 import Meter
from zepben.protobuf.cim.iec61968.metering.UsagePoint_pb2 import UsagePoint
from zepben.protobuf.cim.iec61968.operations.OperationalRestriction_pb2 import OperationalRestriction
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.AuxiliaryEquipment_pb2 import AuxiliaryEquipment
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.FaultIndicator_pb2 import FaultIndicator
from zepben.protobuf.cim.iec61970.base.core.AcDcTerminal_pb2 import AcDcTerminal
from zepben.protobuf.cim.iec61970.base.core.BaseVoltage_pb2 import BaseVoltage
from zepben.protobuf.cim.iec61970.base.core.ConductingEquipment_pb2 import ConductingEquipment
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNodeContainer_pb2 import ConnectivityNodeContainer
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNode_pb2 import ConnectivityNode
from zepben.protobuf.cim.iec61970.base.core.EquipmentContainer_pb2 import EquipmentContainer
from zepben.protobuf.cim.iec61970.base.core.Equipment_pb2 import Equipment
from zepben.protobuf.cim.iec61970.base.core.Feeder_pb2 import Feeder
from zepben.protobuf.cim.iec61970.base.core.GeographicalRegion_pb2 import GeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.PowerSystemResource_pb2 import PowerSystemResource
from zepben.protobuf.cim.iec61970.base.core.Site_pb2 import Site
from zepben.protobuf.cim.iec61970.base.core.SubGeographicalRegion_pb2 import SubGeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.Substation_pb2 import Substation
from zepben.protobuf.cim.iec61970.base.core.Terminal_pb2 import Terminal
from zepben.protobuf.cim.iec61970.base.meas.Accumulator_pb2 import Accumulator
from zepben.protobuf.cim.iec61970.base.meas.Analog_pb2 import Analog
from zepben.protobuf.cim.iec61970.base.meas.Control_pb2 import Control
from zepben.protobuf.cim.iec61970.base.meas.Discrete_pb2 import Discrete
from zepben.protobuf.cim.iec61970.base.meas.IoPoint_pb2 import IoPoint
from zepben.protobuf.cim.iec61970.base.meas.Measurement_pb2 import Measurement
from zepben.protobuf.cim.iec61970.base.scada.RemoteControl_pb2 import RemoteControl
from zepben.protobuf.cim.iec61970.base.scada.RemotePoint_pb2 import RemotePoint
from zepben.protobuf.cim.iec61970.base.scada.RemoteSource_pb2 import RemoteSource
from zepben.protobuf.cim.iec61970.base.wires.AcLineSegment_pb2 import AcLineSegment
from zepben.protobuf.cim.iec61970.base.wires.Breaker_pb2 import Breaker
from zepben.protobuf.cim.iec61970.base.wires.Conductor_pb2 import Conductor
from zepben.protobuf.cim.iec61970.base.wires.Connector_pb2 import Connector
from zepben.protobuf.cim.iec61970.base.wires.Disconnector_pb2 import Disconnector
from zepben.protobuf.cim.iec61970.base.wires.EnergyConnection_pb2 import EnergyConnection
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumerPhase_pb2 import EnergyConsumerPhase
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumer_pb2 import EnergyConsumer
from zepben.protobuf.cim.iec61970.base.wires.EnergySourcePhase_pb2 import EnergySourcePhase
from zepben.protobuf.cim.iec61970.base.wires.EnergySource_pb2 import EnergySource
from zepben.protobuf.cim.iec61970.base.wires.Fuse_pb2 import Fuse
from zepben.protobuf.cim.iec61970.base.wires.Jumper_pb2 import Jumper
from zepben.protobuf.cim.iec61970.base.wires.Junction_pb2 import Junction
from zepben.protobuf.cim.iec61970.base.wires.Line_pb2 import Line
from zepben.protobuf.cim.iec61970.base.wires.LinearShuntCompensator_pb2 import LinearShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.PerLengthImpedance_pb2 import PerLengthImpedance
from zepben.protobuf.cim.iec61970.base.wires.PerLengthLineParameter_pb2 import PerLengthLineParameter
from zepben.protobuf.cim.iec61970.base.wires.PerLengthSequenceImpedance_pb2 import PerLengthSequenceImpedance
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformerEnd_pb2 import PowerTransformerEnd
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformer_pb2 import PowerTransformer
from zepben.protobuf.cim.iec61970.base.wires.ProtectedSwitch_pb2 import ProtectedSwitch
from zepben.protobuf.cim.iec61970.base.wires.RatioTapChanger_pb2 import RatioTapChanger
from zepben.protobuf.cim.iec61970.base.wires.Recloser_pb2 import Recloser
from zepben.protobuf.cim.iec61970.base.wires.RegulatingCondEq_pb2 import RegulatingCondEq
from zepben.protobuf.cim.iec61970.base.wires.ShuntCompensator_pb2 import ShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.Switch_pb2 import Switch
from zepben.protobuf.cim.iec61970.base.wires.TapChanger_pb2 import TapChanger
from zepben.protobuf.cim.iec61970.base.wires.TransformerEnd_pb2 import TransformerEnd
from zepben.protobuf.cim.iec61970.infiec61970.feeder.Loop_pb2 import Loop
from zepben.protobuf.cim.iec61970.infiec61970.feeder.Circuit_pb2 import Circuit
from zepben.cimbend.network.translator.network_proto2cim import *
__all__ = []
CableInfo.mrid = lambda self: self.wi.mrid()
OverheadWireInfo.mrid = lambda self: self.wi.mrid()
WireInfo.mrid = lambda self: self.ai.mrid()
Asset.mrid = lambda self: self.io.mRID
AssetContainer.mrid = lambda self: self.at.mrid()
AssetInfo.mrid = lambda self: self.io.mRID
AssetOrganisationRole.mrid = lambda self: getattr(self, "or").mrid()
AssetOwner.mrid = lambda self: self.aor.mrid()
Pole.mrid = lambda self: self.st.mrid()
Streetlight.mrid = lambda self: self.at.mrid()
Structure.mrid = lambda self: self.ac.mrid()
Location.mrid = lambda self: self.io.mRID
EndDevice.mrid = lambda self: self.ac.mrid()
Meter.mrid = lambda self: self.ed.mrid()
UsagePoint.mrid = lambda self: self.io.mRID
OperationalRestriction.mrid = lambda self: self.doc.mrid()
AuxiliaryEquipment.mrid = lambda self: self.eq.mrid()
FaultIndicator.mrid = lambda self: self.ae.mrid()
AcDcTerminal.mrid = lambda self: self.io.mRID
BaseVoltage.mrid = lambda self: self.io.mRID
ConductingEquipment.mrid = lambda self: self.eq.mrid()
ConnectivityNode.mrid = lambda self: self.io.mRID
ConnectivityNodeContainer.mrid = lambda self: self.psr.mrid()
Equipment.mrid = lambda self: self.psr.mrid()
EquipmentContainer.mrid = lambda self: self.cnc.mrid()
Feeder.mrid = lambda self: self.ec.mrid()
GeographicalRegion.mrid = lambda self: self.io.mRID
PowerSystemResource.mrid = lambda self: self.io.mRID
Site.mrid = lambda self: self.ec.mrid()
SubGeographicalRegion.mrid = lambda self: self.io.mRID
Substation.mrid = lambda self: self.ec.mrid()
Terminal.mrid = lambda self: self.ad.mrid()
AcLineSegment.mrid = lambda self: self.cd.mrid()
Breaker.mrid = lambda self: self.sw.mrid()
Conductor.mrid = lambda self: self.ce.mrid()
Connector.mrid = lambda self: self.ce.mrid()
Disconnector.mrid = lambda self: self.sw.mrid()
EnergyConnection.mrid = lambda self: self.ce.mrid()
EnergyConsumer.mrid = lambda self: self.ec.mrid()
EnergyConsumerPhase.mrid = lambda self: self.psr.mrid()
EnergySource.mrid = lambda self: self.ec.mrid()
EnergySourcePhase.mrid = lambda self: self.psr.mrid()
Fuse.mrid = lambda self: self.sw.mrid()
Jumper.mrid = lambda self: self.sw.mrid()
Junction.mrid = lambda self: self.cn.mrid()
Line.mrid = lambda self: self.ec.mrid()
LinearShuntCompensator.mrid = lambda self: self.sc.mrid()
PerLengthImpedance.mrid = lambda self: self.lp.mrid()
PerLengthLineParameter.mrid = lambda self: self.io.mRID
PerLengthSequenceImpedance.mrid = lambda self: self.pli.mrid()
PowerTransformer.mrid = lambda self: self.ce.mrid()
PowerTransformerEnd.mrid = lambda self: self.te.mrid()
ProtectedSwitch.mrid = lambda self: self.sw.mrid()
RatioTapChanger.mrid = lambda self: self.tc.mrid()
Recloser.mrid = lambda self: self.sw.mrid()
RegulatingCondEq.mrid = lambda self: self.ec.mrid()
ShuntCompensator.mrid = lambda self: self.rce.mrid()
Switch.mrid = lambda self: self.ce.mrid()
TapChanger.mrid = lambda self: self.psr.mrid()
TransformerEnd.mrid = lambda self: self.io.mRID
Loop.mrid = lambda self: self.io.mRID
Circuit.mrid = lambda self: self.l.mrid()
Accumulator.mrid = lambda self: self.measurement.mrid()
Analog.mrid = lambda self: self.measurement.mrid()
Discrete.mrid = lambda self: self.measurement.mrid()
Control.mrid = lambda self: self.ip.mrid()
IoPoint.mrid = lambda self: self.io.mRID
Measurement.mrid = lambda self: self.io.mRID
RemoteControl.mrid = lambda self: self.rp.mrid()
RemotePoint.mrid = lambda self: self.io.mRID
RemoteSource.mrid = lambda self: self.rp.mrid()
PowerSystemResource.name_and_mrid = lambda self: self.io.name_and_mrid()
ConductingEquipment.name_and_mrid = lambda self: self.eq.name_and_mrid()
Equipment.name_and_mrid = lambda self: self.psr.name_and_mrid()
ConnectivityNodeContainer.name_and_mrid = lambda self: self.psr.name_and_mrid()
EquipmentContainer.name_and_mrid = lambda self: self.cnc.name_and_mrid()
Feeder.name_and_mrid = lambda self: self.ec.name_and_mrid()
EnergyConsumerPhase.name_and_mrid = lambda self: self.psr.name_and_mrid()
EnergySourcePhase.name_and_mrid = lambda self: self.psr.name_and_mrid()
PowerTransformerEnd.name_and_mrid = lambda self: self.te.name_and_mrid()
AcDcTerminal.name_and_mrid = lambda self: self.io.name_and_mrid()
TransformerEnd.name_and_mrid = lambda self: self.io.name_and_mrid()
Terminal.name_and_mrid = lambda self: self.ad.name_and_mrid()
# location_mrid
PowerSystemResource.location_mrid = lambda self: getattr(self, "locationMRID", None)
Equipment.location_mrid = lambda self: self.psr.location_mrid()
AuxiliaryEquipment.location_mrid = lambda self: self.eq.location_mrid()
FaultIndicator.location_mrid = lambda self: self.ae.location_mrid()
ConductingEquipment.location_mrid = lambda self: self.eq.location_mrid()
Conductor.location_mrid = lambda self: self.ce.location_mrid()
Connector.location_mrid = lambda self: self.ce.location_mrid()
EnergyConnection.location_mrid = lambda self: self.ce.location_mrid()
PowerTransformer.location_mrid = lambda self: self.ce.location_mrid()
Switch.location_mrid = lambda self: self.ce.location_mrid()
AcLineSegment.location_mrid = lambda self: self.cd.location_mrid()
Junction.location_mrid = lambda self: self.cn.location_mrid()
EnergyConsumer.location_mrid = lambda self: self.ec.location_mrid()
EnergySource.location_mrid = lambda self: self.ec.location_mrid()
RegulatingCondEq.location_mrid = lambda self: self.ec.location_mrid()
Disconnector.location_mrid = lambda self: self.sw.location_mrid()
Fuse.location_mrid = lambda self: self.sw.location_mrid()
Jumper.location_mrid = lambda self: self.sw.location_mrid()
ProtectedSwitch.location_mrid = lambda self: self.sw.location_mrid()
ShuntCompensator.location_mrid = lambda self: self.rce.location_mrid()
Breaker.location_mrid = lambda self: self.sw.location_mrid()
Recloser.location_mrid = lambda self: self.sw.location_mrid()
LinearShuntCompensator.location_mrid = lambda self: self.sc.location_mrid()
# service_location_mrid
EndDevice.service_location_mrid = lambda self: getattr(self, "serviceLocationMRID", None)
Meter.service_location_mrid = lambda self: self.ed.service_location_mrid()
# usage_point_location_mrid
UsagePoint.usage_point_location_mrid = lambda self: getattr(self, "usagePointLocationMRID", None)
# terminal_mrid
AuxiliaryEquipment.terminal_mrid = lambda self: getattr(self, "terminalMRID", None)
FaultIndicator.terminal_mrid = lambda self: self.ae.terminal_mrid()
# terminal_mrids
ConductingEquipment.terminal_mrids = lambda self: getattr(self, "terminalMRIDs", [])
Conductor.terminal_mrids = lambda self: self.ce.terminal_mrids()
Connector.terminal_mrids = lambda self: self.ce.terminal_mrids()
EnergyConnection.terminal_mrids = lambda self: self.ce.terminal_mrids()
PowerTransformer.terminal_mrids = lambda self: self.ce.terminal_mrids()
Switch.terminal_mrids = lambda self: self.ce.terminal_mrids()
AcLineSegment.terminal_mrids = lambda self: self.cd.terminal_mrids()
Junction.terminal_mrids = lambda self: self.cn.terminal_mrids()
EnergyConsumer.terminal_mrids = lambda self: self.ec.terminal_mrids()
EnergySource.terminal_mrids = lambda self: self.ec.terminal_mrids()
RegulatingCondEq.terminal_mrids = lambda self: self.ec.terminal_mrids()
Disconnector.terminal_mrids = lambda self: self.sw.terminal_mrids()
Fuse.terminal_mrids = lambda self: self.sw.terminal_mrids()
Jumper.terminal_mrids = lambda self: self.sw.terminal_mrids()
ProtectedSwitch.terminal_mrids = lambda self: self.sw.terminal_mrids()
ShuntCompensator.terminal_mrids = lambda self: self.rce.terminal_mrids()
Breaker.terminal_mrids = lambda self: self.sw.terminal_mrids()
Recloser.terminal_mrids = lambda self: self.sw.terminal_mrids()
LinearShuntCompensator.terminal_mrids = lambda self: self.sc.terminal_mrids()
# base_voltage_mrid
ConductingEquipment.base_voltage_mrid = lambda self: getattr(self, "baseVoltageMRID", None)
Conductor.base_voltage_mrid = lambda self: self.ce.base_voltage_mrid()
Connector.base_voltage_mrid = lambda self: self.ce.base_voltage_mrid()
EnergyConnection.base_voltage_mrid = lambda self: self.ce.base_voltage_mrid()
PowerTransformer.base_voltage_mrid = lambda self: self.ce.base_voltage_mrid()
Switch.base_voltage_mrid = lambda self: self.ce.base_voltage_mrid()
AcLineSegment.base_voltage_mrid = lambda self: self.cd.base_voltage_mrid()
Junction.base_voltage_mrid = lambda self: self.cn.base_voltage_mrid()
EnergyConsumer.base_voltage_mrid = lambda self: self.ec.base_voltage_mrid()
EnergySource.base_voltage_mrid = lambda self: self.ec.base_voltage_mrid()
RegulatingCondEq.base_voltage_mrid = lambda self: self.ec.base_voltage_mrid()
Disconnector.base_voltage_mrid = lambda self: self.sw.base_voltage_mrid()
Fuse.base_voltage_mrid = lambda self: self.sw.base_voltage_mrid()
Jumper.base_voltage_mrid = lambda self: self.sw.base_voltage_mrid()
ProtectedSwitch.base_voltage_mrid = lambda self: self.sw.base_voltage_mrid()
ShuntCompensator.base_voltage_mrid = lambda self: self.rce.base_voltage_mrid()
Breaker.base_voltage_mrid = lambda self: self.sw.base_voltage_mrid()
Recloser.base_voltage_mrid = lambda self: self.sw.base_voltage_mrid()
LinearShuntCompensator.base_voltage_mrid = lambda self: self.sc.base_voltage_mrid()
# normal_energizing_substation_mrid
Feeder.normal_energizing_substation_mrid = lambda self: getattr(self, "normalEnergizingSubstationMRID", None)
# per_length_sequence_impedance_mrid
AcLineSegment.per_length_sequence_impedance_mrid = lambda self: getattr(self, "perLengthSequenceImpedanceMRID", None)
# asset_info_mrid
Conductor.asset_info_mrid = lambda self: getattr(self, "assetInfoMRID", None)
AcLineSegment.asset_info_mrid = lambda self: self.cd.asset_info_mrid()
# ratio_tap_changer_mrid
TransformerEnd.ratio_tap_changer_mrid = lambda self: getattr(self, "ratioTapChangerMRID", None)
PowerTransformerEnd.ratio_tap_changer_mrid = lambda self: self.te.ratio_tap_changer_mrid() | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/network/translator/__init__.py | __init__.py |
from dataclassy import dataclass
from typing import Dict, List
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_layout import DiagramObject
from zepben.cimbend.common.base_service import BaseService
__all__ = ["DiagramService"]
class DiagramService(BaseService):
name: str = "diagram"
_diagram_objects_by_diagram_mrid: Dict[str, Dict[str, DiagramObject]] = dict()
_diagram_objects_by_identified_object_mrid: Dict[str, Dict[str, DiagramObject]] = dict()
_diagram_object_indexes: List[Dict[str, Dict[str, DiagramObject]]] = list()
def __init__(self):
self._diagram_object_indexes.append(self._diagram_objects_by_identified_object_mrid)
self._diagram_object_indexes.append(self._diagram_objects_by_diagram_mrid)
def get_diagram_objects(self, mrid: str) -> List[DiagramObject]:
"""
Get `DiagramObject`'s from the service associated with the given mRID.
`DiagramObject`'s are indexed by its `DiagramObject.mrid`, its `DiagramObject.diagram.mrid`,
and its `DiagramObject.identifiedObjectMRID`'s (if present).
If you request a `DiagramObject` by its mRID you will receive a List with a single entry, otherwise
the list will contain as many `DiagramObject`'s as have been recorded against the provided mRID.
`mrid` The mRID to look up in the service.
Returns A list of `DiagramObject`'s associated with `mrid`.
"""
obj = self.get(mrid, DiagramObject)
if obj is not None:
return [obj]
for index in self._diagram_object_indexes:
if mrid in index:
return list(index[mrid].values())
return []
def add_diagram_object(self, diagram_object: DiagramObject):
"""
Associate a `DiagramObject` with this service.
The `DiagramObject` will be indexed by its `Diagram` and its `IdentifiedObject` (if present).
`diagram_object` The `DiagramObject` to add.
Returns True if the `DiagramObject` was successfully associated with the service.
"""
return self.add(diagram_object) and self._add_index(diagram_object)
def remove(self, diagram_object: DiagramObject) -> bool:
"""
Disassociate a `DiagramObject` with the service. This will remove all indexing of the `DiagramObject` and it
will no longer be able to be found via the service.
`diagram_object` The `DiagramObject` to disassociate with this service.
Returns True if the `DiagramObject` was removed successfully.
"""
return super(DiagramService, self).remove(diagram_object) and self._remove_index(diagram_object)
def _add_index(self, diagram_object: DiagramObject) -> bool:
"""
Index a `DiagramObject` against its associated [Diagram] and [IdentifiedObject].
`diagram_object` The `DiagramObject` to remove from the indexes.
Returns True if the index was updated.
"""
self._diagram_objects_by_diagram_mrid.setdefault(diagram_object.diagram.mrid, dict())[diagram_object.mrid] = diagram_object
iomrid = diagram_object.identified_object_mrid
if iomrid is not None:
self._diagram_objects_by_identified_object_mrid.setdefault(iomrid, dict())[diagram_object.mrid] = diagram_object
return True
def _remove_index(self, diagram_object: DiagramObject) -> bool:
"""
Remove the indexes of a `DiagramObject`.
`diagram_object` The `DiagramObject` to remove from the indexes.
Returns True if the index was updated.
"""
diagram_map = self._diagram_objects_by_diagram_mrid[diagram_object.diagram.mrid]
if diagram_map is not None:
del diagram_map[diagram_object.mrid]
if not diagram_map:
del self._diagram_objects_by_diagram_mrid[diagram_object.diagram.mrid]
iomrid = diagram_object.identified_object_mrid
if iomrid is not None:
io_map = self._diagram_objects_by_identified_object_mrid[iomrid]
if io_map is not None:
del io_map[diagram_object.mrid]
if not io_map:
del self._diagram_objects_by_identified_object_mrid[iomrid]
return True | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/diagram/diagrams.py | diagrams.py |
from zepben.protobuf.cim.iec61970.base.diagramlayout.Diagram_pb2 import Diagram as PBDiagram
from zepben.protobuf.cim.iec61970.base.diagramlayout.OrientationKind_pb2 import OrientationKind as PBOrientationKind
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramStyle_pb2 import DiagramStyle as PBDiagramStyle
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObject_pb2 import DiagramObject as PBDiagramObject
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObjectPoint_pb2 import DiagramObjectPoint as PBDiagramObjectPoint
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObjectStyle_pb2 import DiagramObjectStyle as PBDiagramObjectStyle
from zepben.cimbend.common.translator.util import mrid_or_empty
from zepben.cimbend.cim.iec61970.base.diagramlayout import Diagram, DiagramObject, DiagramObjectPoint
from zepben.cimbend.common.translator.base_cim2proto import identifiedobject_to_pb
__all__ = ["diagram_to_pb", "diagramobject_to_pb", "diagramobjectpoint_to_pb"]
# IEC61970 DIAGRAMLAYOUT #
def diagram_to_pb(cim: Diagram) -> PBDiagram:
return PBDiagram(io=identifiedobject_to_pb(cim),
diagramStyle=PBDiagramStyle.Value(cim.diagram_style.short_name),
orientationKind=PBOrientationKind.Value(cim.orientation_kind.short_name),
diagramObjectMRIDs=[str(io.mrid) for io in cim.diagram_objects])
def diagramobject_to_pb(cim: DiagramObject) -> PBDiagramObject:
return PBDiagramObject(io=identifiedobject_to_pb(cim),
diagramMRID=mrid_or_empty(cim.diagram),
identifiedObjectMRID=cim.identified_object_mrid,
diagramObjectStyle=PBDiagramObjectStyle.Value(cim.style.short_name),
rotation=cim.rotation,
diagramObjectPoints=[diagramobjectpoint_to_pb(io) for io in cim.points])
def diagramobjectpoint_to_pb(cim: DiagramObjectPoint) -> PBDiagramObjectPoint:
return PBDiagramObjectPoint(xPosition=cim.x_position, yPosition=cim.y_position)
Diagram.to_pb = diagram_to_pb
DiagramObject.to_pb = diagramobject_to_pb
DiagramObjectPoint.to_pb = diagramobjectpoint_to_pb | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/diagram/translator/diagram_cim2proto.py | diagram_cim2proto.py |
import zepben.cimbend.common.resolver as resolver
from zepben.cimbend.common.translator.base_proto2cim import *
from zepben.cimbend.diagram.diagrams import DiagramService
from zepben.protobuf.cim.iec61970.base.diagramlayout.Diagram_pb2 import Diagram as PBDiagram
from zepben.protobuf.cim.iec61970.base.diagramlayout.OrientationKind_pb2 import OrientationKind as PBOrientationKind
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramStyle_pb2 import DiagramStyle as PBDiagramStyle
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObject_pb2 import DiagramObject as PBDiagramObject
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObjectPoint_pb2 import DiagramObjectPoint as PBDiagramObjectPoint
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObjectStyle_pb2 import DiagramObjectStyle as PBDiagramObjectStyle
from zepben.cimbend.cim.iec61970.base.diagramlayout import Diagram, DiagramObject, DiagramObjectPoint
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_object_style import DiagramObjectStyle
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_style import DiagramStyle
from zepben.cimbend.cim.iec61970.base.diagramlayout.orientation_kind import OrientationKind
__all__ = ["diagramobjectpoint_to_cim", "diagram_to_cim", "diagramobject_to_cim"]
def diagramobjectpoint_to_cim(pb: PBDiagramObjectPoint) -> DiagramObjectPoint:
return DiagramObjectPoint(pb.xPosition, pb.yPosition)
# IEC61970 DIAGRAM LAYOUT #
def diagram_to_cim(pb: PBDiagram, service: DiagramService):
cim = Diagram(mrid=pb.mrid(),
orientation_kind=OrientationKind[PBOrientationKind.Name(pb.orientationKind)],
diagram_style=DiagramStyle[PBDiagramStyle.Name(pb.diagramStyle)])
for mrid in pb.diagramObjectMRIDs:
service.resolve_or_defer_reference(resolver.diagram_objects(cim), mrid)
identifiedobject_to_cim(pb.io, cim, service)
service.add(cim)
def diagramobject_to_cim(pb: PBDiagramObject, service: DiagramService):
cim = DiagramObject(mrid=pb.mrid(), identified_object_mrid=pb.identifiedObjectMRID,
style=DiagramObjectStyle[PBDiagramObjectStyle.Name(pb.diagramObjectStyle)])
service.resolve_or_defer_reference(resolver.diagram(cim), pb.diagramMRID)
for point in pb.diagramObjectPoints:
cim.add_point(diagramobjectpoint_to_cim(point))
identifiedobject_to_cim(pb.io, cim, service)
service.add_diagram_object(cim)
PBDiagram.to_cim = diagram_to_cim
PBDiagramObject.to_cim = diagramobject_to_cim
PBDiagramObjectPoint.to_cim = diagramobjectpoint_to_cim | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/diagram/translator/diagram_proto2cim.py | diagram_proto2cim.py |
from __future__ import annotations
from abc import abstractmethod
from dataclassy import dataclass
from zepben.cimbend.traversals.queue import FifoQueue, LifoQueue, PriorityQueue, Queue
from zepben.cimbend.exceptions import TracingException
from zepben.cimbend.traversals.tracker import Tracker
from typing import List, Callable, Awaitable, TypeVar, Generic, Set, Iterable
from enum import Enum
__all__ = ["SearchType", "create_queue", "BaseTraversal", "Traversal"]
T = TypeVar('T')
class SearchType(Enum):
BREADTH = 1
DEPTH = 2
PRIORITY = 3
def create_queue(search_type):
if search_type == SearchType.DEPTH:
return LifoQueue()
elif search_type == SearchType.BREADTH:
return FifoQueue()
elif search_type == SearchType.PRIORITY:
return PriorityQueue()
@dataclass(slots=True)
class BaseTraversal(Generic[T]):
"""
A basic traversal implementation that can be used to traverse any type of item.
This class is asyncio compatible. Stop condition and step action callbacks are called with await.
A stop condition is a callback function that must return a boolean indicating whether the Tracer should stop
processing the current branch. Tracing will only stop when either:
- All branches have been exhausted, or
- A stop condition has returned true on every possible branch.
Stop conditions will be called prior to applying any callbacks, but the stop will only occur after all actions
have been applied.
Step actions are functions to be called on each item visited in the trace. These are called after the stop conditions are evaluated, and each action is
passed the current `zepben.cimbend.network.tracing.connectivity.ConnectivityResult` as well as the `stopping` state (True if the trace is stopping after
the current `ConnectivityResult, False otherwise). Thus, the signature of each step action must be:
:func: action(cr: `zepben.cimbend.tracing.ConnectivityResult`, is_stopping: bool) -> None
"""
start_item: T = None
"""The starting item for this `BaseTraversal`"""
stop_conditions: List[Callable[[T], Awaitable[bool]]] = []
"""A list of callback functions, to be called in order with the current item."""
step_actions: List[Callable[[T, bool], Awaitable[None]]] = []
"""A list of callback functions, to be called on each item."""
_has_run: bool = False
"""Whether this traversal has run """
_running: bool = False
"""Whether this traversal is currently running"""
async def matches_stop_condition(self, item: T):
"""
Checks all the stop conditions for the passed in item and returns true if any match.
This calls all registered stop conditions even if one has already returned true to make sure everything is
notified about this item.
Each stop condition will be awaited and thus must be an async function.
`item` The item to pass to the stop conditions.
Returns True if any of the stop conditions return True.
"""
stop = False
for cond in self.stop_conditions:
stop = stop or await cond(item)
return stop
def add_stop_condition(self, cond: Callable[[T], Awaitable[bool]]):
"""
Add a callback to check whether the current item in the traversal is a stop point.
If any of the registered stop conditions return true, the traversal will not call the callback to queue more items.
Note that a match on a stop condition doesn't necessarily stop the traversal, it just stops traversal of the current branch.
`cond` A function that if returns true will cause the traversal to stop traversing the branch.
Returns this traversal instance.
"""
self.stop_conditions.append(cond)
def add_step_action(self, action: Callable[[T, bool], Awaitable[None]]) -> BaseTraversal[T]:
"""
Add a callback which is called for every item in the traversal (including the starting item).
`action` Action to be called on each item in the traversal, passing if the trace will stop on this step.
Returns this traversal instance.
"""
self.step_actions.append(action)
return self
def copy_stop_conditions(self, other: BaseTraversal[T]):
"""Copy the stop conditions from `other` to this `BaseTraversal`."""
self.stop_conditions.extend(other.stop_conditions)
def copy_step_actions(self, other: BaseTraversal[T]):
"""Copy the step actions from `other` to this `BaseTraversal`."""
self.step_actions.extend(other.step_actions)
def clear_stop_conditions(self):
"""Clear all stop conditions."""
self.stop_conditions.clear()
def clear_step_actions(self):
"""Clear all step actions"""
self.step_actions.clear()
async def apply_step_actions(self, item: T, is_stopping: bool):
"""
Calls all the step actions with the passed in item.
Each action will be awaited.
`item` The item to pass to the step actions.
`is_stopping` Indicates if the trace will stop on this step.
"""
for action in self.step_actions:
await action(item, is_stopping)
def _reset_run_flag(self):
if self._running:
raise TracingException("Can't reset when Traversal is currently executing.")
self._has_run = False
@abstractmethod
def reset(self):
"""
Reset this traversal. Should take care to reset all fields and queues so that the traversal can be reused.
"""
raise NotImplementedError()
async def trace(self, start_item: T = None, can_stop_on_start_item: bool = True):
"""
Perform a trace across the network from `start_item`, applying actions to each piece of equipment encountered
until all branches of the network are exhausted, or a stop condition succeeds and we cannot continue any further.
When a stop condition is reached, we will stop tracing that branch of the network and continue with other branches.
`start_item` The starting point. Must implement :func:`zepben.cimbend.ConductingEquipment::get_connectivity`
which allows tracing over the terminals in a network.
`can_stop_on_start_item` If it's possible for stop conditions to apply to the start_item.
"""
if self._running:
raise TracingException("Traversal is already running.")
if self._has_run:
raise TracingException("Traversal must be reset before reuse.")
self._running = True
self._has_run = True
self.start_item = start_item if start_item is not None else self.start_item
await self._run_trace(can_stop_on_start_item)
self._running = False
@abstractmethod
async def _run_trace(self, can_stop_on_start_item: bool = True):
"""
Extend and implement your tracing algorithm here.
`start_item` The starting object to commence tracing. Must implement :func:`zepben.cimbend.ConductingEquipment.get_connectivity`
`can_stop_on_start_item` Whether to
"""
raise NotImplementedError()
class Traversal(BaseTraversal):
"""
A basic traversal implementation that can be used to traverse any type of item.
The traversal gets the next items to be traversed to by calling a user provided callback (next_), with the current
item of the traversal. This function should return a list of ConnectivityResult's, that will get added to the
process_queue for processing.
Different `SearchType`'s types can be used to provide different trace types via the `process_queue`.
The default `Depth` will utilise a `LifoQueue` to provide a depth-first search of the network, while a `Breadth`
will use a FIFO `Queue` breadth-first search. More complex searches can be achieved with `Priority`, which
will use a PriorityQueue under the hood.
The traversal also requires a `zepben.cimbend.traversals.tracker.Tracker` to be supplied. This gives flexibility
to track items in unique ways, more than just "has this item been visited" e.g. visiting more than once,
visiting under different conditions etc.
"""
queue_next: Callable[[T, Set[T]], Iterable[T]]
"""A function that will return a list of `T` to add to the queue. The function must take the item to queue and optionally a set of already visited items."""
process_queue: Queue
"""Dictates the type of search to be performed on the network graph. Breadth-first, Depth-first, and Priority based searches are possible."""
tracker: Tracker = Tracker()
"""A `zepben.cimbend.traversals.tracker.Tracker` for tracking which items have been seen. If not provided a `Tracker` will be created for this trace."""
async def _run_trace(self, can_stop_on_start_item: bool = True):
"""
Run's the trace. Stop conditions and step_actions are called with await, so you can utilise asyncio when
performing a trace if your step actions or conditions are IO intensive. Stop conditions and
step actions will always be called for each item in the order provided.
`can_stop_on_start_item` Whether the trace can stop on the start_item. Actions will still be applied to
the start_item.
"""
if self.start_item is None:
try:
self.start_item = self.process_queue.get()
except IndexError:
raise TracingException("Starting item wasn't specified and the process queue is empty. Cannot start the trace.")
self.tracker.visit(self.start_item)
# If we can't stop on the start item we don't run any stop conditions. if this causes a problem for you,
# you should run the stop conditions for the start item prior to running the traversal.
stopping = can_stop_on_start_item and await self.matches_stop_condition(self.start_item)
await self.apply_step_actions(self.start_item, stopping)
if not stopping:
for x in self.queue_next(self.start_item, self.tracker.visited):
self.process_queue.put(x)
while not self.process_queue.empty():
current = self.process_queue.get()
if self.tracker.visit(current):
stopping = await self.matches_stop_condition(current)
await self.apply_step_actions(current, stopping)
if not stopping:
for x in self.queue_next(current, self.tracker.visited):
self.process_queue.put(x)
def reset(self):
self._reset_run_flag()
self.process_queue.queue.clear()
self.tracker.clear()
def _depth_trace(start_item, stop_on_start_item=True, stop_fn=None, equip_fn=None, term_fn=None):
equips_to_trace = []
traced = set()
for t in start_item.terminals:
traced.add(t.mrid)
if stop_on_start_item:
yield start_item
equips_to_trace.append(start_item)
while equips_to_trace:
try:
equip = equips_to_trace.pop()
except IndexError: # No more equipment
break
# Explore all connectivity nodes for this equipments terminals,
# and set upstream on each terminal.
for terminal in equip.terminals:
conn_node = terminal.connectivity_node
for term in conn_node:
# keep this
if term.mrid in traced:
continue
if term != terminal:
if not term.conducting_equipment.connected():
continue
equips_to_trace.append(term.conducting_equipment)
yield term.conducting_equipment
# Don't trace over a terminal twice to stop us from reversing direction
traced.add(term.mrid) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/traversals/tracing.py | tracing.py |
from abc import abstractmethod
__all__ = ["BaseTracker", "Tracker"]
from typing import Set
from dataclassy import dataclass
@dataclass(slots=True)
class BaseTracker(object):
"""
An interface used by `zepben.cimbend.tracing.Traversal`'s to 'track' items that have been visited.
A `Traversal` will utilise `has_visited`, `visit`, and `clear`.
"""
@abstractmethod
def has_visited(self, item):
"""
Check if the tracker has already seen an item.
`item` The item to check if it has been visited.
Returns true if the item has been visited, otherwise false.
"""
raise NotImplementedError()
@abstractmethod
def visit(self, item):
"""
Visit an item. Item will not be visited if it has previously been visited.
`item` The item to visit.
Returns True if visit succeeds. False otherwise.
"""
raise NotImplementedError()
@abstractmethod
def clear(self):
"""
Clear the tracker, removing all visited items.
"""
raise NotImplementedError()
class Tracker(BaseTracker):
"""
An interface used by `zepben.cimbend.traversals.tracing.Traversal`'s to 'track' items that have been visited.
"""
visited: Set = set()
def has_visited(self, item):
"""
Check if the tracker has already seen an item.
`item` The item to check if it has been visited.
Returns true if the item has been visited, otherwise false.
"""
return item in self.visited
def visit(self, item):
"""
Visit an item. Item will not be visited if it has previously been visited.
`item` The item to visit.
Returns True if visit succeeds. False otherwise.
"""
if item in self.visited:
return False
else:
self.visited.add(item)
return True
def clear(self):
"""
Clear the tracker, removing all visited items.
"""
self.visited.clear()
def copy(self):
return Tracker(visited=self.visited.copy()) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/traversals/tracker.py | tracker.py |
import copy
from collections import deque
from abc import abstractmethod, ABC
from typing import TypeVar, Generic
from heapq import heappush, heappop
__all__ = ["Queue", "FifoQueue", "LifoQueue", "PriorityQueue", "depth_first", "breadth_first"]
T = TypeVar('T')
def depth_first():
return LifoQueue()
def breadth_first():
return FifoQueue()
class Queue(Generic[T], ABC):
def __init__(self, queue=None):
if queue is None:
self.queue = deque()
else:
self.queue = queue
@abstractmethod
def put(self, item):
raise NotImplementedError()
@abstractmethod
def get(self):
"""
Pop an item off the queue.
Raises `IndexError` if the queue is empty.
"""
raise NotImplementedError()
@abstractmethod
def empty(self):
"""
Check if queue is empty
Returns True if empty, False otherwise
"""
raise NotImplementedError()
@abstractmethod
def peek(self):
"""
Retrieve next item on queue, but don't remove from queue.
Returns Next item on the queue
"""
raise NotImplementedError()
@abstractmethod
def clear(self):
"""Clear the queue."""
raise NotImplementedError()
@abstractmethod
def copy(self):
"""Create a copy of this Queue"""
raise NotImplementedError()
class FifoQueue(Queue[T]):
def put(self, item):
self.queue.append(item)
def get(self):
"""
Pop an item off the queue.
Raises `IndexError` if the queue is empty.
"""
return self.queue.popleft()
def empty(self):
"""
Check if queue is empty
Returns True if empty, False otherwise
"""
return len(self.queue) == 0
def peek(self):
"""
Retrieve next item on queue, but don't remove from queue.
Returns Next item on the queue
"""
return self.queue[0]
def clear(self):
"""Clear the queue."""
self.queue.clear()
def copy(self):
return FifoQueue(self.queue.copy())
class LifoQueue(Queue[T]):
def put(self, item):
self.queue.append(item)
def get(self):
"""
Pop an item off the queue.
Raises `IndexError` if the queue is empty.
"""
return self.queue.pop()
def empty(self):
"""
Check if queue is empty
Returns True if empty, False otherwise
"""
return len(self.queue) == 0
def peek(self):
"""
Retrieve next item on queue, but don't remove from queue.
Returns Next item on the queue
"""
return self.queue[-1]
def clear(self):
"""Clear the queue."""
self.queue.clear()
def copy(self):
return LifoQueue(self.queue.copy())
class PriorityQueue(Queue[T]):
def __init__(self):
super().__init__([])
def __len__(self):
return len(self.queue)
def put(self, item):
"""
Place an item in the queue based on its priority.
`item` The item to place on the queue. Must implement `__lt__`
Returns True if put was successful, False otherwise.
"""
heappush(self.queue, item)
def get(self):
"""
Get the next item in the queue, removing it from the queue.
Returns The next item in the queue by priority.
Raises `IndexError` if the queue is empty
"""
return heappop(self.queue)
def peek(self):
"""
Retrieve the next item in the queue, but don't remove it from the queue.
Note that you shouldn't modify the returned item after using this function, as you could change its
priority and thus corrupt the queue. Always use `get` if you intend on modifying the result.
Returns The next item in the queue
"""
return self.queue[0]
def empty(self):
return len(self) == 0
def clear(self):
"""Clear the queue."""
self.queue.clear()
def copy(self):
return PriorityQueue(self.queue.copy()) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/traversals/queue.py | queue.py |
from zepben.cimbend.traversals.queue import Queue
from zepben.cimbend.traversals.tracing import BaseTraversal
from zepben.cimbend.traversals.tracker import Tracker
from typing import Callable, Set, TypeVar, Optional
import copy
__all__ = ["BranchRecursiveTraversal"]
T = TypeVar('T')
class BranchRecursiveTraversal(BaseTraversal[T]):
queue_next: Callable[[T, BaseTraversal[T], Set[T]], None]
"""A callable for each item encountered during the trace, that should queue the next items found on the given traversal's `process_queue`.
The first argument will be the current item, the second this traversal, and the third a set of already visited items that can be used as an optional
optimisation to skip queuing."""
branch_queue: Queue
"""Queue containing branches to be processed"""
process_queue: Queue
"""Queue containing the items to process for this branch"""
tracker: Tracker = Tracker()
"""Tracker for the items in this branch"""
parent: Optional[BaseTraversal] = None
"""The parent branch for this branch, None implies this branch has no parent"""
on_branch_start: Optional[Callable[[T], None]] = None
"""A function to call at the start of each branches processing"""
def __lt__(self, other):
"""
This Traversal is Less than `other` if the starting item is less than other's starting item.
This is used to dictate which branch is next to traverse in the branch_queue.
"""
if self.start_item is not None and other.start_item is not None:
return self.start_item < other.start_item
elif self.start_item is None and other.start_item is None:
return False
elif other.start_item is None:
return True
else:
return False
def has_visited(self, item: T):
"""
Check whether item has been visited before. An item is visited if this traversal or any parent has visited it.
`item` The item to check
Returns True if the item has been visited once.
"""
parent = self.parent
while parent is not None:
if parent.tracker.has_visited(item):
return True
parent = parent.parent
return self.tracker.has_visited(item)
def visit(self, item: T):
"""
Visit an item.
`item` Item to visit
Returns True if we visit the item. False if this traversal or any parent has previously visited this item.
"""
parent = self.parent
while parent is not None:
if parent.tracker.has_visited(item):
return False
parent = parent.parent
return self.tracker.visit(item)
async def traverse_branches(self):
"""
Start a new traversal for the next branch in the queue.
on_branch_start will be called on the start_item for the branch.
"""
while not self.branch_queue.empty():
t = self.branch_queue.get()
if t is not None:
if self.on_branch_start is not None:
self.on_branch_start(t.start_item)
await t.trace()
def reset(self):
"""Reset the run state, queues and tracker for this this traversal"""
self._reset_run_flag()
self.process_queue.queue.clear()
self.branch_queue.queue.clear()
self.tracker.clear()
def create_branch(self):
"""
Create a branch for this `Traversal`. Will take copies of queues, actions, conditions, and tracker, and
pass this `Traversal` as the parent. The new Traversal will be :meth:`reset` prior to being returned.
Returns A new `BranchRecursiveTraversal` the same as this, but with this Traversal as its parent
"""
branch = BranchRecursiveTraversal(queue_next=self.queue_next,
branch_queue=self.branch_queue.copy(),
tracker=self.tracker.copy(),
parent=self,
on_branch_start=self.on_branch_start,
process_queue=self.process_queue.copy(),
step_actions=list(self.step_actions),
stop_conditions=list(self.stop_conditions))
branch.reset()
return branch
async def _run_trace(self, can_stop_on_start_item: bool = True):
"""
Run's the trace. Stop conditions and step_actions are called with await, so you can utilise asyncio when performing a trace if your step actions or
conditions are IO intensive. Stop conditions and step actions will always be called for each item in the order provided.
`can_stop_on_start_item` Whether the trace can stop on the start_item. Actions will still be applied to the start_item.
"""
# Unroll first iteration of loop to handle can_stop_on_start_item = True
if self.start_item is None:
try:
self.start_item = self.process_queue.get()
except IndexError:
# Our start point may very well be a branch - if so we don't need to process this branch.
await self.traverse_branches()
return
self.tracker.visit(self.start_item)
# If we can't stop on the start item we don't run any stop conditions. if this causes a problem for you,
# work around it by running the stop conditions for the start item prior to running the trace.
stopping = can_stop_on_start_item and await self.matches_stop_condition(self.start_item)
await self.apply_step_actions(self.start_item, stopping)
if not stopping:
self.queue_next(self.start_item, self, self.tracker.visited)
while not self.process_queue.empty():
current = self.process_queue.get()
if self.visit(current):
stopping = await self.matches_stop_condition(current)
await self.apply_step_actions(current, stopping)
if not stopping:
self.queue_next(current, self, self.tracker.visited)
await self.traverse_branches() | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/traversals/branch_recursive_tracing.py | branch_recursive_tracing.py |
from __future__ import annotations
from typing import Optional, TypeVar, Generic, Callable, List, Union
from dataclassy import dataclass
T = TypeVar("T")
@dataclass(slots=True)
class GrpcResult(Generic[T]):
result: Optional[Union[T, Exception]]
was_error_handled: bool = False
@property
def was_successful(self):
return not self.was_failure
@property
def was_failure(self):
return isinstance(self.result, Exception)
def on_success(self, handler: Callable[[T], None]) -> GrpcResult[T]:
"""Calls `handler` with the `result` if this `was_successful`"""
if self.was_successful:
handler(self.result)
return self
def on_error(self, handler: Callable[[Exception, bool], GrpcResult[T]]) -> GrpcResult[T]:
"""Calls `handler` with the `thrown` exception and `self.was_error_handled` if `self.was_failure`."""
if self.was_failure and self.was_error_handled:
return handler(self.result, self.was_error_handled)
return self
def on_handled_error(self, handler: Callable[[Exception], None]) -> GrpcResult[T]:
"""Calls `handler` with the `thrown` exception if `self.was_failure` only if `self.was_error_handled`."""
if self.was_failure and self.was_error_handled:
handler(self.result)
return self
def on_unhandled_error(self, handler: Callable[[Exception], None]) -> GrpcResult[T]:
"""Calls `handler` with the `thrown` exception if `self.was_failure` only if not `self.was_error_handled`."""
if self.was_failure and not self.was_error_handled:
handler(self.result)
return self
def throw_on_error(self) -> GrpcResult[T]:
"""Throws `self.result` if `self.was_failure`"""
if self.was_failure:
raise self.result
return self
def throw_on_unhandled_error(self) -> GrpcResult[T]:
"""Throws `self.result` only if `self.was_failure` and not `self.was_error_handled`"""
if self.was_failure and not self.was_error_handled:
raise self.result
return self
@dataclass(init=False, slots=True)
class GrpcClient(object):
error_handlers: List[Callable[[Exception], bool]] = []
def try_handle_error(self, e: Exception) -> bool:
for handler in self.error_handlers:
if handler(e):
return True
return False
async def try_rpc(self, rpc: Callable[[], IdentifiedObject]) -> GrpcResult:
try:
return GrpcResult(await rpc())
except Exception as e:
return GrpcResult(e, self.try_handle_error(e)) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/grpc.py | grpc.py |
from __future__ import annotations
from typing import Optional, Iterable, AsyncGenerator
from zepben.cimbend.streaming.consumer import CimConsumerClient, MultiObjectResult, extract_identified_object
from zepben.cimbend.streaming.grpc import GrpcResult
from zepben.protobuf.cc.cc_pb2_grpc import CustomerConsumerStub
from zepben.protobuf.cc.cc_requests_pb2 import GetIdentifiedObjectsRequest
__all__ = ["CustomerConsumerClient"]
class CustomerConsumerClient(CimConsumerClient):
_stub: CustomerConsumerStub = None
def __init__(self, channel=None, stub: CustomerConsumerStub = None):
if channel is None and stub is None:
raise ValueError("Must provide either a channel or a stub")
if stub is not None:
self._stub = stub
else:
self._stub = CustomerConsumerStub(channel)
async def get_identified_object(self, service: CustomerService, mrid: str) -> GrpcResult[Optional[IdentifiedObject]]:
"""
Retrieve the object with the given `mrid` and store the result in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
Returns a `GrpcResult` with a result of one of the following:
- The object if found
- None if an object could not be found or it was found but not added to `service` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the object, in which case, `GrpcResult.was_successful` will return false.
"""
async def y():
async for io, _ in self._process_identified_objects(service, [mrid]):
return io
else:
return None
return await self.try_rpc(y)
async def get_identified_objects(self, service: CustomerService, mrids: Iterable[str]) -> GrpcResult[MultiObjectResult]:
"""
Retrieve the objects with the given `mrids` and store the results in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
WARNING: This operation is not atomic upon `service`, and thus if processing fails partway through `mrids`, any previously successful mRID will have been
added to the service, and thus you may have an incomplete `BaseService`. Also note that adding to the `service` may not occur for an object if another
object with the same mRID is already present in `service`. `MultiObjectResult.failed` can be used to check for mRIDs that were retrieved but not
added to `service`.
Returns a `GrpcResult` with a result of one of the following:
- A `MultiObjectResult` containing a map of the retrieved objects keyed by mRID. If an item is not found it will be excluded from the map.
If an item couldn't be added to `service` its mRID will be present in `MultiObjectResult.failed` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the objects, in which case, `GrpcResult.was_successful` will return false.
Note the warning above in this case.
"""
async def y():
results = dict()
failed = set()
async for io, mrid in self._process_identified_objects(service, mrids):
if io:
results[io.mrid] = io
else:
failed.add(mrid)
return MultiObjectResult(results, failed)
return await self.try_rpc(y)
async def _process_identified_objects(self, service: CustomerService, mrids: Iterable[str]) -> AsyncGenerator[IdentifiedObject, None]:
to_fetch = set()
existing = set()
for mrid in mrids:
try:
fetched = service.get(mrid)
existing.add((fetched, fetched.mrid))
except KeyError:
to_fetch.add(mrid)
responses = self._stub.getIdentifiedObjects(GetIdentifiedObjectsRequest(mrids=to_fetch))
for response in responses:
og = response.objectGroup
io, mrid = extract_identified_object(service, og.identifiedObject)
if io:
yield io, mrid
else:
yield None, mrid
for owned_obj in og.ownedIdentifiedObject:
extracted, mrid = extract_identified_object(service, owned_obj)
if extracted:
yield extracted, mrid
else:
yield None, mrid | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/customer_consumer.py | customer_consumer.py |
from abc import abstractmethod, ABC
from asyncio import get_event_loop
from typing import TypeVar, Union, List, Dict, Generic, Type
from dataclassy import dataclass
from grpc import Channel
from zepben.cimbend import NetworkService, BaseService, DiagramService, CustomerService
from zepben.cimbend.network.translator.network_cim2proto import CimTranslationException
from zepben.cimbend.streaming.exceptions import UnsupportedOperationException
from zepben.cimbend.streaming.grpc import GrpcClient, GrpcResult
from zepben.cimbend.streaming.network_rpc import network_rpc_map
from zepben.cimbend.streaming.streaming import NoSuchRPCException, ProtoAttributeError
from zepben.protobuf.cp.cp_pb2_grpc import CustomerProducerStub
from zepben.protobuf.cp.cp_requests_pb2 import CreateCustomerServiceRequest, CompleteCustomerServiceRequest
from zepben.protobuf.dp.dp_pb2_grpc import DiagramProducerStub
from zepben.protobuf.dp.dp_requests_pb2 import CompleteDiagramServiceRequest, CreateDiagramServiceRequest
from zepben.protobuf.np.np_pb2_grpc import NetworkProducerStub
from zepben.protobuf.np.np_requests_pb2 import CreateNetworkRequest, CompleteNetworkRequest
__all__ = ["CimProducerClient", "CustomerProducerClient", "NetworkProducerClient", "DiagramProducerClient", "ProducerClient", "SyncProducerClient",
"SyncCustomerProducerClient"]
T = TypeVar("T", bound=BaseService)
async def _send(stub, service, rpc_map):
if not service:
return
for obj in service.objects():
try:
pb = obj.to_pb()
except Exception as e:
raise CimTranslationException(f"Failed to translate {obj} to protobuf.") from e
try:
rpc = getattr(stub, rpc_map[type(pb)][0])
except AttributeError as e:
raise NoSuchRPCException(f"RPC {rpc_map[type(pb)][0]} could not be found in {stub.__class__.__name__}") from e
try:
attrname = f"{obj.__class__.__name__[:1].lower()}{obj.__class__.__name__[1:]}"
req = rpc_map[type(pb)][1]()
getattr(req, attrname).CopyFrom(pb)
except AttributeError as e:
raise ProtoAttributeError() from e
rpc(req)
class CimProducerClient(GrpcClient):
"""Base class that defines some helpful functions when producer clients are sending to the server."""
@abstractmethod
def send(self, service: T = None):
"""
Sends objects within the given `service` to the producer server.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered. If none of the registered error handlers
return true to indicate the error has been handled, the exception will be rethrown.
"""
raise NotImplementedError()
class NetworkProducerClient(CimProducerClient):
_stub: NetworkProducerStub = None
def __init__(self, channel=None, stub: NetworkProducerStub = None):
if channel is None and stub is None:
raise ValueError("Must provide either a channel or a stub")
if stub is not None:
self._stub = stub
else:
self._stub = NetworkProducerStub(channel)
async def send(self, service: NetworkService = None):
"""
Sends objects within the given `service` to the producer server.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered. If none of the registered error handlers
return true to indicate the error has been handled, the exception will be rethrown.
"""
await self.try_rpc(lambda: self._stub.CreateNetwork(CreateNetworkRequest()))
await _send(self._stub, service, network_rpc_map)
await self.try_rpc(lambda: self._stub.CompleteNetwork(CompleteNetworkRequest()))
class DiagramProducerClient(CimProducerClient):
_stub: DiagramProducerStub = None
def __init__(self, channel=None, stub: DiagramProducerStub = None):
if channel is None and stub is None:
raise ValueError("Must provide either a channel or a stub")
if stub is not None:
self._stub = stub
else:
self._stub = DiagramProducerStub(channel)
async def send(self, service: DiagramService = None):
"""
Sends objects within the given `service` to the producer server.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered. If none of the registered error handlers
return true to indicate the error has been handled, the exception will be rethrown.
"""
await self.try_rpc(lambda: self._stub.CreateDiagramService(CreateDiagramServiceRequest()))
await _send(self._stub, service, network_rpc_map)
await self.try_rpc(lambda: self._stub.CompleteDiagramService(CompleteDiagramServiceRequest()))
class CustomerProducerClient(CimProducerClient):
_stub: CustomerProducerStub = None
def __init__(self, channel=None, stub: CustomerProducerStub = None):
if channel is None and stub is None:
raise ValueError("Must provide either a channel or a stub")
if stub is not None:
self._stub = stub
else:
self._stub = CustomerProducerStub(channel)
async def send(self, service: CustomerService = None):
"""
Sends objects within the given `service` to the producer server.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered. If none of the registered error handlers
return true to indicate the error has been handled, the exception will be rethrown.
"""
await self.try_rpc(lambda: self._stub.CreateCustomerService(CreateCustomerServiceRequest()))
await _send(self._stub, service, network_rpc_map)
await self.try_rpc(lambda: self._stub.CompleteCustomerService(CompleteCustomerServiceRequest()))
class ProducerClient(CimProducerClient):
_channel: Channel = None
_clients: Dict[Type[BaseService], CimProducerClient] = None
def __init__(self, channel: Channel, clients: Dict[Type[BaseService], CimProducerClient] = None):
self._channel = channel
if clients is not None:
self._clients = clients.copy()
else:
self._clients = {
NetworkService: NetworkProducerClient(self._channel),
DiagramService: DiagramProducerClient(self._channel),
CustomerService: CustomerProducerClient(self._channel)
}
async def send(self, services: Union[List[BaseService], BaseService] = None):
"""
Send each service in `services` to the server.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered. If none of the registered error handlers
return true to indicate the error has been handled, the exception will be rethrown.
"""
if not services:
return GrpcResult(UnsupportedOperationException("No services were provided"))
sent = []
for service in services:
client = self._clients[type(service)]
await client.send(service)
sent.append(type(service))
for s in self._clients.keys():
if s not in sent:
client = self._clients[s]
await client.send()
class SyncProducerClient(ProducerClient):
def send(self, services: Union[List[BaseService], BaseService] = None):
return get_event_loop().run_until_complete(super().send(services))
class SyncCustomerProducerClient(CimProducerClient):
def send(self, service: CustomerService = None):
return get_event_loop().run_until_complete(super().send(service))
class SyncNetworkProducerClient(CimProducerClient):
def send(self, service: NetworkService = None):
return get_event_loop().run_until_complete(super().send(service))
class SyncDiagramProducerClient(CimProducerClient):
def send(self, service: DiagramService = None):
return get_event_loop().run_until_complete(super().send(service)) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/producer.py | producer.py |
from __future__ import annotations
from typing import AsyncGenerator
from zepben.cimbend import NetworkService, CustomerService, DiagramService, BaseService
from zepben.cimbend.streaming.exceptions import StreamingException
from zepben.protobuf.cp.cp_pb2_grpc import CustomerProducerStub
from zepben.protobuf.cp.cp_requests_pb2 import CreateCustomerServiceRequest, CompleteCustomerServiceRequest
from zepben.protobuf.dp.dp_pb2_grpc import DiagramProducerStub
from zepben.protobuf.dp.dp_requests_pb2 import CreateDiagramServiceRequest, CompleteDiagramServiceRequest
from zepben.protobuf.np.np_pb2_grpc import NetworkProducerStub
from zepben.protobuf.np.np_requests_pb2 import CreateNetworkRequest, CompleteNetworkRequest
from zepben.protobuf.nc.nc_pb2_grpc import NetworkConsumerStub
from zepben.protobuf.nc.nc_requests_pb2 import GetNetworkHierarchyRequest, GetIdentifiedObjectsRequest
from zepben.protobuf.nc.nc_data_pb2 import IdentifiedObjectGroup
from zepben.cimbend.streaming.network_rpc import diagram_rpc_map, network_rpc_map, customer_rpc_map
from zepben.cimbend.network.translator.network_cim2proto import *
from zepben.cimbend.network.translator.network_proto2cim import NetworkProtoToCim
import random
import math
__all__ = ["retrieve_network", "send_network", "send_customer", "send_diagram", "FeederStreamResult", "FeederSummary"]
# TODO: Fill in all fields
class FeederSummary:
acls_count: int
node_count: int
class FeederStreamResult:
success: bool
summary: FeederSummary
MAX_INT: int = int(math.pow(2, 32) - 1)
def get_random_message_id() -> int:
"""
Provide a random message_id for gRPC communication.
Returns A random message_id as an int.
"""
return random.randint(1, MAX_INT)
def get_identified_object(iog: IdentifiedObjectGroup):
"""
Unwrap an object group and return the enclosed identified object.
`object_group` The object group retrieved.
Returns A `zepben.protobuf.nc.nc_data_pb2.NetworkIdentifiedObject` containing the underlying identified object.
"""
og = getattr(iog, "objectGroup", {})
return getattr(og, "identifiedObject", {})
def get_expected_object(iog: IdentifiedObjectGroup, expected_type: str):
"""
Try to unwrap received identified object group to expected identified object.
`iog` The object group retrieved.
`expected_type` The expected type of the underlying identified object.
Returns One of the possible `zepben.protobuf.cim.*` objects in `zepben.protobuf.nc.nc_data_pb2.NetworkIdentifiedObject`
"""
identified_object = get_identified_object(iog)
object_type = identified_object.WhichOneof("identifiedObject")
if expected_type == "conductingEquipment":
return getattr(identified_object, object_type, None)
if object_type != expected_type:
print(f"Object is not of expected type. Expected '{expected_type}' - Actual '{object_type}'")
return getattr(identified_object, expected_type, None)
def safely_add(network: NetworkService, pb) -> None:
try:
network.add_from_pb(pb)
except Exception as e:
raise StreamingException(f"Failed to add [{pb}] to network. Are you using a cimbend version compatible with the server? Underlying error was: {e}")
async def get_identified_object_group(stub: NetworkConsumerStub, mrid: str) -> AsyncGenerator[IdentifiedObjectGroup, None]:
"""
Send a request to the connected server to retrieve an identified object group given its mRID.
`stub` A network consumer stub.
`mrid` The mRID of the desired object.
Returns The `zepben.protobuf.nc.nc_data_pb2.IdentifiedObjectGroup` object returned by the server.
"""
message_id = get_random_message_id()
request = GetIdentifiedObjectsRequest(messageId=message_id, mrids=[mrid])
response = stub.getIdentifiedObjects(request)
for obj in response:
yield obj
async def get_single_object(stub: NetworkConsumerStub, mrid: str) -> IdentifiedObjectGroup:
async for obj in get_identified_object_group(stub, mrid):
return obj
return None
async def add_identified_object(stub: NetworkConsumerStub, network: NetworkService, equipment_io) -> None:
"""
Add an equipment to the network.
`stub` A network consumer stub.
`network` The network to add the equipment to.
`equipment_io` The equipment identified object returned by the server.
"""
if equipment_io:
equipment_type = equipment_io.WhichOneof("identifiedObject")
if equipment_type:
# TODO: better check of equipment type (cf. oneof) ?
equipment = getattr(equipment_io, equipment_type, None)
safely_add(network, equipment)
async def retrieve_equipment(stub: NetworkConsumerStub, network: NetworkService, equipment_mrid: str) -> None:
"""
Retrieve equipment using its mRID and add it to the network.
`stub` A network consumer stub.
`network` The current network.
`equipment_mrid` The equipment mRID as a string.
"""
async for equipment_iog in get_identified_object_group(stub, equipment_mrid):
if equipment_iog:
await add_identified_object(stub, network, get_identified_object(equipment_iog))
for owned_io in equipment_iog.objectGroup.ownedIdentifiedObject:
await add_identified_object(stub, network, owned_io)
else:
print(f"Could not retrieve equipment {equipment_mrid}")
async def retrieve_feeder(stub: NetworkConsumerStub, network: NetworkService, feeder_mrid: str) -> None:
"""
Retrieve feeder using its mRID, add it to the network and retrieve its equipments.
`stub` A network consumer stub.
`network` The current network.
`equipment_mrid` The equipment mRID as a string.
"""
feeder_iog = await get_single_object(stub, feeder_mrid)
if feeder_iog:
feeder = get_expected_object(feeder_iog, "feeder")
if feeder:
safely_add(network, feeder)
for ce_mrid in getattr(feeder, "currentEquipmentMRIDs", []):
await retrieve_equipment(stub, network, ce_mrid)
else:
print(f"Could not retrieve feeder {feeder_mrid}")
async def retrieve_substation(stub: NetworkConsumerStub, network: NetworkService, substation_mrid: str) -> None:
"""
Retrieve substation using its mRID, add it to the network and retrieve its feeders.
`stub` A network consumer stub.
`network` The current network.
"""
sub_iog = await get_single_object(stub, substation_mrid)
if sub_iog:
sub = get_expected_object(sub_iog, "substation")
if sub:
safely_add(network, sub)
for nef_mrid in set(getattr(sub, "normalEnergizedFeederMRIDs", [])):
await retrieve_feeder(stub, network, nef_mrid)
# add loopMRIDs circuitMRIDs normalEnergizedLoopMRIDs ?
else:
print(f"Could not retrieve substation {substation_mrid}")
async def retrieve_sub_geographical_region(stub: NetworkConsumerStub, network: NetworkService, sub_geographical_region_mrid: str) -> None:
"""
Retrieve subgeographical region using its mRID, add it to the network and retrieve its substations.
`stub` A network consumer stub.
`network` The current network.
"""
sgr_iog = await get_single_object(stub, sub_geographical_region_mrid)
if sgr_iog:
sgr = get_expected_object(sgr_iog, "subGeographicalRegion")
if sgr:
safely_add(network, sgr)
for sub_mrid in getattr(sgr, "substationMRIDs", []):
await retrieve_substation(stub, network, sub_mrid)
else:
print(f"Could not retrieve sub geographical region {sub_geographical_region_mrid}")
async def retrieve_geographical_region(stub: NetworkConsumerStub, network: NetworkService, geographical_region_mrid: str):
"""
Retrieve geographical region using its mRID, add it to the network and retrieve its subgeographical regions.
`stub` A network consumer stub.
`network` The current network.
"""
gr_iog = await get_single_object(stub, geographical_region_mrid)
if gr_iog:
gr = get_expected_object(gr_iog, "geographicalRegion")
if gr:
safely_add(network, gr)
for sgr_mrid in getattr(gr, "subGeographicalRegionMRIDs", []):
await retrieve_sub_geographical_region(stub, network, sgr_mrid)
else:
print(f"Could not retrieve geographical region {geographical_region_mrid}")
async def retrieve_network(channel) -> NetworkService:
"""
Request network hierarchy and retrieve the network geographical regions.
`channel` A gRPC channel to the gRPC server.
Returns The retrieved `wepben.cimbend.NetworkService` object.
"""
service = NetworkService()
stub = NetworkConsumerStub(channel)
message_id = get_random_message_id()
request = GetNetworkHierarchyRequest(messageId=message_id)
response = stub.getNetworkHierarchy(request)
for gr in getattr(response, "geographicalRegions", []):
gr_mrid = getattr(gr, "mRID", None)
if gr_mrid:
await retrieve_geographical_region(stub, service, gr_mrid)
await empty_unresolved_refs(stub, service)
return service
async def empty_unresolved_refs(stub, service: NetworkService):
service = service
while service.has_unresolved_references():
for mrid in service.unresolved_mrids():
await retrieve_equipment(stub, service, mrid)
async def create_network(stub: NetworkProducerStub):
stub.CreateNetwork(CreateNetworkRequest())
async def complete_network(stub: NetworkProducerStub):
stub.CompleteNetwork(CompleteNetworkRequest())
class NoSuchRPCException(Exception):
pass
class ProtoAttributeError(Exception):
pass
async def _send(stub, service, rpc_map):
for obj in service.objects():
try:
pb = obj.to_pb()
except Exception as e:
raise CimTranslationException(f"Failed to translate {obj} to protobuf.") from e
try:
rpc = getattr(stub, rpc_map[type(pb)][0])
except AttributeError as e:
raise NoSuchRPCException(f"RPC {rpc_map[type(pb)][0]} could not be found in {stub.__class__.__name__}") from e
try:
attrname = f"{obj.__class__.__name__[:1].lower()}{obj.__class__.__name__[1:]}"
req = rpc_map[type(pb)][1]()
getattr(req, attrname).CopyFrom(pb)
except AttributeError as e:
raise ProtoAttributeError() from e
rpc(req)
async def send_network(stub: NetworkProducerStub, network_service: NetworkService):
"""
Send a network to the connected server.
`network_service` The Network containing all equipment in the feeder.
"""
return await _send(stub, network_service, network_rpc_map)
async def create_diagram(stub: DiagramProducerStub):
stub.CreateDiagramService(CreateDiagramServiceRequest())
async def complete_diagram(stub: DiagramProducerStub):
stub.CompleteDiagramService(CompleteDiagramServiceRequest())
async def send_diagram(stub: DiagramProducerStub, diagram_service: DiagramService):
return await _send(stub, diagram_service, diagram_rpc_map)
async def create_customer(stub: CustomerProducerStub):
stub.CreateCustomerService(CreateCustomerServiceRequest())
async def complete_customer(stub: CustomerProducerStub):
stub.CompleteCustomerService(CompleteCustomerServiceRequest())
async def send_customer(stub: CustomerProducerStub, customer_service: CustomerService):
return await _send(stub, customer_service, customer_rpc_map) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/streaming.py | streaming.py |
from __future__ import annotations
from asyncio import get_event_loop
from typing import Iterable, Dict, Optional, AsyncGenerator, Union
from zepben.cimbend import NetworkService, Feeder, Conductor
from zepben.cimbend.streaming.consumer import MultiObjectResult, extract_identified_object, CimConsumerClient
from zepben.cimbend.streaming.data import NetworkHierarchyIdentifiedObject, NetworkHierarchyGeographicalRegion, NetworkHierarchySubGeographicalRegion, \
NetworkHierarchySubstation, NetworkHierarchy, NetworkHierarchyFeeder
from zepben.cimbend.streaming.grpc import GrpcResult
from zepben.protobuf.nc.nc_pb2_grpc import NetworkConsumerStub
import zepben.cimbend.common.resolver as resolver
from zepben.protobuf.nc.nc_requests_pb2 import GetIdentifiedObjectsRequest, GetNetworkHierarchyRequest
__all__ = ["NetworkConsumerClient"]
def _lookup(mrids: Iterable[str], lookup: Dict[str, NetworkHierarchyIdentifiedObject]):
return {mrid: lookup[mrid] for mrid in mrids if mrid is not None}
def _finalise_links(geographical_regions: Dict[str, NetworkHierarchyGeographicalRegion],
sub_geographical_regions: Dict[str, NetworkHierarchySubGeographicalRegion],
substations: Dict[str, NetworkHierarchySubstation]):
for gr in geographical_regions.values():
for sgr in gr.sub_geographical_regions.values():
sgr.geographical_region = gr
for sgr in sub_geographical_regions.values():
for subs in sgr.substations.values():
subs.sub_geographical_region = sgr
for subs in substations.values():
for feeder in subs.feeders.values():
feeder.substation = subs
class NetworkConsumerClient(CimConsumerClient):
_stub: NetworkConsumerStub = None
def __init__(self, channel=None, stub: NetworkConsumerStub = None):
if channel is None and stub is None:
raise ValueError("Must provide either a channel or a stub")
if stub is not None:
self._stub = stub
else:
self._stub = NetworkConsumerStub(channel)
async def get_identified_object(self, service: NetworkService, mrid: str) -> GrpcResult[Optional[IdentifiedObject]]:
"""
Retrieve the object with the given `mrid` and store the result in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
Returns a `GrpcResult` with a result of one of the following:
- The object if found
- None if an object could not be found or it was found but not added to `service` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the object, in which case, `GrpcResult.was_successful` will return false.
"""
return await self._get_identified_objects(service, mrid)
async def get_identified_objects(self, service: NetworkService, mrids: Iterable[str]) -> GrpcResult[MultiObjectResult]:
"""
Retrieve the objects with the given `mrids` and store the results in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
WARNING: This operation is not atomic upon `service`, and thus if processing fails partway through `mrids`, any previously successful mRID will have been
added to the service, and thus you may have an incomplete `BaseService`. Also note that adding to the `service` may not occur for an object if another
object with the same mRID is already present in `service`. `MultiObjectResult.failed` can be used to check for mRIDs that were retrieved but not
added to `service`.
Returns a `GrpcResult` with a result of one of the following:
- A `MultiObjectResult` containing a map of the retrieved objects keyed by mRID. If an item is not found it will be excluded from the map.
If an item couldn't be added to `service` its mRID will be present in `MultiObjectResult.failed` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the objects, in which case, `GrpcResult.was_successful` will return false.
Note the warning above in this case.
"""
return await self._get_identified_objects(service, mrids)
async def get_network_hierarchy(self) -> GrpcResult[NetworkHierarchy]:
"""
Retrieve the network hierarchy
Returns a simplified version of the network hierarchy that can be used to make further in-depth requests.
"""
return await self._get_network_hierarchy()
async def get_feeder(self, service: NetworkService, mrid: str) -> GrpcResult[MultiObjectResult]:
"""
Retrieve the feeder network for the specified `mrid` and store the results in the `service`.
This is a convenience method that will fetch the feeder object, all of the equipment referenced by the feeder (normal state),
the terminals of all elements, the connectivity between terminals, the locations of all elements, the ends of all transformers
and the wire info for all conductors.
Returns a GrpcResult of a `MultiObjectResult`, containing a map keyed by mRID of all the objects retrieved as part of retrieving the `Feeder` and the
'Feeder' itself. If an item couldn't be added to `service`, its mRID will be present in `MultiObjectResult.failed`.
"""
return await self._get_feeder(service, mrid)
async def retrieve_network(self) -> GrpcResult[Union[NetworkService, Exception]]:
"""
Retrieve the entire network.
Returns a GrpcResult containing the complete `zepben.cimbend.network.network.NetworkService` from the server.
"""
return await self._retrieve_network()
async def _get_identified_object(self, service: NetworkService, mrid: str) -> GrpcResult[Optional[IdentifiedObject]]:
async def y():
async for io, _ in self._process_identified_objects(service, [mrid]):
return io
else:
return None
return await self.try_rpc(y)
async def _get_identified_objects(self, service: NetworkService, mrids: Iterable[str]) -> GrpcResult[MultiObjectResult]:
async def y():
results = dict()
failed = set()
async for io, mrid in self._process_identified_objects(service, mrids):
if io:
results[io.mrid] = io
else:
failed.add(mrid)
return MultiObjectResult(results, failed)
return await self.try_rpc(y)
async def _get_network_hierarchy(self) -> GrpcResult[NetworkHierarchy]:
return await self.try_rpc(self._handle_network_hierarchy)
async def _get_feeder(self, service: NetworkService, mrid: str) -> GrpcResult[MultiObjectResult]:
feeder_response = await self._get_identified_object(service, mrid)
if feeder_response.was_failure:
return feeder_response
feeder: Feeder = feeder_response.result
if not feeder:
return GrpcResult(result=None)
equipment_objects = await self._get_identified_objects(service, service.get_unresolved_reference_mrids(resolver.ec_equipment(feeder)))
if equipment_objects.was_failure:
return equipment_objects
resolvers = list()
resolvers.append(resolver.normal_energizing_substation(feeder))
for equip in feeder.equipment:
try:
for terminal in equip.terminals:
resolvers.append(resolver.connectivity_node(terminal))
if isinstance(equip, Conductor):
resolvers.append(resolver.per_length_sequence_impedance(equip))
resolvers.append(resolver.asset_info(equip))
except AttributeError:
pass # Not ConductingEquipment.
resolvers.append(resolver.psr_location(equip))
mrids = service.get_unresolved_reference_mrids(resolvers)
objects = await self._get_identified_objects(service, mrids)
if objects.was_failure:
return objects
objects.result.value.update(equipment_objects.result.value) # Combine with previous results
objects.result.value[feeder.mrid] = feeder # Add feeder to result
return GrpcResult(result=MultiObjectResult(objects.result.value, objects.result.failed.union(equipment_objects.result.failed)))
async def _retrieve_network(self) -> GrpcResult[Union[NetworkService, Exception]]:
service = NetworkService()
result = await self._get_network_hierarchy()
if result.was_failure:
return result
hierarchy: NetworkHierarchy = result.result
for mrid, gr in hierarchy.geographical_regions.items():
gr_result = await self._get_identified_object(service, mrid)
if gr_result.was_failure:
return gr_result
for mrid, sgr in hierarchy.sub_geographical_regions.items():
sgr_result = await self._get_identified_object(service, mrid)
if sgr_result.was_failure:
return sgr_result
for mrid, substation in hierarchy.substations.items():
substation_result = await self._get_identified_object(service, mrid)
if substation_result.was_failure:
return substation_result
for mrid, feeder in hierarchy.feeders.items():
feeder_result = await self._get_identified_object(service, mrid)
if feeder_result.was_failure:
return feeder_result
while service.has_unresolved_references():
for mrid in service.unresolved_mrids():
await self._get_identified_object(service, mrid)
return GrpcResult(service)
async def _process_identified_objects(self, service: NetworkService, mrids: Iterable[str]) -> AsyncGenerator[IdentifiedObject, None]:
to_fetch = set()
existing = set()
for mrid in mrids:
try:
fetched = service.get(mrid)
existing.add((fetched, fetched.mrid))
except KeyError:
to_fetch.add(mrid)
responses = self._stub.getIdentifiedObjects(GetIdentifiedObjectsRequest(mrids=to_fetch))
for response in responses:
og = response.objectGroup
io, mrid = extract_identified_object(service, og.identifiedObject)
if io:
yield io, mrid
else:
yield None, mrid
for owned_obj in og.ownedIdentifiedObject:
extracted, mrid = extract_identified_object(service, owned_obj)
if extracted:
yield extracted, mrid
else:
yield None, mrid
async def _handle_network_hierarchy(self):
response = self._stub.getNetworkHierarchy(GetNetworkHierarchyRequest())
feeders = {f.mRID: NetworkHierarchyFeeder(f.mRID, f.name) for f in response.feeders}
substations = {s.mRID: NetworkHierarchySubstation(s.mRID, s.name, _lookup(s.feederMrids, feeders)) for s in response.substations}
sub_geographical_regions = {s.mRID: NetworkHierarchySubGeographicalRegion(s.mRID, s.name, _lookup(s.substationMrids, substations)) for s in
response.subGeographicalRegions}
geographical_regions = {g.mRID: NetworkHierarchyGeographicalRegion(g.mRID, g.name, _lookup(g.subGeographicalRegionMrids, sub_geographical_regions)) for
g in response.geographicalRegions}
_finalise_links(geographical_regions, sub_geographical_regions, substations)
return NetworkHierarchy(geographical_regions, sub_geographical_regions, substations, feeders)
class SyncNetworkConsumerClient(NetworkConsumerClient):
def get_network_hierarchy(self):
"""
Retrieve the network hierarchy
Returns a simplified version of the network hierarchy that can be used to make further in-depth requests.
"""
return get_event_loop().run_until_complete(super().get_network_hierarchy())
def get_feeder(self, service: NetworkService, mrid: str) -> GrpcResult[MultiObjectResult]:
"""
Retrieve the feeder network for the specified `mrid` and store the results in the `service`.
This is a convenience method that will fetch the feeder object, all of the equipment referenced by the feeder (normal state),
the terminals of all elements, the connectivity between terminals, the locations of all elements, the ends of all transformers
and the wire info for all conductors.
Returns a GrpcResult of a `MultiObjectResult`, containing a map keyed by mRID of all the objects retrieved as part of retrieving the `Feeder` and the
'Feeder' itself. If an item couldn't be added to `service`, its mRID will be present in `MultiObjectResult.failed`.
"""
return get_event_loop().run_until_complete(super().get_feeder(service, mrid))
def get_identified_objects(self, service: NetworkService, mrids: Iterable[str]) -> GrpcResult[MultiObjectResult]:
"""
Retrieve the objects with the given `mrids` and store the results in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
WARNING: This operation is not atomic upon `service`, and thus if processing fails partway through `mrids`, any previously successful mRID will have been
added to the service, and thus you may have an incomplete `BaseService`. Also note that adding to the `service` may not occur for an object if another
object with the same mRID is already present in `service`. `MultiObjectResult.failed` can be used to check for mRIDs that were retrieved but not
added to `service`.
Returns a `GrpcResult` with a result of one of the following:
- A `MultiObjectResult` containing a map of the retrieved objects keyed by mRID. If an item is not found it will be excluded from the map.
If an item couldn't be added to `service` its mRID will be present in `MultiObjectResult.failed` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the objects, in which case, `GrpcResult.was_successful` will return false.
Note the warning above in this case.
"""
return get_event_loop().run_until_complete(super().get_identified_objects(service, mrids))
def get_identified_object(self, service: NetworkService, mrid: str) -> GrpcResult[Optional[IdentifiedObject]]:
"""
Retrieve the object with the given `mrid` and store the result in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
Returns a `GrpcResult` with a result of one of the following:
- The object if found
- None if an object could not be found or it was found but not added to `service` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the object, in which case, `GrpcResult.was_successful` will return false.
"""
return get_event_loop().run_until_complete(super().get_identified_objects(service, mrid))
def retrieve_network(self) -> GrpcResult[Union[NetworkService, Exception]]:
return get_event_loop().run_until_complete(super().retrieve_network()) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/network_consumer.py | network_consumer.py |
from __future__ import annotations
from typing import List, Union, Callable
from dataclassy import dataclass
from zepben.cimbend.common import BaseService
from zepben.cimbend.network import NetworkService
from zepben.cimbend.customer import CustomerService
from zepben.cimbend.diagram import DiagramService
from zepben.protobuf.np.np_pb2_grpc import NetworkProducerStub
from zepben.protobuf.cp.cp_pb2_grpc import CustomerProducerStub
from zepben.protobuf.dp.dp_pb2_grpc import DiagramProducerStub
from zepben.cimbend.streaming.streaming import retrieve_network, send_network, send_customer, send_diagram, \
create_network, complete_network, create_diagram, complete_diagram, create_customer, complete_customer, \
CimTranslationException
__all__ = ["WorkbenchConnection"]
NetworkProducerStub.send = send_network
NetworkProducerStub.create = create_network
NetworkProducerStub.complete = complete_network
DiagramProducerStub.send = send_diagram
DiagramProducerStub.create = create_diagram
DiagramProducerStub.complete = complete_diagram
CustomerProducerStub.send = send_customer
CustomerProducerStub.create = create_customer
CustomerProducerStub.complete = complete_customer
class WorkbenchConnection(object):
def __init__(self, channel):
self.channel = channel
self._stubs = {
NetworkService: NetworkProducerStub(channel),
DiagramService: DiagramProducerStub(channel),
CustomerService: CustomerProducerStub(channel)
}
# async def get_whole_network(self, mrid=""):
# """
# Retrieve an entire network from the connection.
# `mrid` ID of the network to retrieve (not supported yet) TODO
# Returns An `zepben.cimbend.network.Network` populated with the network.
# """
# ec = await retrieve_network(self.network_stub.getWholeNetwork, Identity(mRID=mrid))
# return ec
async def _send_service(self, service: BaseService):
stub = self._stubs[type(service)]
await stub.create()
await stub.send(service)
await stub.complete()
async def send(self, services: Union[List[BaseService], BaseService]):
sent = []
try:
for service in services:
await self._send_service(service)
sent.append(type(service))
except AttributeError:
await self._send_service(services)
sent.append(type(services))
for s in self._stubs.keys():
if s not in sent:
stub = self._stubs[s]
await stub.create()
await stub.complete()
# async def send_feeder(self, ns: NetworkService):
# """
# Send a feeder to the connected server. A feeder must start with a feeder circuit `zepben.cimbend.switch.Breaker`.
#
# `ns` The Network containing all equipment in the feeder.
# Returns A `zepben.cimbend.streaming.streaming.FeederStreamResult`
# Raises A derivative of `zepben.cimbend.exceptions.MissingReferenceException` if a incorrect reference
# between types is made.
# """
# # res = await send_network(self.network_stub, ns)
# return res
async def get_network_hierarchy():
response = self.stub.getNetworkHierarchy(request)
def __exit__(self, exc_type, exc_val, exc_tb):
self.channel.close() | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/api.py | api.py |
from __future__ import annotations
from abc import abstractmethod
from typing import Iterable, Dict, Optional, Set, Tuple
from dataclassy import dataclass
from zepben.cimbend.streaming.exceptions import UnsupportedOperationException
from zepben.protobuf.nc.nc_data_pb2 import NetworkIdentifiedObject
from zepben.cimbend.streaming.grpc import GrpcClient, GrpcResult
__all__ = ["CimConsumerClient", "MultiObjectResult", "extract_identified_object"]
@dataclass()
class MultiObjectResult(object):
value: Dict[str, IdentifiedObject]
failed: Set[str]
class CimConsumerClient(GrpcClient):
@abstractmethod
async def get_identified_object(self, service: BaseService, mrid: str) -> GrpcResult:
"""
Retrieve the object with the given `mrid` and store the result in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
Returns a `GrpcResult` with a result of one of the following:
- The object if found
- null if an object could not be found or it was found but not added to `service` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the object, in which case, `GrpcResult.was_successful` will return false.
"""
raise NotImplementedError()
@abstractmethod
async def get_identified_objects(self, service: BaseService, mrids: Iterable[str]) -> GrpcResult:
"""
Retrieve the objects with the given `mrids` and store the results in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
WARNING: This operation is not atomic upon `service`, and thus if processing fails partway through `mrids`, any previously successful mRID will have been
added to the service, and thus you may have an incomplete `BaseService`. Also note that adding to the `service` may not occur for an object if another
object with the same mRID is already present in `service`. `MultiObjectResult.failed` can be used to check for mRIDs that were retrieved but not
added to `service`.
Returns a `GrpcResult` with a result of one of the following:
- A `MultiObjectResult` containing a map of the retrieved objects keyed by mRID. If an item is not found it will be excluded from the map.
If an item couldn't be added to `service` its mRID will be present in `MultiObjectResult.failed` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the objects, in which case, `GrpcResult.was_successful` will return false.
Note the warning above in this case.
"""
raise NotImplementedError()
def extract_identified_object(service: NetworkService, nio: NetworkIdentifiedObject) -> Tuple[Optional[IdentifiedObject], str]:
"""
Add an equipment to the network.
`stub` A network consumer stub.
`network` The network to add the equipment to.
`equipment_io` The equipment identified object returned by the server.
Raises `UnsupportedOperationException` if `nio` was invalid/unset.
"""
io_type = nio.WhichOneof("identifiedObject")
if io_type:
pbio = getattr(nio, io_type)
return service.add_from_pb(pbio), pbio.mrid()
else:
raise UnsupportedOperationException(f"Received a NetworkIdentifiedObject where no field was set") | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/consumer.py | consumer.py |
import contextlib
import grpc
import requests
import json
from jose import jwt
from datetime import datetime
from zepben.cimbend.streaming.exceptions import AuthException
__all__ = ["connect", "connect_async"]
_AUTH_HEADER_KEY = 'authorization'
class AuthTokenPlugin(grpc.AuthMetadataPlugin):
def __init__(self, host, conf_address, client_id, client_secret):
self.host = host
self.conf_address = conf_address
self.client_id = client_id
self.client_secret = client_secret
self.token = ""
self.token_expiry = 0
self._refresh_token()
def __call__(self, context, callback):
if datetime.utcnow().timestamp() > self.token_expiry:
self._refresh_token()
callback(((_AUTH_HEADER_KEY, self.token),), None)
def _refresh_token(self):
parts = get_token(self.host, self.conf_address, self.client_id, self.client_secret)
self.token = f"{parts['token_type']} {parts['access_token']}"
self.token_expiry = jwt.get_unverified_claims(parts['access_token'])['exp']
def get_token(addr, conf_address, client_id, client_secret):
# Get the configuration TODO: this probably needs to be OAuth2 compliant or something
with requests.session() as session:
with session.get(conf_address) as resp:
result = json.loads(resp.text)
domain = result["dom"]
aud = result["aud"]
with session.post(domain, data={'client_id': client_id, 'client_secret': client_secret, 'audience': aud, 'grant_type': 'client_credentials'}) as resp:
token = json.loads(resp.text)
if 'error' in token:
raise AuthException(f"{token['error']}: {token['error_description']}")
return token
def _conn(host: str = "localhost", rpc_port: int = 50051, conf_address: str = "http://localhost/auth", client_id: str = None,
client_secret: str = None, pkey=None, cert=None, ca=None):
"""
`host` The host to connect to.
`rpc_port` The gRPC port for host.
`conf_address` The complete address for the auth configuration endpoint.
`client_id` Your client id for your OAuth Auth provider.
`client_secret` Corresponding client secret.
`pkey` Private key for client authentication
`cert` Corresponding signed certificate. CN must reflect your hosts FQDN, and must be signed by the servers
CA.
`ca` CA trust for the server.
`secure_conf` Whether the server hosting configuration is secured (https)
Returns A gRPC channel
"""
# TODO: make this more robust so it can handle SSL without client verification
if pkey and cert and client_id and client_secret:
call_credentials = grpc.metadata_call_credentials(AuthTokenPlugin(host, conf_address, client_id, client_secret))
# Channel credential will be valid for the entire channel
channel_credentials = grpc.ssl_channel_credentials(ca, pkey, cert)
# Combining channel credentials and call credentials together
composite_credentials = grpc.composite_channel_credentials(
channel_credentials,
call_credentials,
)
channel = grpc.secure_channel(f"{host}:{rpc_port}", composite_credentials)
else:
channel = grpc.insecure_channel(f"{host}:{rpc_port}")
return channel
@contextlib.contextmanager
def connect(host: str = "localhost",
rpc_port: int = 50051,
conf_address: str = "http://localhost/auth",
client_id: str = None,
client_secret: str = None,
pkey=None,
cert=None,
ca=None):
"""
Usage:
with connect(args) as channel:
`host` The host to connect to.
`rpc_port` The gRPC port for host.
`conf_address` The complete address for the auth configuration endpoint.
`client_id` Your client id for your OAuth Auth provider.
`client_secret` Corresponding client secret.
`pkey` Private key for client authentication
`cert` Corresponding signed certificate. CN must reflect your hosts FQDN, and must be signed by the servers
CA.
`ca` CA trust for the server.
Returns A gRPC channel
"""
yield _conn(host, rpc_port, conf_address, client_id, client_secret, pkey, cert, ca)
@contextlib.asynccontextmanager
async def connect_async(host: str = "localhost",
rpc_port: int = 50051,
conf_address: str = "http://localhost/auth",
client_id: str = None,
client_secret: str = None,
pkey=None,
cert=None,
ca=None):
"""
Usage:
async with connect_async(args) as channel:
`host` The host to connect to.
`rpc_port` The gRPC port for host.
`conf_address` The complete address for the auth configuration endpoint.
`client_id` Your client id for your OAuth Auth provider.
`client_secret` Corresponding client secret.
`pkey` Private key for client authentication
`cert` Corresponding signed certificate. CN must reflect your hosts FQDN, and must be signed by the servers
CA.
`ca` CA trust for the server.
Returns A gRPC channel
"""
yield _conn(host, rpc_port, conf_address, client_id, client_secret, pkey, cert, ca) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/connect.py | connect.py |
from __future__ import annotations
from typing import Optional, Iterable, AsyncGenerator
from zepben.cimbend.streaming.consumer import CimConsumerClient, MultiObjectResult, extract_identified_object
from zepben.cimbend.streaming.grpc import GrpcResult
from zepben.protobuf.dc.dc_pb2_grpc import DiagramConsumerStub
from zepben.protobuf.dc.dc_requests_pb2 import GetIdentifiedObjectsRequest
__all__ = ["DiagramConsumerClient"]
class DiagramConsumerClient(CimConsumerClient):
_stub: DiagramConsumerStub = None
def __init__(self, channel=None, stub: DiagramConsumerStub = None):
if channel is None and stub is None:
raise ValueError("Must provide either a channel or a stub")
if stub is not None:
self._stub = stub
else:
self._stub = DiagramConsumerStub(channel)
async def get_identified_object(self, service: DiagramService, mrid: str) -> GrpcResult[Optional[IdentifiedObject]]:
"""
Retrieve the object with the given `mrid` and store the result in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
Returns a `GrpcResult` with a result of one of the following:
- The object if found
- None if an object could not be found or it was found but not added to `service` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the object, in which case, `GrpcResult.was_successful` will return false.
"""
async def y():
async for io, _ in self._process_identified_objects(service, [mrid]):
return io
else:
return None
return await self.try_rpc(y)
async def get_identified_objects(self, service: DiagramService, mrids: Iterable[str]) -> GrpcResult[MultiObjectResult]:
"""
Retrieve the objects with the given `mrids` and store the results in the `service`.
Exceptions that occur during sending will be caught and passed to all error handlers that have been registered against this client.
WARNING: This operation is not atomic upon `service`, and thus if processing fails partway through `mrids`, any previously successful mRID will have been
added to the service, and thus you may have an incomplete `BaseService`. Also note that adding to the `service` may not occur for an object if another
object with the same mRID is already present in `service`. `MultiObjectResult.failed` can be used to check for mRIDs that were retrieved but not
added to `service`.
Returns a `GrpcResult` with a result of one of the following:
- A `MultiObjectResult` containing a map of the retrieved objects keyed by mRID. If an item is not found it will be excluded from the map.
If an item couldn't be added to `service` its mRID will be present in `MultiObjectResult.failed` (see `zepben.cimbend.common.base_service.BaseService.add`).
- An `Exception` if an error occurred while retrieving or processing the objects, in which case, `GrpcResult.was_successful` will return false.
Note the warning above in this case.
"""
async def y():
results = dict()
failed = set()
async for io, mrid in self._process_identified_objects(service, mrids):
if io:
results[io.mrid] = io
else:
failed.add(mrid)
return MultiObjectResult(results, failed)
return await self.try_rpc(y)
async def _process_identified_objects(self, service: DiagramService, mrids: Iterable[str]) -> AsyncGenerator[IdentifiedObject, None]:
to_fetch = set()
existing = set()
for mrid in mrids:
try:
fetched = service.get(mrid)
existing.add((fetched, fetched.mrid))
except KeyError:
to_fetch.add(mrid)
responses = self._stub.getIdentifiedObjects(GetIdentifiedObjectsRequest(mrids=to_fetch))
for response in responses:
og = response.objectGroup
io, mrid = extract_identified_object(service, og.identifiedObject)
if io:
yield io, mrid
else:
yield None, mrid
for owned_obj in og.ownedIdentifiedObject:
extracted, mrid = extract_identified_object(service, owned_obj)
if extracted:
yield extracted, mrid
else:
yield None, mrid | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/diagram_consumer.py | diagram_consumer.py |
from zepben.protobuf.cim.iec61968.assetinfo.CableInfo_pb2 import CableInfo
from zepben.protobuf.cim.iec61968.assetinfo.OverheadWireInfo_pb2 import OverheadWireInfo
from zepben.protobuf.cim.iec61968.assets.AssetOwner_pb2 import AssetOwner
from zepben.protobuf.cim.iec61968.assets.Pole_pb2 import Pole
from zepben.protobuf.cim.iec61968.assets.Streetlight_pb2 import Streetlight
from zepben.protobuf.cim.iec61968.common.Location_pb2 import Location
from zepben.protobuf.cim.iec61968.common.Organisation_pb2 import Organisation
from zepben.protobuf.cim.iec61968.metering.Meter_pb2 import Meter
from zepben.protobuf.cim.iec61968.metering.UsagePoint_pb2 import UsagePoint
from zepben.protobuf.cim.iec61968.operations.OperationalRestriction_pb2 import OperationalRestriction
from zepben.protobuf.cim.iec61970.base.auxiliaryequipment.FaultIndicator_pb2 import FaultIndicator
from zepben.protobuf.cim.iec61970.base.core.BaseVoltage_pb2 import BaseVoltage
from zepben.protobuf.cim.iec61970.base.core.ConnectivityNode_pb2 import ConnectivityNode
from zepben.protobuf.cim.iec61970.base.core.Feeder_pb2 import Feeder
from zepben.protobuf.cim.iec61970.base.core.GeographicalRegion_pb2 import GeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.Site_pb2 import Site
from zepben.protobuf.cim.iec61970.base.core.SubGeographicalRegion_pb2 import SubGeographicalRegion
from zepben.protobuf.cim.iec61970.base.core.Substation_pb2 import Substation
from zepben.protobuf.cim.iec61970.base.core.Terminal_pb2 import Terminal
from zepben.protobuf.cim.iec61970.base.wires.AcLineSegment_pb2 import AcLineSegment
from zepben.protobuf.cim.iec61970.base.wires.Breaker_pb2 import Breaker
from zepben.protobuf.cim.iec61970.base.wires.Disconnector_pb2 import Disconnector
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumer_pb2 import EnergyConsumer
from zepben.protobuf.cim.iec61970.base.wires.EnergyConsumerPhase_pb2 import EnergyConsumerPhase
from zepben.protobuf.cim.iec61970.base.wires.EnergySource_pb2 import EnergySource
from zepben.protobuf.cim.iec61970.base.wires.EnergySourcePhase_pb2 import EnergySourcePhase
from zepben.protobuf.cim.iec61970.base.wires.Fuse_pb2 import Fuse
from zepben.protobuf.cim.iec61970.base.wires.Jumper_pb2 import Jumper
from zepben.protobuf.cim.iec61970.base.wires.Junction_pb2 import Junction
from zepben.protobuf.cim.iec61970.base.wires.LinearShuntCompensator_pb2 import LinearShuntCompensator
from zepben.protobuf.cim.iec61970.base.wires.PerLengthSequenceImpedance_pb2 import PerLengthSequenceImpedance
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformer_pb2 import PowerTransformer
from zepben.protobuf.cim.iec61970.base.wires.PowerTransformerEnd_pb2 import PowerTransformerEnd
from zepben.protobuf.cim.iec61970.base.wires.RatioTapChanger_pb2 import RatioTapChanger
from zepben.protobuf.cim.iec61970.base.wires.Recloser_pb2 import Recloser
from zepben.protobuf.cim.iec61970.base.diagramlayout.Diagram_pb2 import Diagram
from zepben.protobuf.cim.iec61970.base.diagramlayout.DiagramObject_pb2 import DiagramObject
from zepben.protobuf.cim.iec61968.customers.Customer_pb2 import Customer
from zepben.protobuf.cim.iec61968.customers.CustomerAgreement_pb2 import CustomerAgreement
from zepben.protobuf.cim.iec61968.customers.PricingStructure_pb2 import PricingStructure
from zepben.protobuf.cim.iec61968.customers.Tariff_pb2 import Tariff
from zepben.protobuf.cim.iec61968.common.Organisation_pb2 import Organisation
from zepben.protobuf.dp.dp_requests_pb2 import *
from zepben.protobuf.cp.cp_requests_pb2 import *
from zepben.protobuf.cp.cp_requests_pb2 import CreateOrganisationRequest as CreateCustomerOrganisationRequest
from zepben.protobuf.np.np_requests_pb2 import *
network_rpc_map = {
CableInfo: ('CreateCableInfo', CreateCableInfoRequest),
OverheadWireInfo: ('CreateOverheadWireInfo', CreateOverheadWireInfoRequest),
AssetOwner: ('CreateAssetOwner', CreateAssetOwnerRequest),
Pole: ('CreatePole', CreatePoleRequest),
Streetlight: ('CreateStreetlight', CreateStreetlightRequest),
Location: ('CreateLocation', CreateLocationRequest),
Organisation: ('CreateOrganisation', CreateOrganisationRequest),
Meter: ('CreateMeter', CreateMeterRequest),
UsagePoint: ('CreateUsagePoint', CreateUsagePointRequest),
OperationalRestriction: ('CreateOperationalRestriction', CreateOperationalRestrictionRequest),
FaultIndicator: ('CreateFaultIndicator', CreateFaultIndicatorRequest),
BaseVoltage: ('CreateBaseVoltage', CreateBaseVoltageRequest),
ConnectivityNode: ('CreateConnectivityNode', CreateConnectivityNodeRequest),
Feeder: ('CreateFeeder', CreateFeederRequest),
GeographicalRegion: ('CreateGeographicalRegion', CreateGeographicalRegionRequest),
Site: ('CreateSite', CreateSiteRequest),
SubGeographicalRegion: ('CreateSubGeographicalRegion', CreateSubGeographicalRegionRequest),
Substation: ('CreateSubstation', CreateSubstationRequest),
Terminal: ('CreateTerminal', CreateTerminalRequest),
AcLineSegment: ('CreateAcLineSegment', CreateAcLineSegmentRequest),
EnergyConsumer: ('CreateEnergyConsumer', CreateEnergyConsumerRequest),
Disconnector: ('CreateDisconnector', CreateDisconnectorRequest),
Breaker: ('CreateBreaker', CreateBreakerRequest),
EnergyConsumerPhase: ('CreateEnergyConsumerPhase', CreateEnergyConsumerPhaseRequest),
EnergySource: ('CreateEnergySource', CreateEnergySourceRequest),
EnergySourcePhase: ('CreateEnergySourcePhase', CreateEnergySourcePhaseRequest),
Fuse: ('CreateFuse', CreateFuseRequest),
Jumper: ('CreateJumper', CreateJumperRequest),
Junction: ('CreateJunction', CreateJunctionRequest),
LinearShuntCompensator: ('CreateLinearShuntCompensator', CreateLinearShuntCompensatorRequest),
PerLengthSequenceImpedance: ('CreatePerLengthSequenceImpedance', CreatePerLengthSequenceImpedanceRequest),
PowerTransformer: ('CreatePowerTransformer', CreatePowerTransformerRequest),
PowerTransformerEnd: ('CreatePowerTransformerEnd', CreatePowerTransformerEndRequest),
RatioTapChanger: ('CreateRatioTapChanger', CreateRatioTapChangerRequest),
Recloser: ('CreateRecloser', CreateRecloserRequest),
}
diagram_rpc_map = {
Diagram: ('CreateDiagram', CreateDiagramRequest),
DiagramObject: ('CreateDiagramObject', CreateDiagramObjectRequest),
}
customer_rpc_map = {
Customer: ('CreateCustomer', CreateCustomerRequest),
CustomerAgreement: ('CreateCustomerAgreement', CreateCustomerAgreementRequest),
PricingStructure: ('CreatePricingStructure', CreatePricingStructureRequest),
Tariff: ('CreateTariff', CreateTariffRequest),
Organisation: ('CreateOrganisation', CreateCustomerOrganisationRequest),
} | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/streaming/network_rpc.py | network_rpc.py |
from zepben.protobuf.cim.iec61968.common.Agreement_pb2 import Agreement as PBAgreement
from zepben.protobuf.cim.iec61968.customers.CustomerAgreement_pb2 import CustomerAgreement as PBCustomerAgreement
from zepben.protobuf.cim.iec61968.customers.CustomerKind_pb2 import CustomerKind as PBCustomerKind
from zepben.protobuf.cim.iec61968.customers.Customer_pb2 import Customer as PBCustomer
from zepben.protobuf.cim.iec61968.customers.PricingStructure_pb2 import PricingStructure as PBPricingStructure
from zepben.protobuf.cim.iec61968.customers.Tariff_pb2 import Tariff as PBTariff
from zepben.cimbend.common.translator.util import mrid_or_empty
from zepben.cimbend.cim.iec61968.customers.customer import Customer
from zepben.cimbend.common.translator.base_cim2proto import document_to_pb, organisation_to_pb
from zepben.cimbend.cim.iec61968.common.document import Agreement
from zepben.cimbend.cim.iec61968.customers import CustomerAgreement, PricingStructure, Tariff
__all__ = ["agreement_to_pb", "customer_to_pb", "customeragreement_to_pb", "pricingstructure_to_pb", "tariff_to_pb"]
def agreement_to_pb(cim: Agreement) -> PBAgreement:
return PBAgreement(doc=document_to_pb(cim))
def customer_to_pb(cim: Customer) -> PBCustomer:
cust = PBCustomer(kind=PBCustomerKind.Value(cim.kind.short_name), agreementMRIDs=[str(io.mrid) for io in cim.agreements])
setattr(cust, 'or', organisation_to_pb(cim))
return cust
def customeragreement_to_pb(cim: CustomerAgreement) -> PBCustomerAgreement:
return PBCustomerAgreement(agr=agreement_to_pb(cim),
customerMRID=mrid_or_empty(cim.customer),
pricingStructureMRIDs=[str(io.mrid) for io in cim.pricing_structures])
def pricingstructure_to_pb(cim: PricingStructure) -> PBPricingStructure:
return PBPricingStructure(doc=document_to_pb(cim), tariffMRIDs=[str(io.mrid) for io in cim.tariffs])
def tariff_to_pb(cim: Tariff) -> PBTariff:
return PBTariff(doc=document_to_pb(cim))
Agreement.to_pb = agreement_to_pb
Customer.to_pb = customer_to_pb
CustomerAgreement.to_pb = customeragreement_to_pb
PricingStructure.to_pb = pricingstructure_to_pb
Tariff.to_pb = tariff_to_pb | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/customer/translator/customer_cim2proto.py | customer_cim2proto.py |
from __future__ import annotations
import zepben.cimbend.common.resolver as resolver
from zepben.cimbend.common import BaseService
from zepben.protobuf.cim.iec61968.common.Agreement_pb2 import Agreement as PBAgreement
from zepben.protobuf.cim.iec61968.customers.CustomerAgreement_pb2 import CustomerAgreement as PBCustomerAgreement
from zepben.protobuf.cim.iec61968.customers.CustomerKind_pb2 import CustomerKind as PBCustomerKind
from zepben.protobuf.cim.iec61968.customers.Customer_pb2 import Customer as PBCustomer
from zepben.protobuf.cim.iec61968.customers.PricingStructure_pb2 import PricingStructure as PBPricingStructure
from zepben.protobuf.cim.iec61968.customers.Tariff_pb2 import Tariff as PBTariff
from zepben.cimbend.cim.iec61968.customers.customer import Customer
from zepben.cimbend.customer.customers import CustomerService
from zepben.cimbend.common.translator.base_proto2cim import *
from zepben.cimbend.cim.iec61968.common.document import Agreement
from zepben.cimbend.cim.iec61968.customers import CustomerAgreement, CustomerKind, PricingStructure, Tariff
__all__ = ["agreement_to_cim", "tariff_to_cim", "customer_to_cim", "customeragreement_to_cim", "pricingstructure_to_cim"]
def agreement_to_cim(pb: PBAgreement, cim: Agreement, service: BaseService):
document_to_cim(pb.doc, cim, service)
def customer_to_cim(pb: PBCustomer, service: CustomerService):
cim = Customer(mrid=pb.mrid(), kind=CustomerKind[PBCustomerKind.Name(pb.kind)])
for mrid in pb.customerAgreementMRIDs:
service.resolve_or_defer_reference(resolver.agreements(cim), mrid)
organisationrole_to_cim(getattr(pb, 'or'), cim)
service.add(cim)
def customeragreement_to_cim(pb: PBCustomerAgreement, service: CustomerService):
cim = CustomerAgreement(mrid=pb.mrid())
service.resolve_or_defer_reference(resolver.customer(cim), pb.customerMRID)
for mrid in pb.pricingStructureMRIDs:
service.resolve_or_defer_reference(resolver.pricing_structures(cim), mrid)
agreement_to_cim(pb.agr, cim, service)
service.add(cim)
def pricingstructure_to_cim(pb: PBPricingStructure, service: CustomerService):
cim = PricingStructure(mrid=pb.mrid())
for mrid in pb.tariffMRIDs:
service.resolve_or_defer_reference(resolver.tariffs(cim), mrid)
document_to_cim(pb.doc, cim, service)
service.add(cim)
def tariff_to_cim(self, pb: PBTariff, service: CustomerService):
cim = Tariff(mrid=pb.mrid())
document_to_cim(pb.doc, cim, self.service)
service.add(cim)
PBAgreement.to_cim = agreement_to_cim
PBCustomer.to_cim = customer_to_cim
PBCustomerAgreement.to_cim = customeragreement_to_cim
PBPricingStructure.to_cim = pricingstructure_to_cim
PBTariff.to_cim = PBTariff | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/customer/translator/customer_proto2cim.py | customer_proto2cim.py |
from __future__ import annotations
import logging
from zepben.cimbend.traversals.tracing import Traversal
from zepben.cimbend.traversals.queue import LifoQueue
from zepben.cimbend.tracing.phase_status import normal_phases, current_phases
__all__ = ["normally_open", "currently_open", "ignore_open", "phase_log"]
phase_logger = logging.getLogger("phase_logger")
def normally_open(equip: ConductingEquipment, phase: Optional[SinglePhaseKind] = None):
"""
Test if a given phase on an equipment is normally open.
`equip` The equipment to test
`phase` The Phase to test. If None tests all phases.
Returns True if the equipment is open (de-energised), False otherwise
"""
try:
return not equip.normally_in_service or equip.is_normally_open(phase)
except AttributeError:
return not equip.normally_in_service
def currently_open(equip: ConductingEquipment, phase: Optional[SinglePhaseKind] = None):
"""
Test if a given phase on an equipment is open.
`equip` The equipment to test
`phase` The phase to test. If None tests all phases.
Returns True if the equipment is open (de-energised), False otherwise
"""
try:
return not equip.in_service or equip.is_open(phase)
except AttributeError:
return not equip.in_service
def ignore_open(ce: ConductingEquipment, phase: Optional[SinglePhaseKind] = None):
"""
Test that always returns that the phase is closed.
`equip` The equipment to test
`phase` The phase to test. If None tests all cores.
Returns False
"""
return False
async def phase_log(cond_equip):
msg = ""
try:
for e in cond_equip:
msg = await _phase_log_trace(e)
except:
msg = await _phase_log_trace(cond_equip)
phase_logger.debug(msg)
async def _phase_log_trace(cond_equip):
log_msg = []
async def log(e, exc):
equip_msgs = []
for term in e.terminals:
e_msg = f"{e.mrid}-T{term.sequence_number}:"
for n in term.phases.single_phases:
ps_n = normal_phases(term, n)
phase_n_msg = f"n: {ps_n.phase().short_name}:{ps_n.direction().short_name}"
ps_c = current_phases(term, n)
phase_c_msg = f"c: {ps_c.phase().short_name}:{ps_c.direction().short_name}"
e_msg = f"{e_msg} {{core {n}: {phase_n_msg} {phase_c_msg}}}"
equip_msgs.append(e_msg)
log_msg.append(equip_msgs)
trace = Traversal(queue_next=queue_next_equipment, start_item=cond_equip, process_queue=LifoQueue(), step_actions=[log])
await trace.trace()
return "\n".join([", ".join(x) for x in log_msg])
def queue_next_equipment(item, exclude=None):
connected_equips = item.get_connected_equipment(exclude=exclude)
tracing_logger.debug(f"Queuing connections [{', '.join(e.mrid for e in connected_equips)}] from {item.mrid}")
return connected_equips | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/tracing/util.py | util.py |
from __future__ import annotations
from dataclassy import dataclass
from operator import attrgetter
from zepben.cimbend.cim.iec61970.base.core.conducting_equipment import ConductingEquipment
from zepben.cimbend.cim.iec61970.base.core.terminal import Terminal
from zepben.cimbend.model.phases import NominalPhasePath
from typing import List, Optional, Tuple
__all__ = ["ConnectivityResult", "get_connectivity", "terminal_compare", "get_connected_equipment"]
def terminal_compare(terminal: Terminal, other: Terminal):
"""
This definition should only be used for sorting within a `zepben.cimbend.traversals.queue.PriorityQueue`
`terminal` The terminal to compare
`other` The terminal to compare against
Returns True if `terminal` has more phases than `other`, False otherwise.
"""
return terminal.phases.num_phases > other.phases.num_phases
Terminal.__lt__ = terminal_compare
def get_connectivity(terminal: Terminal, phases: Set[SinglePhaseKind] = None, exclude=None):
"""
Get the connectivity between this terminal and all other terminals in its `ConnectivityNode`.
`cores` Core paths to trace between the terminals. Defaults to all cores.
`exclude` `zepben.cimbend.iec61970.base.core.terminal.Terminal`'s to exclude from the result. Will be skipped if encountered.
Returns List of `ConnectivityResult`'s for this terminal.
"""
if exclude is None:
exclude = set()
if phases is None:
phases = terminal.phases.single_phases
trace_phases = phases.intersection(terminal.phases.single_phases)
cn = terminal.connectivity_node if terminal.connectivity_node else []
results = []
for term in cn:
if terminal is not term and term not in exclude: # Don't include ourselves, or those specifically excluded.
cr = _terminal_connectivity(terminal, term, trace_phases)
if cr.nominal_phase_paths:
results.append(cr)
return results
Terminal.connected_terminals = get_connectivity
def get_connected_equipment(cond_equip, exclude: Set = None):
"""
Get all `ConductingEquipment` connected to this piece of equipment. An `Equipment` is connected if it has
a `zepben.cimbend.iec61970.base.core.terminal.Terminal` associated with a `ConnectivityNode` that this `ConductingEquipment` is also associated with.
`exclude` Equipment to exclude from return.
Returns A list of `ConductingEquipment` that are connected to this.
"""
if exclude is None:
exclude = []
connected_equip = []
for terminal in cond_equip._terminals:
conn_node = terminal.connectivity_node
for term in conn_node:
if term.conducting_equipment in exclude:
continue
if term != terminal: # Don't include ourselves.
connected_equip.append(term.conducting_equipment)
return connected_equip
ConductingEquipment.connected_equipment = get_connected_equipment
def _terminal_connectivity(terminal: Terminal, connected_terminal: Terminal, phases: Set[SinglePhaseKind]) -> ConnectivityResult:
nominal_phase_paths = [NominalPhasePath(phase, phase) for phase in phases if phase in connected_terminal.phases.single_phases]
if not nominal_phase_paths:
xy_phases = {phase for phase in phases if phase == SinglePhaseKind.X or phase == SinglePhaseKind.Y}
connected_xy_phases = {phase for phase in connected_terminal.phases.single_phases if phase == SinglePhaseKind.X or phase == SinglePhaseKind.Y}
_process_xy_phases(terminal, connected_terminal, phases, xy_phases, connected_xy_phases, nominal_phase_paths)
return ConnectivityResult(from_terminal=terminal, to_terminal=connected_terminal, nominal_phase_paths=nominal_phase_paths)
def _process_xy_phases(terminal: Terminal, connected_terminal: Terminal, phases: Set[SinglePhaseKind], xy_phases: Set[SinglePhaseKind],
connectied_xy_phases: Set[SinglePhaseKind], nominal_phase_paths: List[NominalPhasePath]):
if (not xy_phases and not connectied_xy_phases) or (xy_phases and connectied_xy_phases):
return
for phase in xy_phases:
i = terminal.phases.single_phases.index(phase)
if i < len(connected_terminal.phases.single_phases):
nominal_phase_paths.append(NominalPhasePath(from_phase=phase, to_phase=connected_terminal.phases.single_phases[i]))
for phase in connectied_xy_phases:
i = connected_terminal.phases.single_phases.index(phase)
if i < len(terminal.phases.single_phases):
terminal_phase = terminal.phases.single_phases[i]
if terminal_phase in phases:
nominal_phase_paths.append(NominalPhasePath(from_phase=terminal_phase, to_phase=phase))
@dataclass(slots=True)
class ConnectivityResult(object):
"""
Stores the connectivity between two terminals, including the mapping between the nominal phases.
This class is intended to be used in an immutable way. You should avoid modifying it after it has been created.
"""
from_terminal: Terminal
"""The terminal from which the connectivity was requested."""
to_terminal: Terminal
"""The terminal which is connected to the requested terminal."""
nominal_phase_paths: Tuple[NominalPhasePath]
"""The mapping of nominal phase paths between the from and to terminals."""
def __init__(self, nominal_phase_paths: List[NominalPhasePath]):
self.nominal_phase_paths = tuple(sorted(nominal_phase_paths, key=attrgetter('from_terminal', 'to_terminal')))
def __eq__(self, other: ConnectivityResult):
if self is other:
return True
try:
return self.from_terminal is other.from_terminal and self.to_terminal is other.to_terminal and self.nominal_phase_paths != other.nominal_phase_paths
except:
return False
def __ne__(self, other):
if self is other:
return False
try:
return self.from_terminal is not other.from_terminal or self.to_terminal is not other.to_terminal or self.nominal_phase_paths != other.nominal_phase_paths
except:
return True
def __str__(self):
return (f"ConnectivityResult(from_terminal={self.from_equip.mrid}-t{self.from_terminal.sequence_number}"
f", to_terminal={self.to_equip.mrid}-t{self.to_terminal.sequence_number}, core_paths={self.nominal_phase_paths})")
def __hash__(self):
res = self.from_terminal.mrid.__hash__()
res = 31 * res + self.to_terminal.mrid.__hash__()
res = 31 * res + self.nominal_phase_paths.__hash__()
return res
@property
def from_equip(self) -> Optional[ConductingEquipment]:
"""The conducting equipment that owns the `from_terminal."""
return self.from_terminal.conducting_equipment
@property
def to_equip(self) -> Optional[ConductingEquipment]:
"""The conducting equipment that owns the `to_terminal`."""
return self.to_terminal.conducting_equipment
@property
def from_nominal_phases(self) -> List[SinglePhaseKind]:
"""The nominal phases that are connected in the `from_terminal`."""
return [npp.from_phase for npp in self.nominal_phase_paths]
@property
def to_nominal_phases(self) -> List[SinglePhaseKind]:
"""The nominal phases that are connected in the `to_terminal`."""
return [npp.to_phase for npp in self.nominal_phase_paths] | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/tracing/connectivity.py | connectivity.py |
import logging
from typing import Optional, Callable, Set, Iterable, TypeVar
from zepben.cimbend.cim.iec61970.base.core.conducting_equipment import ConductingEquipment
from zepben.cimbend.cim.iec61970.base.core.terminal import Terminal
from zepben.cimbend.cim.iec61970.base.wires.single_phase_kind import SinglePhaseKind
from zepben.cimbend.model.phasedirection import PhaseDirection
from zepben.cimbend.tracing.phase_step import PhaseStep
from zepben.cimbend.tracing.phase_status import PhaseStatus, current_phases, normal_phases
from zepben.cimbend.tracing.connectivity import get_connected_equipment, get_connectivity
from zepben.cimbend.tracing.util import currently_open, normally_open
from zepben.cimbend.traversals import Traversal, depth_first, Queue, PriorityQueue
__all__ = ["queue_next_terminal", "normal_downstream_trace", "create_basic_depth_trace", "connected_equipment_trace", "current_downstream_trace"]
tracing_logger = logging.getLogger("queue_next")
T = TypeVar("T")
def connected_equipment_trace():
return create_basic_depth_trace(conducting_equipment_queue_next)
def create_basic_depth_trace(queue_next: Callable[[T, Set[T]], Iterable[T]]):
return Traversal(queue_next, depth_first())
def conducting_equipment_queue_next(conducting_equipment: Optional[ConductingEquipment], exclude: Optional[Set] = None) -> Iterable[ConductingEquipment]:
"""
Get the next `ConductingEquipment` to queue next as determined by `conducting_equipment`s connectivity.
`conducting_equipment` the `ConductingEquipment` to fetch connected equipment for.
`exclude` Any `ConductingEquipment` that should be excluded from the result.
Returns a list of `ConductingEquipment` that should be queued next.
"""
if exclude is None:
exclude = []
if conducting_equipment:
crs = get_connected_equipment(conducting_equipment, exclude)
return [cr.to_equip for cr in crs if cr.to_equip and cr.to_equip not in exclude]
def current_downstream_trace(queue: Queue = None, **kwargs):
"""
Create a downstream trace over current phases
`queue` Queue to use for this trace. Defaults to a `zepben.cimbend.traversals.queue.PriorityQueue`
`kwargs` Args to be passed to `zepben.cimbend.Traversal`
Returns A `zepben.cimbend.traversals.Traversal`
"""
return Traversal(queue_next=_create_downstream_queue_next(currently_open, current_phases), process_queue=queue, **kwargs)
def _create_downstream_queue_next(open_test: Callable[[ConductingEquipment, Optional[SinglePhaseKind]], bool],
active_phases: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
"""
Creates a queue_next function from the given open test and phase selector for use with traversals.
`open_test` Function that takes a ConductingEquipment and a phase and returns whether the phase on the equipment is open (True) or closed (False).
`active_phases` A `zepben.cimbend.phase_status.PhaseStatus`
Returns A queue_next function for use with `zepben.cimbend.BaseTraversal` classes
"""
def qn(phase_step, visited):
connected_terms = []
if not phase_step:
return connected_terms
out_phases = set()
for term in phase_step.conducting_equipment.terminals:
_get_phases_with_direction(open_test, active_phases, term, phase_step.phases, PhaseDirection.OUT, out_phases)
if out_phases:
crs = get_connectivity(term, out_phases)
for cr in crs:
if cr.to_equip is not None:
if cr.to_equip in visited:
continue
connected_terms.append(PhaseStep(cr.to_equip, out_phases, cr.from_equip))
return connected_terms
return qn
def queue_next_terminal(item, exclude: Optional[Set] = None):
"""
Wrapper tracing queue function for fetching the terminals that should be queued based on their connectivity
`item` The Terminal to fetch connected `zepben.cimbend.iec61970.base.core.terminal.Terminal`s for.
`exclude` set of `Terminal`s to be excluded from queuing.
Returns a list of `zepben.cimbend.iec61970.base.core.terminal.Terminal`s to be queued
"""
other_terms = item.get_other_terminals()
if not other_terms:
# If there are no other terminals we get connectivity for this one and return that. Note that this will
# also return connections for EnergyConsumer's, but upstream will be covered by the exclude parameter and thus
# should yield an empty list.
to_terms = [cr.to_terminal for cr in item.get_connectivity(exclude=exclude)]
if len(to_terms) > 0:
tracing_logger.debug(f"Queuing {to_terms[0].mrid} from single terminal equipment {item.mrid}")
return to_terms
crs = []
for term in other_terms:
crs.extend(term.get_connectivity(exclude=exclude))
to_terms = [cr.to_terminal for cr in crs]
tracing_logger.debug(f"Queuing terminals: [{', '.join(t.mrid for t in to_terms)}] from {item.mrid}")
return to_terms
def normal_downstream_trace(queue: Queue = None, **kwargs):
"""
Create a downstream trace over nominal phases.
`queue` Queue to use for this trace. Defaults to a `zepben.cimbend.traversals.queue.PriorityQueue`
`kwargs` Args to be passed to `zepben.cimbend.Traversal`
Returns A `zepben.cimbend.traversals.Traversal`
"""
if queue is None:
queue = PriorityQueue()
return Traversal(queue_next=_create_downstream_queue_next(normally_open, normal_phases), process_queue=queue, **kwargs)
def _get_phases_with_direction(open_test: Callable[[ConductingEquipment, Optional[SinglePhaseKind]], bool],
active_phases: Callable[[Terminal, SinglePhaseKind], PhaseStatus],
terminal: Terminal,
candidate_phases: Set[SinglePhaseKind],
direction: PhaseDirection,
matched_phases: Set[SinglePhaseKind]):
"""
Adds the closed phases from `terminal` in a specified `zepben.cimbend.model.phasedirection.PhaseDirection` to `matched_phases`.
`open_test` Function that takes a ConductingEquipment and a phase and returns whether the phase on the equipment is open (True) or closed (False).
`active_phases` A `zepben.cimbend.phase_status.PhaseStatus`
`terminal` `zepben.cimbend.cim.iec61970.base.core.terminal.Terminal` to retrieve phases for
`filter_cores` The phases of `terminal` to test.
`direction` The `zepben.cimbend.model.phasedirection.PhaseDirection` to check against.
`matched_phases` The set of matched phases to add to.
"""
if terminal.conducting_equipment is None:
raise TraceException(f"Terminal {terminal} did not have an associated ConductingEquipment, cannot get phases.")
for phase in candidate_phases:
if phase in terminal.phases.single_phases and not open_test(terminal.conducting_equipment, phase):
if active_phases(terminal, phase).direction().has(direction):
matched_phases.add(phase)
class TraceException(Exception):
pass | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/tracing/traces.py | traces.py |
from __future__ import annotations
import copy
import logging
from dataclassy import dataclass
from enum import Enum
from zepben.cimbend.cim.iec61970.base.wires.energy_source import EnergySource
from zepben.cimbend.cim.iec61970.base.wires.switch import Breaker
from zepben.cimbend.cim.iec61970.base.wires.single_phase_kind import SinglePhaseKind
from zepben.cimbend.model.phasedirection import PhaseDirection
from zepben.cimbend.exceptions import PhaseException
from zepben.cimbend.tracing.connectivity import get_connectivity
from zepben.cimbend.exceptions import TracingException
from zepben.cimbend.tracing.phase_status import normal_phases, current_phases
from zepben.cimbend.tracing.traces import queue_next_terminal
from zepben.cimbend.traversals.queue import PriorityQueue
from zepben.cimbend.traversals.tracing import Traversal
from zepben.cimbend.tracing.phase_status import PhaseStatus
from zepben.cimbend.traversals.branch_recursive_tracing import BranchRecursiveTraversal
from zepben.cimbend.tracing.util import normally_open, currently_open
from typing import Set, Callable, List, Iterable, Optional
__all__ = ["FeederProcessingStatus", "SetPhases", "FeederCbTerminalPhasesByStatus", "DelayedFeederTrace",
"set_phases_and_queue_next", "set_current_phases_and_queue_next", "set_normal_phases_and_queue_next"]
logger = logging.getLogger("phasing.py")
class FeederProcessingStatus(Enum):
COMPLETE = 0,
PARTIAL = 1,
NONE = 2
@dataclass(slots=True)
class FeederCbTerminalPhasesByStatus:
terminal: Terminal
in_phases: Set[SinglePhaseKind] = set()
none_phases: Set[SinglePhaseKind] = set()
phases_to_flow: Set[SinglePhaseKind] = set()
@dataclass(slots=True)
class DelayedFeederTrace:
out_terminal: Terminal
phases_to_flow: Set[SinglePhaseKind]
class SetPhases(object):
def __init__(self):
self.normal_traversal = BranchRecursiveTraversal(queue_next=set_normal_phases_and_queue_next,
process_queue=PriorityQueue(),
branch_queue=PriorityQueue())
self.current_traversal = BranchRecursiveTraversal(queue_next=set_current_phases_and_queue_next,
process_queue=PriorityQueue(),
branch_queue=PriorityQueue())
async def run(self, network: NetworkService):
# terminals = await _apply_phases_from_feeder_cbs(network)
await _apply_phases_from_sources(network)
terminals = [term for es in network.objects(EnergySource) if es.num_phases() > 0 for term in es.terminals]
if not terminals:
raise TracingException("No feeder sources were found, tracing cannot be performed.")
breakers = network.objects(Breaker)
await self.run_complete(terminals, breakers)
async def run_complete(self, terminals: Iterable[Terminal], breakers: Iterable[Breaker]):
feeder_cbs = [br for br in breakers if br.is_substation_breaker()]
await self._run_normal(terminals, feeder_cbs)
await self._run_current(terminals, feeder_cbs)
async def _run_normal(self, terminals, feeder_cbs):
await run_set_phasing(terminals, feeder_cbs, self.normal_traversal, normally_open, normal_phases)
async def _run_current(self, terminals, feeder_cbs):
await run_set_phasing(terminals, feeder_cbs, self.current_traversal, currently_open, current_phases)
async def run_ce(self, ce: ConductingEquipment, breakers: Iterable[Breaker]):
if ce.num_terminals() == 0:
return
for in_term in ce.terminals:
normal_phases_to_flow = _get_phases_to_flow(in_term, normally_open, normal_phases)
current_phases_to_flow = _get_phases_to_flow(in_term, currently_open, current_phases)
for out_term in ce.terminals:
if out_term is not in_term:
_flow_through_equipment(self.normal_traversal, in_term, out_term, normal_phases_to_flow, normal_phases)
_flow_through_equipment(self.current_traversal, in_term, out_term, current_phases_to_flow, current_phases)
self.normal_traversal.tracker.clear()
self.current_traversal.tracker.clear()
await self.run_complete(ce.terminals, breakers)
async def find_es_breaker_terminal(es):
"""
From an EnergySource finds the closest connected Feeder CB (Breaker that is part of a substation).
At the moment we assume that all EnergySource's with EnergySourcePhase's will be associated with at least a
single feeder circuit breaker, and thus this function given an `EnergySource` will perform a trace that returns
the first `zepben.cimbend.iec61970.base.core.terminal.Terminal` encountered from that `EnergySource` that belongs to a `Breaker`. This `zepben.cimbend.iec61970.base.core.terminal.Terminal` should always
be the most downstream `zepben.cimbend.iec61970.base.core.terminal.Terminal` on the `Breaker`, and thus can then be used for setting `Direction` downstream and
away from this `Breaker`.
TODO: check how ES are normally connected to feeder CB's.
"""
out_terminals = set()
async def stop_on_sub_breaker(term, exc=None):
if out_terminals: # stop as soon as we find a substation breaker.
return True
try:
if term.conducting_equipment.is_substation_breaker():
out_terminals.add(term)
return True
except AttributeError:
return False
return False
t = Traversal(queue_next=queue_next_terminal, start_item=es.terminals[0], process_queue=PriorityQueue(), stop_conditions=[stop_on_sub_breaker])
await t.trace()
return out_terminals
async def _apply_phases_from_feeder_cbs(network):
"""
Apply phase and direction on all Feeder Circuit Breakers. Will make all phases on the outgoing Terminal of a
`Breaker` that is part of a substation have a `Direction` of `OUT`.
`network` `zepben.cimbend.network.Network` to apply phasing on.
"""
start_terms = []
# TODO: check if below assumption is correct
# We find the substation breaker from the networks energy sources as we assume that the ES will be wired below
# the breaker, and thus we can determine which terminal of the breaker to flow out from and apply phases.
for es in network.energy_sources.values():
esp = es.energy_source_phases
if esp:
if len(esp) != es.num_cores:
# TODO: java network phases doesn't throw here, but would throw in the below for loop if num_phases > len(esp). why does java silently handle less cores?
logger.error(f"Energy source {es.name} [{es.mrid}] is a source with {len(esp)} and {es.num_phases}. Number of phases should match number of cores. Phasing cannot be applied")
raise TracingException(
f"Energy source {es.name} [{es.mrid}] is a source with {len(esp)} and {es.num_cores}. Number of phases should match number of cores. Phasing cannot be applied")
breaker_terms = await find_es_breaker_terminal(es)
for terminal in breaker_terms:
for phase in terminal.phases.single_phases:
normal_phases(terminal, phase).add(esp[phase].phase, PhaseDirection.OUT)
current_phases(terminal, phase).add(esp[phase].phase, PhaseDirection.OUT)
logger.debug(f"Set {terminal.conducting_equipment.mrid} as Feeder Circuit Breaker with phases {terminal.phases.phase}")
start_terms.extend(breaker_terms)
return start_terms
async def _apply_phases_from_sources(network: NetworkService):
"""
Apply phase and direction on all Feeder Circuit Breakers. Will make all phases on the outgoing Terminal of a
`Breaker` that is part of a substation have a `Direction` of `OUT`.
`network` `zepben.cimbend.network.Network` to apply phasing on.
"""
for es in network.objects(EnergySource):
if es.num_phases() > 0:
await _apply_phases_from_source(es)
async def _apply_phases_from_source(energy_source: EnergySource):
if energy_source.num_terminals() == 0:
return
es_phases = set()
for phase in energy_source.phases:
es_phases.add(phase)
nominal_phases = set()
for terminal in energy_source.terminals:
nominal_phases.update(terminal.phases.single_phases)
if len(es_phases) != len(nominal_phases):
logger.warning((f"Energy source {str(energy_source)} is a source with {len(es_phases)} phases and {len(nominal_phases)} nominal phases. "
f"Number of phases should match the number of nominal phases!"))
for term in energy_source.terminals:
for phase in term.phases.single_phases:
normal_phases(term, phase).add(phase, PhaseDirection.OUT)
current_phases(term, phase).add(phase, PhaseDirection.OUT)
# TODO: pass through visited and be smart with it
def set_normal_phases_and_queue_next(terminal, traversal, visited):
set_phases_and_queue_next(terminal, traversal, normally_open, normal_phases)
def set_current_phases_and_queue_next(terminal, traversal, visited):
set_phases_and_queue_next(terminal, traversal, currently_open, current_phases)
def set_phases_and_queue_next(current: Terminal,
traversal: BranchRecursiveTraversal,
open_test: Callable[[ConductingEquipment, SinglePhaseKind], bool],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
phases_to_flow = _get_phases_to_flow(current, open_test, phase_selector)
if current.conducting_equipment:
for out_terminal in current.conducting_equipment.terminals:
if out_terminal != current and _flow_through_equipment(traversal, current, out_terminal, phases_to_flow, phase_selector):
_flow_out_to_connected_terminals_and_queue(traversal, out_terminal, phases_to_flow, phase_selector)
async def run_set_phasing(start_terminals: List[Terminal],
process_feeder_cbs: List[Breaker],
traversal: BranchRecursiveTraversal,
open_test: Callable[[ConductingEquipment, Optional[SinglePhaseKind]], bool],
phase_selector: Callable[[Terminal, Optional[SinglePhaseKind]], PhaseStatus]):
for terminal in start_terminals:
await _run_terminal(terminal, traversal, phase_selector)
# We take a copy of the feeder CB's as we will modify the list while processing them.
process_feeder_cbs = copy.copy(process_feeder_cbs)
keep_processing = True
while keep_processing:
delayed_feeder_traces = []
for feeder_cb in process_feeder_cbs:
status = _run_feeder_breaker(feeder_cb, traversal, open_test, phase_selector, delayed_feeder_traces)
if status == FeederProcessingStatus.COMPLETE:
process_feeder_cbs.remove(feeder_cb)
for trace in delayed_feeder_traces:
await _run_from_out_terminal(traversal, trace.out_terminal, trace.phases_to_flow, phase_selector)
keep_processing = len(delayed_feeder_traces) > 0
async def _run_terminal(start: Terminal, traversal: BranchRecursiveTraversal, phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
phases_to_flow = {phase for phase in start.phases.single_phases if phase_selector(start, phase).direction().has(PhaseDirection.OUT)}
await _run_from_out_terminal(traversal, start, phases_to_flow, phase_selector)
async def _run_from_out_terminal(traversal: BranchRecursiveTraversal, out_terminal: Terminal, phases_to_flow: Set[SinglePhaseKind],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
traversal.reset()
traversal.tracker.visit(out_terminal)
_flow_out_to_connected_terminals_and_queue(traversal, out_terminal, phases_to_flow, phase_selector)
await traversal.trace()
def _flow_out_to_connected_terminals_and_queue(traversal: BranchRecursiveTraversal, out_terminal: Terminal, phases_to_flow: Set[SinglePhaseKind],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
connectivity_results = get_connectivity(out_terminal, phases_to_flow)
for cr in connectivity_results:
in_term = cr.to_terminal
has_added = False
for oi in cr.nominal_phase_paths:
out_core = oi.from_core
in_core = oi.to_core
out_phase = phase_selector(out_terminal, out_core).phase()
in_phase = phase_selector(in_term, in_core)
try:
if in_phase.add(out_phase, PhaseDirection.IN):
has_added = True
except PhaseException as ex:
raise PhaseException(
(f"Attempted to apply more than one phase to [{in_term.conducting_equipment.mrid if in_term.conducting_equipment else in_term.mrid}"
f" on nominal phase {oi.to_phase}. Attempted to apply phase {out_phase} to {in_phase.phase()}."), ex)
if has_added and not traversal.has_visited(in_term):
if len(connectivity_results) > 1 or (out_terminal.conducting_equipment is not None and out_terminal.conducting_equipment.num_terminals() > 2):
branch = traversal.create_branch()
branch.start_item = in_term
traversal.branch_queue.put(branch)
else:
traversal.process_queue.put(in_term)
def _get_phases_to_flow(terminal: Terminal,
open_test: Callable[[ConductingEquipment, Optional[SinglePhaseKind]], bool],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
phases_to_flow = set()
try:
if terminal.conducting_equipment.is_substation_breaker():
return phases_to_flow
except AttributeError:
pass
if terminal.conducting_equipment is None:
return phases_to_flow
equip = terminal.conducting_equipment
for phase in terminal.phases.single_phases:
if not open_test(equip, phase) and phase_selector(terminal, phase).direction().has(PhaseDirection.IN):
phases_to_flow.add(phase)
return phases_to_flow
def _flow_through_equipment(traversal: BranchRecursiveTraversal, in_terminal: Terminal, out_terminal: Terminal, phases_to_flow: Set[SinglePhaseKind],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
traversal.tracker.visit(out_terminal)
has_changes = False
for phase in phases_to_flow:
out_phase_status = phase_selector(out_terminal, phase)
try:
in_phase = phase_selector(in_terminal, phase).phase()
applied = out_phase_status.add(in_phase, PhaseDirection.OUT)
has_changes = applied or has_changes
except PhaseException as ex:
raise PhaseException((
f"Attempted to apply more than one phase to {out_terminal.conducting_equipment.mrid if out_terminal.conducting_equipment else in_terminal.mrid}"
f" on nominal phase {phase}. Detected phases {out_phase_status.phase()} and {in_phase}. Underlying error was {str(ex)}"),
ex)
return has_changes
def _get_feeder_cb_terminal_cores_by_status(feeder_cb: Breaker,
open_test: Callable[[ConductingEquipment, Optional[SinglePhaseKind]], bool],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus]):
res = []
for terminal in feeder_cb.terminals:
status = FeederCbTerminalPhasesByStatus(terminal=terminal)
res.append(status)
for phase in terminal.phases.single_phases:
phase_status = phase_selector(terminal, phase)
if phase_status.direction() == PhaseDirection.IN:
status.in_phases.add(phase)
if not open_test(feeder_cb, phase):
status.phases_to_flow.add(phase)
elif phase_status.direction() == PhaseDirection.BOTH:
status.in_phases.add(phase)
elif phase_status.direction() == PhaseDirection.NONE:
status.none_phases.add(phase)
return res
def _flow_through_feeder_cb_and_queue(in_terminal: FeederCbTerminalPhasesByStatus,
out_terminal: FeederCbTerminalPhasesByStatus,
traversal: BranchRecursiveTraversal,
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus],
delayed_traces: List,
processed_phases: Set[SinglePhaseKind]):
if not in_terminal.in_phases:
return
phases_to_flow = copy.copy(in_terminal.phases_to_flow)
for phase in in_terminal.terminal.phases.single_phases:
if phase in in_terminal.in_phases:
processed_phases.add(phase)
# Remove any phases that have already been processed from the other side
if phase not in out_terminal.none_phases:
phases_to_flow.remove(phase)
if _flow_through_equipment(traversal, in_terminal.terminal, out_terminal.terminal, phases_to_flow, phase_selector):
delayed_traces.append(DelayedFeederTrace(out_terminal.terminal, phases_to_flow))
def _run_feeder_breaker(feeder_cb: Breaker,
traversal: BranchRecursiveTraversal,
open_test: Callable[[ConductingEquipment, Optional[SinglePhaseKind]], bool],
phase_selector: Callable[[Terminal, SinglePhaseKind], PhaseStatus],
delayed_traces: List):
if feeder_cb.num_terminals() not in (1, 2):
logger.warning(f"Ignoring feeder CB {str(feeder_cb)} with {feeder_cb.num_terminals()} terminals, expected 1 or 2 terminals")
return FeederProcessingStatus.COMPLETE
if feeder_cb.num_terminals() == 1:
set_phases_and_queue_next(next(feeder_cb.terminals), traversal, open_test, phase_selector)
return FeederProcessingStatus.COMPLETE
processed_phases = set()
statuses = _get_feeder_cb_terminal_cores_by_status(feeder_cb, open_test, phase_selector)
_flow_through_feeder_cb_and_queue(statuses[0], statuses[1], traversal, phase_selector, delayed_traces, processed_phases)
_flow_through_feeder_cb_and_queue(statuses[1], statuses[0], traversal, phase_selector, delayed_traces, processed_phases)
nominal_phases = {phase for term in feeder_cb.terminals for phase in term.phases.single_phases}
if len(processed_phases) == len(nominal_phases):
return FeederProcessingStatus.COMPLETE
elif processed_phases:
return FeederProcessingStatus.PARTIAL
else:
return FeederProcessingStatus.NONE | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/tracing/phasing.py | phasing.py |
from __future__ import annotations
from zepben.cimbend.cim.iec61970.base.wires import SinglePhaseKind
from zepben.cimbend.model.phasedirection import PhaseDirection
from abc import ABC, abstractmethod
__all__ = ["normal_phases", "current_phases", "PhaseStatus", "NormalPhases", "CurrentPhases"]
def normal_phases(terminal: Terminal, phase: SinglePhaseKind):
return NormalPhases(terminal, phase)
def current_phases(terminal: Terminal, phase: SinglePhaseKind):
return CurrentPhases(terminal, phase)
class PhaseStatus(ABC):
@abstractmethod
def phase(self):
"""
Returns The phase added to this status
"""
raise NotImplementedError()
@abstractmethod
def direction(self):
"""
Returns The direction added to this status.
"""
raise NotImplementedError()
@abstractmethod
def set(self, phase: SinglePhaseKind, direction: PhaseDirection):
"""
Clears the phase and sets it to the specified phase and direction.
If the passed in phase is NONE or the passed in direction is NONE, this should clear the phase status.
`phase` The new phase to be set.
`direction` The direction of the phase.
"""
raise NotImplementedError()
@abstractmethod
def add(self, phase: SinglePhaseKind, direction: PhaseDirection):
"""
Adds a phase to the status with the given direction.
`phase` The phase to be added.
`direction` The direction of the phase.
Returns True if the phase or direction has been updated
"""
raise NotImplementedError()
@abstractmethod
def remove(self, phase: SinglePhaseKind, direction: PhaseDirection = None):
"""
Removes a phase from the status. If direction is supplied will remove phase matching the direction.
`phase` The phase to be removed.
`direction` The direction to match with the phase being removed.
Returns True if the phase or direction has been removed.
"""
raise NotImplementedError()
class NormalPhases(PhaseStatus):
def __init__(self, terminal: Terminal, nominal_phase: SinglePhaseKind):
self.terminal = terminal
self.nominal_phase = nominal_phase
def phase(self):
return self.terminal.traced_phases.phase_normal(self.nominal_phase)
def direction(self):
return self.terminal.traced_phases.direction_normal(self.nominal_phase)
def set(self, phase_kind: SinglePhaseKind, dir: PhaseDirection):
return self.terminal.traced_phases.set_normal(phase_kind, self.nominal_phase, dir)
def add(self, phase_kind: SinglePhaseKind, dir: PhaseDirection):
return self.terminal.traced_phases.add_normal(phase_kind, self.nominal_phase, dir)
def remove(self, phase_kind: SinglePhaseKind, dir: PhaseDirection = None):
if dir is not None:
return self.terminal.traced_phases.remove_normal(phase_kind, self.nominal_phase, dir)
else:
return self.terminal.traced_phases.remove_normal(phase_kind, self.nominal_phase)
class CurrentPhases(PhaseStatus):
def __init__(self, terminal: Terminal, nominal_phase: SinglePhaseKind):
self.terminal = terminal
self.nominal_phase = nominal_phase
def phase(self):
return self.terminal.traced_phases.phase_current(self.nominal_phase)
def direction(self):
return self.terminal.traced_phases.direction_current(self.nominal_phase)
def set(self, phase_kind: SinglePhaseKind, dir: PhaseDirection):
return self.terminal.traced_phases.set_current(phase_kind, self.nominal_phase, dir)
def add(self, phase_kind: SinglePhaseKind, dir: PhaseDirection):
return self.terminal.traced_phases.add_current(phase_kind, self.nominal_phase, dir)
def remove(self, phase_kind: SinglePhaseKind, dir: PhaseDirection = None):
if dir is not None:
return self.terminal.traced_phases.remove_current(phase_kind, self.nominal_phase, dir)
else:
return self.terminal.traced_phases.remove_current(phase_kind, self.nominal_phase) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/tracing/phase_status.py | phase_status.py |
from __future__ import annotations
from dataclassy import dataclass
from zepben.cimbend.tracing.phase_step import PhaseStep
from zepben.cimbend.tracing.traces import normal_downstream_trace, current_downstream_trace
from typing import Callable, List, Optional, Dict
from enum import Enum
__all__ = ["Status", "Result", "find_current", "find_normal"]
class Status(Enum):
SUCCESS = 1,
NO_PATH = 2,
MISMATCHED_FROM_TO = 3
@dataclass(slots=True)
class Result(object):
status: Status = Status.SUCCESS
equipment: Optional[Dict[str, ConductingEquipment]] = {}
async def _trace(traversal_supplier: Callable[[...], Traversal], from_: ConductingEquipment, to: Optional[ConductingEquipment]):
if from_.num_terminals() == 0:
if to is not None:
return Result(status=Status.NO_PATH)
elif from_.num_usage_points() != 0:
return Result(equipment={from_.mrid: from_})
else:
return Result(status=Status.SUCCESS)
extent_ids = {ce.mrid for ce in (from_, to) if ce is not None}
path_found = [to is None]
with_usage_points = {}
async def stop_contains(phase_step):
return phase_step.conducting_equipment.mrid in extent_ids
async def step(phase_step, is_stopping):
if is_stopping:
path_found[0] = True
if phase_step.conducting_equipment.num_usage_points() != 0:
with_usage_points[phase_step.conducting_equipment.mrid] = phase_step.conducting_equipment
traversal = traversal_supplier()
traversal.add_stop_condition(stop_contains)
traversal.add_step_action(step)
traversal.reset()
await traversal.trace(PhaseStep(from_, frozenset(next(from_.terminals).phases.single_phases)), can_stop_on_start_item=False)
# this works off a downstream trace, so if we didn't find a path try reverse from and to in case the "to" point was higher up in the network.
if to is not None and not path_found[0]:
if to.num_terminals() == 0:
return Result(status=Status.NO_PATH)
with_usage_points.clear()
traversal.reset()
traversal.trace(PhaseStep(to, frozenset(next(to.terminals).phases.single_phases)), can_stop_on_start_item=False)
if path_found[0]:
return Result(conducting_equipment=with_usage_points)
else:
return Result(status=Status.NO_PATH)
async def _find(traversal_supplier: Callable[[...], Traversal], froms: List[ConductingEquipment], tos: List[ConductingEquipment]) -> List[Result]:
if len(froms) != len(tos):
return [Result(status=Status.MISMATCHED_FROM_TO)] * min(len(froms), len(tos))
res = []
for f, t in zip(froms, tos):
if t is not None and f.mrid == t.mrid:
res.append(Result(equipment={f.mrid: f} if f.num_usage_points() != 0 else None))
else:
res.append(_trace(traversal_supplier, f, t))
return res
def find_normal(from_: ConductingEquipment, to: ConductingEquipment):
return _find(normal_downstream_trace, froms=[from_], tos=[to])
def find_current(from_: ConductingEquipment, to: ConductingEquipment):
return _find(current_downstream_trace, froms=[from_], tos=[to]) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/tracing/find.py | find.py |
from zepben.cimbend.cim.iec61968.common.organisation_role import OrganisationRole
from zepben.cimbend.cim.iec61968.assets.asset import Asset
from zepben.cimbend.cim.iec61968.assets.pole import Pole
from zepben.cimbend.cim.iec61968.assets.streetlight import Streetlight
from zepben.cimbend.cim.iec61968.customers.customer import Customer
from zepben.cimbend.cim.iec61968.customers.customer_agreement import CustomerAgreement
from zepben.cimbend.cim.iec61968.customers.pricing_structure import PricingStructure
from zepben.cimbend.cim.iec61968.metering.metering import EndDevice, UsagePoint
from zepben.cimbend.cim.iec61968.operations.operational_restriction import OperationalRestriction
from zepben.cimbend.cim.iec61970.base.auxiliaryequipment import AuxiliaryEquipment
from zepben.cimbend.cim.iec61970.base.core.conducting_equipment import ConductingEquipment
from zepben.cimbend.cim.iec61970.base.core.connectivity_node import ConnectivityNode
from zepben.cimbend.cim.iec61970.base.core.equipment import Equipment
from zepben.cimbend.cim.iec61970.base.core.equipment_container import *
from zepben.cimbend.cim.iec61970.base.core.power_system_resource import *
from zepben.cimbend.cim.iec61970.base.core.regions import *
from zepben.cimbend.cim.iec61970.base.core.substation import *
from zepben.cimbend.cim.iec61970.base.core.terminal import Terminal
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_layout import Diagram, DiagramObject
from zepben.cimbend.cim.iec61970.base.meas.measurement import Measurement
from zepben.cimbend.cim.iec61970.base.meas.control import Control
from zepben.cimbend.cim.iec61970.base.scada.remote_source import RemoteSource
from zepben.cimbend.cim.iec61970.base.scada.remote_control import RemoteControl
from zepben.cimbend.cim.iec61970.base.wires.aclinesegment import Conductor
from zepben.cimbend.cim.iec61970.base.wires.energy_consumer import EnergyConsumer, EnergyConsumerPhase
from zepben.cimbend.cim.iec61970.base.wires.energy_source import EnergySource
from zepben.cimbend.cim.iec61970.base.wires.energy_source_phase import EnergySourcePhase
from zepben.cimbend.cim.iec61970.base.wires.power_transformer import *
from zepben.cimbend.cim.iec61970.infiec61970.feeder import Circuit, Loop
from zepben.cimbend.common.reference_resolvers import *
__all__ = ["per_length_sequence_impedance", "organisation_roles", "at_location", "ae_terminal", "ce_base_voltage", "ce_terminals",
"asset_info", "streetlights", "pole", "cn_terminals", "remote_control", "agreements", "customer",
"pricing_structures",
"diagram_objects", "diagram", "service_location", "ed_usage_points", "containers", "current_feeders",
"operational_restrictions",
"eq_usage_points", "ec_equipment", "ec_phases", "energy_consumer", "es_phases", "energy_source", "current_equipment",
"normal_energizing_substation", "normal_head_terminal", "sub_geographical_regions", "remote_source",
"or_equipment", "organisation",
"psr_location", "ends", "power_transformer", "tariffs", "transformer_end", "control", "measurement",
"geographical_region", "substations",
"normal_energizing_feeders", "sub_geographical_region", "conducting_equipment", "connectivity_node",
"te_base_voltage", "ratio_tap_changer",
"te_terminal", "end_devices", "up_equipment", "usage_point_location"]
def per_length_sequence_impedance(aclinesegment):
return BoundReferenceResolver(aclinesegment, acls_to_plsi_resolver, None)
def organisation_roles(asset: Asset) -> BoundReferenceResolver:
return BoundReferenceResolver(asset, asset_to_asset_org_role_resolver, None)
def at_location(asset: Asset) -> BoundReferenceResolver:
return BoundReferenceResolver(asset, asset_to_location_resolver, None)
def ae_terminal(auxiliaryEquipment: AuxiliaryEquipment) -> BoundReferenceResolver:
return BoundReferenceResolver(auxiliaryEquipment, aux_equip_to_term_resolver, None)
def ce_base_voltage(conducting_equipment: ConductingEquipment) -> BoundReferenceResolver:
return BoundReferenceResolver(conducting_equipment, cond_equip_to_bv_resolver, None)
def ce_terminals(conducting_equipment: ConductingEquipment) -> BoundReferenceResolver:
return BoundReferenceResolver(conducting_equipment, cond_equip_to_terminal_resolver, term_to_ce_resolver)
def asset_info(conductor: Conductor) -> BoundReferenceResolver:
return BoundReferenceResolver(conductor, conductor_to_wire_info_resolver, None)
def streetlights(pole: Pole) -> BoundReferenceResolver:
return BoundReferenceResolver(pole, pole_to_streetlight_resolver, streetlight_to_pole_resolver)
def pole(streetlight: Streetlight) -> BoundReferenceResolver:
return BoundReferenceResolver(streetlight, streetlight_to_pole_resolver, pole_to_streetlight_resolver)
def cn_terminals(connectivity_node: ConnectivityNode) -> BoundReferenceResolver:
return BoundReferenceResolver(connectivity_node, conn_node_to_term_resolver, term_to_cn_resolver)
def remote_control(control: Control) -> BoundReferenceResolver:
return BoundReferenceResolver(control, control_to_remote_control_resolver, rc_to_cont_resolver)
def agreements(customer: Customer) -> BoundReferenceResolver:
return BoundReferenceResolver(customer, cust_to_custagr_resolver, custagr_to_cust_resolver)
def customer(customer_agreement: CustomerAgreement) -> BoundReferenceResolver:
return BoundReferenceResolver(customer_agreement, custagr_to_cust_resolver, cust_to_custagr_resolver)
def pricing_structures(customer_agreement: CustomerAgreement) -> BoundReferenceResolver:
return BoundReferenceResolver(customer_agreement, custagr_to_ps_resolver, None)
def diagram_objects(diagram: Diagram) -> BoundReferenceResolver:
return BoundReferenceResolver(diagram, diag_to_diagobj_resolver, diagobj_to_diag_resolver)
def diagram(diagram_object: DiagramObject) -> BoundReferenceResolver:
return BoundReferenceResolver(diagram_object, diagobj_to_diag_resolver, diag_to_diagobj_resolver)
def service_location(end_device: EndDevice) -> BoundReferenceResolver:
return BoundReferenceResolver(end_device, ed_to_loc_resolver, None)
def ed_usage_points(end_device: EndDevice) -> BoundReferenceResolver:
return BoundReferenceResolver(end_device, ed_to_up_resolver, up_to_ed_resolver)
def containers(equipment: Equipment) -> BoundReferenceResolver:
return BoundReferenceResolver(equipment, eq_to_ec_resolver, ec_to_eq_resolver)
def current_feeders(equipment: Equipment) -> BoundReferenceResolver:
return BoundReferenceResolver(equipment, eq_to_curfeeder_resolver, curfeeder_to_eq_resolver)
def operational_restrictions(equipment: Equipment) -> BoundReferenceResolver:
return BoundReferenceResolver(equipment, eq_to_or_resolver, or_to_eq_resolver)
def eq_usage_points(equipment: Equipment) -> BoundReferenceResolver:
return BoundReferenceResolver(equipment, eq_to_up_resolver, up_to_eq_resolver)
def ec_equipment(equipment_container: EquipmentContainer) -> BoundReferenceResolver:
return BoundReferenceResolver(equipment_container, ec_to_eq_resolver, eq_to_ec_resolver)
def ec_phases(energy_consumer: EnergyConsumer) -> BoundReferenceResolver:
return BoundReferenceResolver(energy_consumer, ec_to_ecp_resolver, ecp_to_ec_resolver)
def energy_consumer(energy_consumer_phase: EnergyConsumerPhase) -> BoundReferenceResolver:
return BoundReferenceResolver(energy_consumer_phase, ecp_to_ec_resolver, ec_to_ecp_resolver)
def es_phases(energy_source: EnergySource) -> BoundReferenceResolver:
return BoundReferenceResolver(energy_source, es_to_esp_resolver, esp_to_es_resolver)
def energy_source(energy_source_phase: EnergySourcePhase) -> BoundReferenceResolver:
return BoundReferenceResolver(energy_source_phase, esp_to_es_resolver, es_to_esp_resolver)
def current_equipment(feeder: Feeder) -> BoundReferenceResolver:
return BoundReferenceResolver(feeder, curfeeder_to_eq_resolver, eq_to_curfeeder_resolver)
def normal_energizing_substation(feeder: Feeder) -> BoundReferenceResolver:
return BoundReferenceResolver(feeder, feeder_to_nes_resolver, sub_to_feeder_resolver)
def normal_head_terminal(feeder: Feeder) -> BoundReferenceResolver:
return BoundReferenceResolver(feeder, feeder_to_nht_resolver, None)
def sub_geographical_regions(geographical_region: GeographicalRegion) -> BoundReferenceResolver:
return BoundReferenceResolver(geographical_region, gr_to_sgr_resolver, sgr_to_gr_resolver)
def remote_source(measurement: Measurement) -> BoundReferenceResolver:
return BoundReferenceResolver(measurement, meas_to_rs_resolver, rs_to_meas_resolver)
def or_equipment(operational_restriction: OperationalRestriction) -> BoundReferenceResolver:
return BoundReferenceResolver(operational_restriction, or_to_eq_resolver, eq_to_or_resolver)
def organisation(organisation_role: OrganisationRole) -> BoundReferenceResolver:
return BoundReferenceResolver(organisation_role, orgr_to_org_resolver, None)
def psr_location(power_system_resource: PowerSystemResource) -> BoundReferenceResolver:
return BoundReferenceResolver(power_system_resource, psr_to_loc_resolver, None)
def ends(power_transformer: PowerTransformer) -> BoundReferenceResolver:
return BoundReferenceResolver(power_transformer, pt_to_pte_resolver, pte_to_pt_resolver)
def power_transformer(power_transformerEnd: PowerTransformerEnd) -> BoundReferenceResolver:
return BoundReferenceResolver(power_transformerEnd, pte_to_pt_resolver, pt_to_pte_resolver)
def tariffs(pricing_structure: PricingStructure) -> BoundReferenceResolver:
return BoundReferenceResolver(pricing_structure, ps_to_tariff_resolver, None)
def transformer_end(ratio_tap_changer: RatioTapChanger) -> BoundReferenceResolver:
return BoundReferenceResolver(ratio_tap_changer, rtc_to_te_resolver, te_to_rtc_resolver)
def control(remote_control: RemoteControl) -> BoundReferenceResolver:
return BoundReferenceResolver(remote_control, rc_to_cont_resolver, control_to_remote_control_resolver)
def measurement(remote_source: RemoteSource) -> BoundReferenceResolver:
return BoundReferenceResolver(remote_source, rs_to_meas_resolver, meas_to_rs_resolver)
def geographical_region(sub_geographical_region: SubGeographicalRegion) -> BoundReferenceResolver:
return BoundReferenceResolver(sub_geographical_region, sgr_to_gr_resolver, gr_to_sgr_resolver)
def substations(sub_geographical_region: SubGeographicalRegion) -> BoundReferenceResolver:
return BoundReferenceResolver(sub_geographical_region, sgr_to_sub_resolver, sub_to_sgr_resolver)
def normal_energizing_feeders(substation: Substation) -> BoundReferenceResolver:
return BoundReferenceResolver(substation, sub_to_feeder_resolver, feeder_to_nes_resolver)
def sub_geographical_region(substation: Substation) -> BoundReferenceResolver:
return BoundReferenceResolver(substation, sub_to_sgr_resolver, sgr_to_sub_resolver)
def circuits(substation: Substation) -> BoundReferenceResolver:
return BoundReferenceResolver(substation, sub_to_circuit_resolver, circuit_to_sub_resolver)
def normal_energized_loops(substation: Substation) -> BoundReferenceResolver:
return BoundReferenceResolver(substation, sub_to_eloop_resolver, loop_to_esub_resolver)
def loops(substation: Substation) -> BoundReferenceResolver:
return BoundReferenceResolver(substation, sub_to_loop_resolver, loop_to_sub_resolver)
def conducting_equipment(terminal: Terminal) -> BoundReferenceResolver:
return BoundReferenceResolver(terminal, term_to_ce_resolver, cond_equip_to_terminal_resolver)
def connectivity_node(terminal: Terminal) -> BoundReferenceResolver:
return BoundReferenceResolver(terminal, term_to_cn_resolver, conn_node_to_term_resolver)
def te_base_voltage(transformer_end: TransformerEnd) -> BoundReferenceResolver:
return BoundReferenceResolver(transformer_end, te_to_bv_resolver, None)
def ratio_tap_changer(transformer_end: TransformerEnd) -> BoundReferenceResolver:
return BoundReferenceResolver(transformer_end, te_to_rtc_resolver, rtc_to_te_resolver)
def te_terminal(transformer_end: TransformerEnd) -> BoundReferenceResolver:
return BoundReferenceResolver(transformer_end, te_to_term_resolver, None)
def end_devices(usage_point: UsagePoint) -> BoundReferenceResolver:
return BoundReferenceResolver(usage_point, up_to_ed_resolver, ed_to_up_resolver)
def up_equipment(usage_point: UsagePoint) -> BoundReferenceResolver:
return BoundReferenceResolver(usage_point, up_to_eq_resolver, eq_to_up_resolver)
def usage_point_location(usage_point: UsagePoint) -> BoundReferenceResolver:
return BoundReferenceResolver(usage_point, up_to_loc_resolver, None)
def loop(circuit: Circuit) -> BoundReferenceResolver:
return BoundReferenceResolver(circuit, circuit_to_loop_resolver, loop_to_circuit_resolver)
def end_terminal(circuit: Circuit) -> BoundReferenceResolver:
return BoundReferenceResolver(circuit, circuit_to_term_resolver, None)
def end_substation(circuit: Circuit) -> BoundReferenceResolver:
return BoundReferenceResolver(circuit, circuit_to_sub_resolver, sub_to_circuit_resolver)
def loop_circuits(loop: Loop) -> BoundReferenceResolver:
return BoundReferenceResolver(loop, loop_to_circuit_resolver, circuit_to_loop_resolver)
def loop_substations(loop: Loop) -> BoundReferenceResolver:
return BoundReferenceResolver(loop, loop_to_sub_resolver, sub_to_loop_resolver)
def loop_energizing_substations(loop: Loop) -> BoundReferenceResolver:
return BoundReferenceResolver(loop, loop_to_esub_resolver, sub_to_eloop_resolver) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/common/resolver.py | resolver.py |
from collections import OrderedDict
def create_registrar():
registry = {}
def registrar(func):
registry[func.__name__] = func
return func
registrar.all = registry
return registrar
# # A decorator simply used for registering Network getter functions.
# # If you create a new equipment map in __init__, you should create a corresponding getter function and
# # decorate it with @getter
# getter: ClassVar = create_registrar()
#
# # A decorator used to specify which types are stored in each map. For every map there should be a
# # corresponding `@property` declaration that is decorated with `type_map(class, [pb_class, gRPC_create_func])`,
# # where `class` indicates the CIM type stored in that map, `pb_class` optionally indicates `class`'s corresponding
# # Protobuf class, and `gRPC_create_func` indicates `pb_class`'s corresponding gRPC function for streaming.
# # Utilised in the `add` method, but also in the streaming library.
# type_map: ClassVar = map_type()
def map_type():
# Maps types to the decorated function. The ordering here is important, as we use this ordering when we
# serialise or deserialise from an Network.
type_map = OrderedDict()
types = []
# Maps protobuf types to CIM types
pb_to_cim = OrderedDict()
# Maps protobuf types to the name of a gRPC streaming function.
# For example, a Protobuf BaseVoltage maps to createBaseVoltage.
# This is used when streaming an Network.
grpc_func_map = dict()
def wrap(typ, weight: int, pb_typ=None, stream_func_name=None):
def mapper(func):
if pb_typ is None and stream_func_name is not None:
raise Exception(f"A protobuf type must be provided for {typ} because stream_func_name is set. We can only stream types with protobuf mappings.")
if typ in type_map:
raise Exception(f"Type {typ} already has an associated map - ensure {typ} corresponds to only one map")
if pb_typ in type_map:
raise Exception(f"Protobuf Type {pb_typ} already has an associated map - ensure {typ} corresponds to only one map")
types.append((typ, weight))
type_map[typ] = func
if pb_typ is not None:
type_map[pb_typ] = func
pb_to_cim[pb_typ] = typ
if stream_func_name is not None:
grpc_func_map[pb_typ] = stream_func_name
return func
return mapper
wrap.types = sorted(types, key=lambda t: t[1])
wrap.all = type_map
wrap.pb_to_cim = pb_to_cim
wrap.grpc = grpc_func_map
return wrap | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/common/decorators.py | decorators.py |
from __future__ import annotations
from abc import ABCMeta
from collections import OrderedDict
from dataclassy import dataclass
from typing import Dict, Generator, Callable, Optional, List, Set, Union, Iterable, Sized
from itertools import chain
from zepben.cimbend.common.reference_resolvers import BoundReferenceResolver, UnresolvedReference
__all__ = ["BaseService"]
_GET_DEFAULT = (1,)
@dataclass(slots=True)
class BaseService(object, metaclass=ABCMeta):
name: str
_objectsByType: Dict[type, Dict[str, IdentifiedObject]] = OrderedDict()
_unresolved_references: Dict[str, List[UnresolvedReference]] = OrderedDict()
def __contains__(self, mrid: str) -> bool:
"""
Check if `mrid` has any associated object.
`mrid` The mRID to search for.
Returns True if there is an object associated with the specified `mrid`, False otherwise.
"""
for type_map in self._objectsByType.values():
if mrid in type_map:
return True
return False
def __str__(self):
return f"{type.__name__}{f' {self.name}' if self.name else ''}"
def has_unresolved_references(self):
"""
Returns True if this service has unresolved references, False otherwise.
"""
return len(self._unresolved_references) > 0
def len_of(self, t: type = None) -> int:
"""
Get the len of objects of type `t` in the service.
`t` The type of object to get the len of. If None (default), will get the len of all objects in the service.
"""
if t is None:
return sum([len(vals) for vals in self._objectsByType.values()])
else:
return len(self._objectsByType[t].values())
def num_unresolved_references(self):
"""
Get the total number of unresolved references.
Note that this is not terribly cheap call, and should be used sparingly. To test if unresolved references exist,
use `has_unresolved_references()` instead.
Returns The number of references in the network that have not already been resolved.
"""
return len({r.to_mrid for reflist in self._unresolved_references.values() for r in reflist})
def unresolved_references(self):
for from_mrid, unresolved_refs in self._unresolved_references.copy().items():
yield from_mrid, unresolved_refs
def unresolved_mrids(self):
seen = set()
for refs in self._unresolved_references.copy().values():
for ref in refs:
if ref.to_mrid not in seen:
seen.add(ref.to_mrid)
yield ref.to_mrid
def get(self, mrid: str, type_: type = None, default=_GET_DEFAULT,
generate_error: Callable[[str, str], str] = lambda mrid, typ: f"Failed to find {typ}[{mrid}]") -> IdentifiedObject:
"""
Get an object associated with this service.
`mrid` The mRID of the `iec61970.base.core.identified_object.IdentifiedObject` to retrieve.
`type_` The `iec61970.base.core.identified_object.IdentifiedObject` subclass type of the object
with `mrid`. If None, will check all types stored in the service.
`default` The default to return if `mrid` can't be found in the service.
`generate_error` Function to call for an error message. Will be passed the mrid and _type (if set).
Returns The `iec61970.base.core.identified_object.IdentifiedObject` associated with `mrid`, or default
if it is set.
Raises `KeyError` if `mrid` was not found in the service with `_type` or if no objects of `_type` are
stored by the service and default was not set.
"""
if not mrid:
raise KeyError("You must specify an mRID to get. Empty/None is invalid.")
if type_:
try:
return self._objectsByType[type_][mrid]
except KeyError:
for c, obj_map in self._objectsByType.items():
if issubclass(c, type_):
try:
return obj_map[mrid]
except KeyError:
pass
if default is _GET_DEFAULT:
raise KeyError(generate_error(mrid, type_.__name__))
else:
return default
else:
for object_map in self._objectsByType.values():
if mrid in object_map:
return object_map[mrid]
if default is _GET_DEFAULT:
raise KeyError(generate_error(mrid, ""))
return default
def __getitem__(self, mrid):
"""
Get an object associated with this service.
Note that you should use `get` directly where the type of the desired object is known.
`mrid` The mRID of the `iec61970.base.core.identified_object.IdentifiedObject` to retrieve.
Returns The `iec61970.base.core.identified_object.IdentifiedObject` associated with `mrid`.
Raises `KeyError` if `mrid` was not found in the service with `type`.
"""
return self.get(mrid)
def add(self, identified_object: IdentifiedObject) -> bool:
"""
Associate an object with this service.
`identified_object` The object to associate with this service.
Returns True if the object is associated with this service, False otherwise.
"""
if not identified_object.mrid:
return False
# TODO: Only allow supported types
objs = self._objectsByType.get(identified_object.__class__, dict())
if identified_object.mrid in objs:
return False
# Check other types and make sure this mRID is unique
for obj_map in self._objectsByType.values():
if identified_object.mrid in obj_map:
return False
unresolved_refs = self._unresolved_references.get(identified_object.mrid, None)
if unresolved_refs:
for ref in unresolved_refs:
ref.resolver.resolve(ref.from_ref, identified_object)
del self._unresolved_references[identified_object.mrid]
objs[identified_object.mrid] = identified_object
self._objectsByType[identified_object.__class__] = objs
return True
def resolve_or_defer_reference(self, bound_resolver: BoundReferenceResolver, to_mrid: str) -> bool:
"""
Resolves a property reference between two types by looking up the `to_mrid` in the service and
using the provided `bound_resolver` to resolve the reference relationships (including any reverse relationship).
If the `to_mrid` object has not yet been added to the service, the reference resolution will be deferred until the
object with `to_mrid` is added to the service, which will then use the resolver from the `bound_resolver` at that
time to resolve the reference relationship.
`bound_resolver`
`to_mrid` The MRID of an object that is the subclass of the to_class of `bound_resolver`.
Returns true if the reference was resolved, otherwise false if it has been deferred.
"""
if not to_mrid:
return True
from_ = bound_resolver.from_obj
resolver = bound_resolver.resolver
reverse_resolver = bound_resolver.reverse_resolver
try:
to = self.get(to_mrid, resolver.to_class)
resolver.resolve(from_, to)
if reverse_resolver:
reverse_resolver.resolve(to, from_)
# Clean up any reverse unresolved references now that the reference has been resolved
if from_.mrid in self._unresolved_references:
refs = self._unresolved_references[from_.mrid]
self._unresolved_references[from_.mrid] = [ref for ref in refs if not ref.to_mrid == from_.mrid or not ref.resolver == reverse_resolver]
if not self._unresolved_references[from_.mrid]:
del self._unresolved_references[from_.mrid]
return True
except KeyError:
urefs = self._unresolved_references.get(to_mrid, list())
urefs.append(UnresolvedReference(from_ref=from_, to_mrid=to_mrid, resolver=resolver))
self._unresolved_references[to_mrid] = urefs
return False
def get_unresolved_reference_mrids(self, bound_resolvers: Union[BoundReferenceResolver, Sized[BoundReferenceResolver]]) -> Generator[str, None, None]:
"""
Gets a set of MRIDs that are referenced by the from_obj held by `bound_resolver` that are unresolved.
`bound_resolver` The `BoundReferenceResolver` to retrieve unresolved references for.
Returns Set of mRIDs that have unresolved references.
"""
seen = set()
try:
len(bound_resolvers)
resolvers = bound_resolvers
except TypeError:
resolvers = [bound_resolvers]
for refs in self._unresolved_references.values():
for ref in refs:
for resolver in resolvers:
if ref.from_ref is resolver.from_obj and ref.to_mrid not in seen and ref.resolver == resolver.resolver:
seen.add(ref.to_mrid)
yield ref.to_mrid
def remove(self, identified_object: IdentifiedObject) -> bool:
"""
Disassociate an object from this service.
`identified_object` THe object to disassociate from the service.
Raises `KeyError` if `identified_object` or its type was not present in the service.
"""
del self._objectsByType[identified_object.__class__][identified_object.mrid]
return True
def objects(self, obj_type: Optional[type] = None, exc_types: Optional[List[type]] = None) -> Generator[ IdentifiedObject, None, None]:
"""
Generator for the objects in this service of type `obj_type`.
`obj_type` The type of object to yield. If this is a base class it will yield all subclasses.
Returns Generator over
"""
if obj_type is None:
for typ, obj_map in self._objectsByType.items():
if exc_types:
if typ in exc_types:
continue
for obj in obj_map.values():
yield obj
return
else:
try:
for obj in self._objectsByType[obj_type].values():
yield obj
except KeyError:
for _type, object_map in self._objectsByType.items():
if issubclass(_type, obj_type):
for obj in object_map.values():
yield obj | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/common/base_service.py | base_service.py |
from dataclassy import dataclass
from typing import Callable, Optional
from zepben.cimbend.cim.iec61968.common.organisation import Organisation
from zepben.cimbend.cim.iec61968.common.organisation_role import OrganisationRole
from zepben.cimbend.cim.iec61968.assetinfo.wire_info import WireInfo
from zepben.cimbend.cim.iec61968.assets.asset import Asset
from zepben.cimbend.cim.iec61968.assets.pole import Pole
from zepben.cimbend.cim.iec61968.assets.streetlight import Streetlight
from zepben.cimbend.cim.iec61968.assets.asset_organisation_role import AssetOrganisationRole
from zepben.cimbend.cim.iec61968.common.location import Location
from zepben.cimbend.cim.iec61968.customers.customer import Customer
from zepben.cimbend.cim.iec61968.customers.customer_agreement import CustomerAgreement
from zepben.cimbend.cim.iec61968.customers.pricing_structure import PricingStructure
from zepben.cimbend.cim.iec61968.customers.tariff import Tariff
from zepben.cimbend.cim.iec61968.metering.metering import EndDevice, UsagePoint
from zepben.cimbend.cim.iec61968.operations.operational_restriction import OperationalRestriction
from zepben.cimbend.cim.iec61970.base.auxiliaryequipment import AuxiliaryEquipment
from zepben.cimbend.cim.iec61970.base.core.base_voltage import BaseVoltage
from zepben.cimbend.cim.iec61970.base.core.conducting_equipment import ConductingEquipment
from zepben.cimbend.cim.iec61970.base.core.connectivity_node import ConnectivityNode
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.cim.iec61970.base.core.equipment import Equipment
from zepben.cimbend.cim.iec61970.base.core.equipment_container import *
from zepben.cimbend.cim.iec61970.base.core.power_system_resource import *
from zepben.cimbend.cim.iec61970.base.core.regions import *
from zepben.cimbend.cim.iec61970.base.core.substation import *
from zepben.cimbend.cim.iec61970.base.core.terminal import Terminal
from zepben.cimbend.cim.iec61970.base.diagramlayout.diagram_layout import Diagram, DiagramObject
from zepben.cimbend.cim.iec61970.base.meas.measurement import Measurement
from zepben.cimbend.cim.iec61970.base.meas.control import Control
from zepben.cimbend.cim.iec61970.base.scada.remote_source import RemoteSource
from zepben.cimbend.cim.iec61970.base.scada.remote_control import RemoteControl
from zepben.cimbend.cim.iec61970.base.wires.aclinesegment import AcLineSegment, Conductor
from zepben.cimbend.cim.iec61970.base.wires.energy_consumer import EnergyConsumer, EnergyConsumerPhase
from zepben.cimbend.cim.iec61970.base.wires.energy_source import EnergySource
from zepben.cimbend.cim.iec61970.base.wires.energy_source_phase import EnergySourcePhase
from zepben.cimbend.cim.iec61970.base.wires.per_length import PerLengthSequenceImpedance
from zepben.cimbend.cim.iec61970.base.wires.power_transformer import *
__all__ = ["acls_to_plsi_resolver", "asset_to_asset_org_role_resolver", "asset_to_location_resolver", "pole_to_streetlight_resolver",
"streetlight_to_pole_resolver", "aux_equip_to_term_resolver", "cond_equip_to_bv_resolver", "cond_equip_to_terminal_resolver",
"conductor_to_wire_info_resolver", "conn_node_to_term_resolver", "control_to_remote_control_resolver", "cust_to_custagr_resolver",
"custagr_to_cust_resolver", "custagr_to_ps_resolver", "diag_to_diagobj_resolver", "diagobj_to_diag_resolver", "ed_to_up_resolver",
"ed_to_loc_resolver", "ec_to_ecp_resolver", "ecp_to_ec_resolver", "es_to_esp_resolver", "esp_to_es_resolver", "eq_to_curfeeder_resolver",
"eq_to_ec_resolver", "eq_to_or_resolver", "eq_to_up_resolver", "ec_to_eq_resolver", "curfeeder_to_eq_resolver", "feeder_to_nes_resolver",
"feeder_to_nht_resolver", "gr_to_sgr_resolver", "meas_to_rs_resolver", "or_to_eq_resolver", "orgr_to_org_resolver", "psr_to_loc_resolver",
"pt_to_pte_resolver", "pte_to_pt_resolver", "ps_to_tariff_resolver", "rtc_to_te_resolver", "rc_to_cont_resolver", "rs_to_meas_resolver",
"sgr_to_gr_resolver", "sgr_to_sub_resolver", "sub_to_feeder_resolver", "sub_to_sgr_resolver", "sub_to_circuit_resolver", "sub_to_eloop_resolver",
"sub_to_loop_resolver", "term_to_ce_resolver", "term_to_cn_resolver", "te_to_term_resolver", "te_to_bv_resolver", "te_to_rtc_resolver",
"up_to_ed_resolver", "up_to_eq_resolver", "up_to_loc_resolver", "circuit_to_loop_resolver", "circuit_to_sub_resolver", "circuit_to_term_resolver",
"loop_to_circuit_resolver", "loop_to_esub_resolver", "loop_to_sub_resolver", "BoundReferenceResolver", "ReferenceResolver", "UnresolvedReference"]
from zepben.cimbend.cim.iec61970.infiec61970.feeder import Circuit, Loop
@dataclass(frozen=True, eq=False, slots=True)
class ReferenceResolver(object):
from_class: type
to_class: type
resolve: Callable[[IdentifiedObject, IdentifiedObject], None]
def __eq__(self, other):
return self.from_class is other.from_class and self.to_class is other.to_class and self.resolve is other.resolve
def __neq__(self, other):
return self.from_class is not other.from_class or self.to_class is not other.to_class or self.resolve is not other.resolve
@dataclass(frozen=True, eq=False, slots=True)
class BoundReferenceResolver(object):
from_obj: IdentifiedObject
resolver: ReferenceResolver
reverse_resolver: Optional[ReferenceResolver]
def __eq__(self, other):
return self.from_obj is other.from_obj and self.resolver is other.resolver
def __neq__(self, other):
return self.from_obj is not other.from_obj or self.resolver is not other.resolver
@dataclass(frozen=True, eq=False, slots=True)
class UnresolvedReference(object):
from_ref: IdentifiedObject
to_mrid: str
resolver: ReferenceResolver
def _resolve_ce_term(ce, t):
t.conducting_equipment = ce
ce.add_terminal(t)
def _resolve_pt_pte(pt, pte):
pte.power_transformer = pt
pt.add_end(pte)
def _resolve_diag_diagobj(diag, diag_obj):
diag_obj.diagram = diag
diag.add_diagram_object(diag_obj)
acls_to_plsi_resolver = ReferenceResolver(AcLineSegment, PerLengthSequenceImpedance, lambda t, r: setattr(t, 'per_length_sequence_impedance', r))
asset_to_asset_org_role_resolver = ReferenceResolver(Asset, AssetOrganisationRole, lambda t, r: t.add_organisation_role(r))
asset_to_location_resolver = ReferenceResolver(Asset, Location, lambda t, r: setattr(t, 'location', r))
pole_to_streetlight_resolver = ReferenceResolver(Pole, Streetlight, lambda t, r: t.add_streetlight(r))
streetlight_to_pole_resolver = ReferenceResolver(Streetlight, Pole, lambda t, r: setattr(t, 'pole', r))
aux_equip_to_term_resolver = ReferenceResolver(AuxiliaryEquipment, Terminal, lambda t, r: setattr(t, 'terminal', r))
cond_equip_to_bv_resolver = ReferenceResolver(ConductingEquipment, BaseVoltage, lambda t, r: setattr(t, 'base_voltage', r))
cond_equip_to_terminal_resolver = ReferenceResolver(ConductingEquipment, Terminal, _resolve_ce_term)
conductor_to_wire_info_resolver = ReferenceResolver(Conductor, WireInfo, lambda t, r: setattr(t, 'asset_info', r))
conn_node_to_term_resolver = ReferenceResolver(ConnectivityNode, Terminal, lambda t, r: t.add_terminal(r))
control_to_remote_control_resolver = ReferenceResolver(Control, RemoteControl, lambda t, r: setattr(t, 'remote_control', r))
cust_to_custagr_resolver = ReferenceResolver(Customer, CustomerAgreement, lambda t, r: t.add_agreement(r))
custagr_to_cust_resolver = ReferenceResolver(CustomerAgreement, Customer, lambda t, r: setattr(t, 'customer', r))
custagr_to_ps_resolver = ReferenceResolver(CustomerAgreement, PricingStructure, lambda t, r: t.add_pricing_structure(r))
diag_to_diagobj_resolver = ReferenceResolver(Diagram, DiagramObject, _resolve_diag_diagobj)
diagobj_to_diag_resolver = ReferenceResolver(DiagramObject, Diagram, lambda t, r: setattr(t, 'diagram', r))
ed_to_up_resolver = ReferenceResolver(EndDevice, UsagePoint, lambda t, r: setattr(t, 'diagram', r))
ed_to_loc_resolver = ReferenceResolver(EndDevice, Location, lambda t, r: setattr(t, 'service_location', r))
ec_to_ecp_resolver = ReferenceResolver(EnergyConsumer, EnergyConsumerPhase, lambda t, r: t.add_phase(r))
ecp_to_ec_resolver = ReferenceResolver(EnergyConsumerPhase, EnergyConsumer, lambda t, r: setattr(t, 'energy_consumer', r))
es_to_esp_resolver = ReferenceResolver(EnergySource, EnergySourcePhase, lambda t, r: t.add_phase(r))
esp_to_es_resolver = ReferenceResolver(EnergySourcePhase, EnergySource, lambda t, r: setattr(t, 'energy_source', r))
eq_to_curfeeder_resolver = ReferenceResolver(Equipment, Feeder, lambda t, r: t.add_current_feeder(r))
eq_to_ec_resolver = ReferenceResolver(Equipment, EquipmentContainer, lambda t, r: t.add_container(r))
eq_to_or_resolver = ReferenceResolver(Equipment, OperationalRestriction, lambda t, r: t.add_restriction(r))
eq_to_up_resolver = ReferenceResolver(Equipment, UsagePoint, lambda t, r: t.add_usage_point(r))
ec_to_eq_resolver = ReferenceResolver(EquipmentContainer, Equipment, lambda t, r: t.add_equipment(r))
curfeeder_to_eq_resolver = ReferenceResolver(Feeder, Equipment, lambda t, r: t.add_equipment(r))
feeder_to_nes_resolver = ReferenceResolver(Feeder, Substation, lambda t, r: setattr(t, 'normal_energizing_substation', r))
feeder_to_nht_resolver = ReferenceResolver(Feeder, Terminal, lambda t, r: setattr(t, 'normal_head_terminal', r))
gr_to_sgr_resolver = ReferenceResolver(GeographicalRegion, SubGeographicalRegion, lambda t, r: t.add_sub_geographical_region(r))
meas_to_rs_resolver = ReferenceResolver(Measurement, RemoteSource, lambda t, r: setattr(t, 'remote_source', r))
or_to_eq_resolver = ReferenceResolver(OperationalRestriction, Equipment, lambda t, r: t.add_equipment(r))
orgr_to_org_resolver = ReferenceResolver(OrganisationRole, Organisation, lambda t, r: setattr(t, 'organisation', r))
psr_to_loc_resolver = ReferenceResolver(PowerSystemResource, Location, lambda t, r: setattr(t, 'location', r))
pt_to_pte_resolver = ReferenceResolver(PowerTransformer, PowerTransformerEnd, _resolve_pt_pte)
pte_to_pt_resolver = ReferenceResolver(PowerTransformerEnd, PowerTransformer, lambda t, r: setattr(t, 'power_transformer', r))
ps_to_tariff_resolver = ReferenceResolver(PricingStructure, Tariff, lambda t, r: t.tariff_to_cim(r))
rtc_to_te_resolver = ReferenceResolver(RatioTapChanger, PowerTransformerEnd, lambda t, r: setattr(t, 'transformer_end', r))
rc_to_cont_resolver = ReferenceResolver(RemoteControl, Control, lambda t, r: setattr(t, 'control', r))
rs_to_meas_resolver = ReferenceResolver(RemoteSource, Measurement, lambda t, r: setattr(t, 'measurement', r))
sgr_to_gr_resolver = ReferenceResolver(SubGeographicalRegion, GeographicalRegion, lambda t, r: setattr(t, 'geographical_region', r))
sgr_to_sub_resolver = ReferenceResolver(SubGeographicalRegion, Substation, lambda t, r: t.add_substation(r))
sub_to_feeder_resolver = ReferenceResolver(Substation, Feeder, lambda t, r: t.add_feeder(r))
sub_to_sgr_resolver = ReferenceResolver(Substation, SubGeographicalRegion, lambda t, r: setattr(t, 'sub_geographical_region', r))
sub_to_circuit_resolver = ReferenceResolver(Substation, Circuit, lambda t, r: t.add_circuit(r))
sub_to_loop_resolver = ReferenceResolver(Substation, Loop, lambda t, r: t.add_loop(r))
sub_to_eloop_resolver = ReferenceResolver(Substation, Loop, lambda t, r: t.add_energized_loop(r))
term_to_ce_resolver = ReferenceResolver(Terminal, ConductingEquipment, lambda t, r: setattr(t, 'conducting_equipment', r))
term_to_cn_resolver = ReferenceResolver(Terminal, ConnectivityNode, lambda t, r: setattr(t, 'connectivity_node', r))
te_to_term_resolver = ReferenceResolver(TransformerEnd, Terminal, lambda t, r: setattr(t, 'terminal', r))
te_to_bv_resolver = ReferenceResolver(TransformerEnd, BaseVoltage, lambda t, r: setattr(t, 'base_voltage', r))
te_to_rtc_resolver = ReferenceResolver(TransformerEnd, RatioTapChanger, lambda t, r: setattr(t, 'ratio_tap_changer', r))
up_to_ed_resolver = ReferenceResolver(UsagePoint, EndDevice, lambda t, r: t.add_end_device(r))
up_to_eq_resolver = ReferenceResolver(UsagePoint, Equipment, lambda t, r: t.add_equipment(r))
up_to_loc_resolver = ReferenceResolver(UsagePoint, Location, lambda t, r: setattr(t, 'usage_point_location', r))
circuit_to_term_resolver = ReferenceResolver(Circuit, Terminal, lambda t, r: t.add_terminal(r))
circuit_to_loop_resolver = ReferenceResolver(Circuit, Loop, lambda t, r: setattr(t, 'loop', r))
circuit_to_sub_resolver = ReferenceResolver(Circuit, Substation, lambda t, r: t.add_substation(r))
loop_to_circuit_resolver = ReferenceResolver(Loop, Circuit, lambda t, r: t.add_circuit(r))
loop_to_sub_resolver = ReferenceResolver(Loop, Substation, lambda t, r: t.add_substation(r))
loop_to_esub_resolver = ReferenceResolver(Loop, Substation, lambda t, r: t.add_energizing_substation(r)) | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/common/reference_resolvers.py | reference_resolvers.py |
from abc import ABCMeta
from typing import Optional
from dataclassy import dataclass
from zepben.cimbend.common.base_service import BaseService
from zepben.protobuf.cim.iec61970.base.core.IdentifiedObject_pb2 import IdentifiedObject as PBIdentifiedObject
from zepben.protobuf.cim.iec61968.common.Document_pb2 import Document as PBDocument
from zepben.cimbend.cim.iec61968.common.document import Document
from zepben.cimbend.cim.iec61968.common import Organisation
from zepben.cimbend.cim.iec61968.common.organisation_role import OrganisationRole
from zepben.protobuf.cim.iec61968.common.Organisation_pb2 import Organisation as PBOrganisation
from zepben.protobuf.cim.iec61968.common.OrganisationRole_pb2 import OrganisationRole as PBOrganisationRole
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
from zepben.cimbend.common import resolver
__all__ = ["identifiedobject_to_cim", "document_to_cim", "organisation_to_cim", "organisationrole_to_cim", "BaseProtoToCim"]
# IEC61970 CORE #
def identifiedobject_to_cim(pb: PBIdentifiedObject, cim: IdentifiedObject, service: BaseService):
cim.mrid = pb.mRID
cim.name = pb.name
cim.description = pb.description
# IEC61968 COMMON #
def document_to_cim(pb: PBDocument, cim: Document, service: BaseService):
cim.title = pb.title
cim.created_date_time = pb.createdDateTime.ToDatetime()
cim.author_name = pb.authorName
cim.type = pb.type
cim.status = pb.status
cim.comment = pb.comment
identifiedobject_to_cim(pb.io, cim, service)
def organisation_to_cim(pb: PBOrganisation, service: BaseService) -> Optional[Organisation]:
cim = Organisation()
identifiedobject_to_cim(pb.io, cim, service)
return cim if service.add(cim) else None
def organisationrole_to_cim(pb: PBOrganisationRole, cim: OrganisationRole, service: BaseService):
cim.organisation = service.resolve_or_defer_reference(resolver.organisation(cim), pb.organisationMRID)
identifiedobject_to_cim(pb.io, cim, service)
PBDocument.to_cim = document_to_cim
PBOrganisation.to_cim = organisation_to_cim
PBOrganisationRole.to_cim = organisationrole_to_cim
PBIdentifiedObject.to_cim = identifiedobject_to_cim
@dataclass(slots=True)
class BaseProtoToCim(object, metaclass=ABCMeta):
service: BaseService | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/common/translator/base_proto2cim.py | base_proto2cim.py |
from zepben.protobuf.cim.iec61970.base.core.IdentifiedObject_pb2 import IdentifiedObject as PBIdentifiedObject
from zepben.protobuf.cim.iec61968.common.Document_pb2 import Document as PBDocument
from zepben.cimbend.common.translator.util import mrid_or_empty
from zepben.cimbend.cim.iec61968.common.document import Document
from zepben.cimbend.cim.iec61968.common import Organisation
from zepben.cimbend.cim.iec61968.common.organisation_role import OrganisationRole
from zepben.protobuf.cim.iec61968.common.Organisation_pb2 import Organisation as PBOrganisation
from zepben.protobuf.cim.iec61968.common.OrganisationRole_pb2 import OrganisationRole as PBOrganisationRole
from zepben.cimbend.cim.iec61970.base.core.identified_object import IdentifiedObject
__all__ = ["identifiedobject_to_pb", "document_to_pb", "organisationrole_to_pb", "organisation_to_pb"]
# IEC61968 COMMON #
def document_to_pb(cim: Document) -> PBDocument:
return PBDocument(io=identifiedobject_to_pb(cim),
title=cim.title,
createdDateTime=cim.created_date_time.timestamp() if cim.created_date_time else None,
authorName=cim.author_name,
type=cim.type,
status=cim.status,
comment=cim.comment)
def organisation_to_pb(cim: Organisation) -> PBOrganisation:
return PBOrganisation(identifiedobject_to_pb(cim))
def organisationrole_to_pb(cim: OrganisationRole) -> PBOrganisationRole:
return PBOrganisationRole(io=identifiedobject_to_pb(cim),
organisationMRID=mrid_or_empty(cim.organisation.mrid))
# IEC61970 CORE #
def identifiedobject_to_pb(cim: IdentifiedObject) -> PBIdentifiedObject:
return PBIdentifiedObject(mRID=str(cim.mrid),
name=cim.name,
description=cim.description)
Document.to_pb = document_to_pb
Organisation.to_pb = organisation_to_pb
OrganisationRole.to_pb = organisationrole_to_pb
IdentifiedObject.to_pb = identifiedobject_to_pb | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/common/translator/base_cim2proto.py | base_cim2proto.py |
from __future__ import annotations
from collections import defaultdict
from dataclassy import dataclass
from zepben.cimbend.exceptions import PhaseException
from zepben.cimbend.model.phasedirection import PhaseDirection
from zepben.cimbend.cim.iec61970.base.wires import SinglePhaseKind, SINGLE_PHASE_KIND_VALUES
__all__ = ["phase", "direction", "pos_shift", "add", "setphs", "remove", "remove_all", "TracedPhases", "NominalPhasePath"]
CORE_MASKS = [0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000]
DIR_MASK = 0b11
PHASE_DIR_MAP = defaultdict(lambda: SinglePhaseKind.NONE)
PHASE_DIR_MAP[0b01] = SinglePhaseKind.A
PHASE_DIR_MAP[0b10] = SinglePhaseKind.A
PHASE_DIR_MAP[0b11] = SinglePhaseKind.A
PHASE_DIR_MAP[0b0100] = SinglePhaseKind.B
PHASE_DIR_MAP[0b1000] = SinglePhaseKind.B
PHASE_DIR_MAP[0b1100] = SinglePhaseKind.B
PHASE_DIR_MAP[0b010000] = SinglePhaseKind.C
PHASE_DIR_MAP[0b100000] = SinglePhaseKind.C
PHASE_DIR_MAP[0b110000] = SinglePhaseKind.C
PHASE_DIR_MAP[0b01000000] = SinglePhaseKind.N
PHASE_DIR_MAP[0b10000000] = SinglePhaseKind.N
PHASE_DIR_MAP[0b11000000] = SinglePhaseKind.N
def _valid_phase_check(nominal_phase):
if nominal_phase not in SINGLE_PHASE_KIND_VALUES[1:7]:
raise ValueError(f"INTERNAL ERROR: Phase {nominal_phase} is invalid. Must be one of {SINGLE_PHASE_KIND_VALUES[1:7]}.")
def phase(status: int, nominal_phase: SinglePhaseKind):
core_val = (status >> (nominal_phase.mask_index * 8)) & 0xff
return PHASE_DIR_MAP[core_val]
def direction(status: int, nominal_phase: SinglePhaseKind):
dir_val = (status >> pos_shift(phase(status, nominal_phase), nominal_phase)) & DIR_MASK
return PhaseDirection(dir_val)
def pos_shift(phs: SinglePhaseKind, nominal_phase: SinglePhaseKind):
return (2 * max(phs.value - 1, 0)) + (nominal_phase.mask_index * 8)
def setphs(status: int, phs: SinglePhaseKind, direction: PhaseDirection, nominal_phs: SinglePhaseKind) -> int:
return (status & ~CORE_MASKS[nominal_phs.mask_index]) | _shifted_value(direction, phs, nominal_phs)
def add(status: int, phs: SinglePhaseKind, direction: PhaseDirection, nominal_phs: SinglePhaseKind) -> int:
return status | _shifted_value(direction, phs, nominal_phs)
def remove_all(status: int, nominal_phase: SinglePhaseKind) -> int:
return status & ~CORE_MASKS[nominal_phase.mask_index]
def remove(status: int, phs: SinglePhaseKind, direction: PhaseDirection, nominal_phs: SinglePhaseKind) -> int:
return status & ~_shifted_value(direction, phs, nominal_phs)
def _shifted_value(pd: PhaseDirection, spk: SinglePhaseKind, nom: SinglePhaseKind) -> int:
return pd.value << pos_shift(spk, nom)
@dataclass(slots=True)
class NominalPhasePath(object):
"""
Defines how a nominal phase is wired through a connectivity node between two terminals
"""
from_phase: SinglePhaseKind
"""The nominal phase where the path comes from."""
to_phase: SinglePhaseKind
"""The nominal phase where the path goes to."""
@dataclass(slots=True)
class TracedPhases(object):
"""
Class that holds the traced phase statuses for the current and normal state of the network.
Each byte in an int is used to store all possible phases and directions for a core.
Each byte has 2 bits that represent the direction for a phase. If none of those bits are set the direction is equal to NONE.
Use the figures below as a reference.
<p>
PhaseStatus: | integer |
| byte | byte | byte | byte |
|Core 3|Core 2|Core 1|Core 0|
<p>
Core: | byte |
| 2bits | 2bits | 2bits | 2bits |
Phase: | N | C | B | A |
Direction: |OUT | IN |OUT | IN |OUT | IN |OUT | IN |
"""
_normal_status: int = 0
_current_status: int = 0
def __init__(self, normal_status: int = 0, current_status: int = 0):
self._normal_status = normal_status
self._current_status = current_status
def __str__(self):
s = []
for phs in (SinglePhaseKind.A, SinglePhaseKind.B, SinglePhaseKind.C, SinglePhaseKind.N):
pn = self.phase_normal(phs)
pc = self.phase_current(phs)
dn = self.direction_normal(phs)
dc = self.direction_current(phs)
s.append(f"phase {phs}: n: {pn.short_name}|{dn.short_name} c: {pc.short_name}|{dc.short_name}")
return ", ".join(s)
def phase_normal(self, nominal_phase: SinglePhaseKind):
"""
Get the normal (nominal) phase for a core.
`nominal_phase` The number of the core to check (between 0 - 4)
Returns `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` for the core
Raises `CoreException` if core is invalid.
"""
_valid_phase_check(nominal_phase)
return phase(self._normal_status, nominal_phase)
def phase_current(self, nominal_phase: SinglePhaseKind):
"""
Get the current (actual) phase for a core.
`nominal_phase` The number of the core to check (between 0 - 4)
Returns `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` for the core
"""
_valid_phase_check(nominal_phase)
return phase(self._current_status, nominal_phase)
def direction_normal(self, nominal_phase: SinglePhaseKind):
"""
Get the normal (nominal) direction for a core.
`nominal_phase` The number of the core to check (between 0 - 4)
Returns `zepben.phases.direction.Direction` for the core
"""
_valid_phase_check(nominal_phase)
return direction(self._normal_status, nominal_phase)
def direction_current(self, nominal_phase: SinglePhaseKind):
"""
Get the current (actual) direction for a core.
`nominal_phase` The number of the core to check (between 0 - 4)
Returns `zepben.phases.direction.Direction` for the core
"""
_valid_phase_check(nominal_phase)
return direction(self._current_status, nominal_phase)
def add_normal(self, phs: SinglePhaseKind, nominal_phase: SinglePhaseKind, dir_: PhaseDirection):
"""
Add a normal phase
`phs` The `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` to add.
`nominal_phase` The core number this phase should be applied to
`dir_` The direction of this phase relative to the location of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` to its feeder circuit breaker.
Returns True if phase status was changed, False otherwise.
Raises `zepben.phases.exceptions.PhaseException` if phases cross,
`zepben.phases.exceptions.CoreException` if `nominal_phase` is invalid.
"""
_valid_phase_check(nominal_phase)
if phs == SinglePhaseKind.NONE or dir_ == PhaseDirection.NONE:
return False
if self.phase_normal(nominal_phase) != SinglePhaseKind.NONE and phs != self.phase_normal(nominal_phase):
raise PhaseException("Crossing phases")
if self.direction_normal(nominal_phase).has(dir_):
return False
self._normal_status = add(self._normal_status, phs, dir_, nominal_phase)
return True
def add_current(self, phs: SinglePhaseKind, nominal_phase: SinglePhaseKind, dir_: PhaseDirection):
"""
Add a current phase
`phs` The `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` to add.
`nominal_phase` The core number this phase should be applied to
`dir_` The direction of this phase relative to the location of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` to its feeder circuit breaker.
Returns True if phase status was changed, False otherwise.
Raises `zepben.phases.exceptions.PhaseException` if phases cross
"""
_valid_phase_check(nominal_phase)
if phs == SinglePhaseKind.NONE or dir_ == PhaseDirection.NONE:
return False
if self.phase_current(nominal_phase) != SinglePhaseKind.NONE and phs != self.phase_current(nominal_phase):
raise PhaseException("Crossing phases")
if self.direction_current(nominal_phase).has(dir_):
return False
self._current_status = add(self._current_status, phs, dir_, nominal_phase)
return True
def set_normal(self, phs: SinglePhaseKind, nominal_phase: SinglePhaseKind, dir_: PhaseDirection):
"""
`phs` The `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` to add.
`nominal_phase` The core number this phase should be applied to
`dir_` The direction of this phase relative to the location of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` to its feeder circuit breaker.
Returns True if phase status was changed, False otherwise.
"""
_valid_phase_check(nominal_phase)
if phs == SinglePhaseKind.NONE or dir_ == PhaseDirection.NONE:
self.remove_normal(self.phase_normal(nominal_phase), nominal_phase)
return True
if self.phase_normal(nominal_phase) == phs and self.direction_normal(nominal_phase) == dir_:
return False
self._normal_status = setphs(self._normal_status, phs, dir_, nominal_phase)
return True
def set_current(self, phs: SinglePhaseKind, dir_: PhaseDirection, nominal_phase: SinglePhaseKind):
"""
`phs` The `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` to add.
`nominal_phase` The core number this phase should be applied to
`dir_` The direction of this phase relative to the location of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` to its feeder circuit breaker.
Returns True if phase status was changed, False otherwise.
"""
_valid_phase_check(nominal_phase)
if phs == SinglePhaseKind.NONE or dir_ == PhaseDirection.NONE:
self.remove_current(self.phase_current(nominal_phase), nominal_phase)
return True
if self.phase_current(nominal_phase) == phs and self.direction_current(nominal_phase) == dir_:
return False
self._current_status = setphs(self._current_status, phs, dir_, nominal_phase)
return True
def remove_normal(self, phs: SinglePhaseKind, nominal_phase: SinglePhaseKind, dir_: PhaseDirection = None):
"""
`phs` The `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` to add.
`nominal_phase` The core number this phase should be applied to
`dir_` The direction of this phase relative to the location of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` to its feeder circuit breaker.
Returns True if phase status was changed, False otherwise.
"""
_valid_phase_check(nominal_phase)
if phs != self.phase_normal(nominal_phase):
return False
if dir_ is not None:
if not self.direction_normal(nominal_phase).has(dir_):
return False
self._normal_status = remove(self._normal_status, phs, dir_, nominal_phase)
else:
self._normal_status = remove_all(self._normal_status, nominal_phase)
return True
def remove_current(self, phs: SinglePhaseKind, nominal_phase: SinglePhaseKind, dir_: PhaseDirection = None):
"""
`phs` The `zepben.protobuf.cim.iec61970.base.wires.SinglePhaseKind` to add.
`nominal_phase` The core number this phase should be applied to
`dir_` The direction of this phase relative to the location of the `zepben.cimbend.iec61970.base.core.terminal.Terminal` to its feeder circuit breaker.
Returns True if phase status was changed, False otherwise.
"""
_valid_phase_check(nominal_phase)
if phs != self.phase_current(nominal_phase):
return False
if dir_ is not None:
if not self.direction_current(nominal_phase).has(dir_):
return False
self._current_status = remove(self._current_status, phs, dir_, nominal_phase)
else:
self._current_status = remove_all(self._current_status, nominal_phase)
return True
def copy(self):
return TracedPhases() | zepben.cimbend | /zepben.cimbend-0.16.0b1.tar.gz/zepben.cimbend-0.16.0b1/src/zepben/cimbend/model/phases.py | phases.py |
import json
import ssl
import warnings
from asyncio import get_event_loop
from hashlib import sha256
from typing import Optional
import aiohttp
from aiohttp import ClientSession
from urllib3.exceptions import InsecureRequestWarning
from zepben.auth import AuthMethod, ZepbenTokenFetcher, create_token_fetcher
from zepben.eas.client.study import Study
from zepben.eas.client.util import construct_url
from zepben.eas.client.work_package import WorkPackageConfig
__all__ = ["EasClient"]
class EasClient:
"""
A class used to represent a client to the Evolve App Server, with methods that represent requests to its API.
"""
def __init__(
self,
host: str,
port: int,
protocol: str = "https",
client_id: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
client_secret: Optional[str] = None,
token_fetcher: Optional[ZepbenTokenFetcher] = None,
verify_certificate: bool = True,
ca_filename: Optional[str] = None,
session: ClientSession = None,
json_serialiser=None
):
"""
Construct a client for the Evolve App Server. If the server is HTTPS, authentication may be configured.
Authentication may be configured in one of two ways:
- Specifying the client ID of the Auth0 application via the client_id parameter, plus one of the following:
- A username and password pair via the username and password parameters (account authentication)
- The client secret via the client_secret parameter (M2M authentication)
If this method is used, the auth configuration will be fetched from the Evolve App Server at the path
"/api/config/auth".
- Specifying a ZepbenTokenFetcher directly via the token_fetcher parameter
Address parameters:
:param host: The domain of the Evolve App Server, e.g. "evolve.local"
:param port: The port on which to make requests to the Evolve App Server, e.g. 7624
:param protocol: The protocol of the Evolve App Server. Should be either "http" or "https". Must be "https" if
auth is configured. (Defaults to "https")
Authentication parameters:
:param client_id: The Auth0 client ID used to specify to the auth server which application to request a token
for. (Optional)
:param username: The username used for account authentication. (Optional)
:param password: The password used for account authentication. (Optional)
:param client_secret: The Auth0 client secret used for M2M authentication. (Optional)
:param token_fetcher: A ZepbenTokenFetcher used to fetch auth tokens for access to the Evolve App Server.
(Optional)
HTTP/HTTPS parameters:
:param verify_certificate: Set this to False to disable certificate verification. This will also apply to the
auth provider if auth is initialised via client id + username + password or
client_id + client_secret. (Defaults to True)
:param ca_filename: Path to CA file to use for verification. (Optional)
:param session: aiohttp ClientSession to use, if not provided a new session will be created for you. You should
typically only use one aiohttp session per application.
:param json_serialiser: JSON serialiser to use for requests e.g. ujson.dumps. (Defaults to json.dumps)
"""
self._protocol = protocol
self._host = host
self._port = port
self._verify_certificate = verify_certificate
self._ca_filename = ca_filename
if protocol != "https" and (token_fetcher or client_id):
raise ValueError(
"Incompatible arguments passed to connect to secured Evolve App Server. "
"Authentication tokens must be sent via https. "
"To resolve this issue, exclude the \"protocol\" argument when initialising the EasClient.")
if token_fetcher and (client_id or client_secret or username or password):
raise ValueError(
"Incompatible arguments passed to connect to secured Evolve App Server. "
"You cannot provide both a token_fetcher and credentials, "
"please provide either client_id + client_secret, username + password, or token_fetcher."
)
if client_secret and (username or password):
raise ValueError(
"Incompatible arguments passed to connect to secured Evolve App Server. "
"You cannot provide both a client_secret and username/password, "
"please provide either client_id + client_secret or client_id + username + password."
)
if client_id:
self._token_fetcher = create_token_fetcher(
conf_address=f"{self._protocol}://{self._host}:{self._port}/api/config/auth",
verify_conf=self._verify_certificate,
auth_type_field="configType",
audience_field="audience",
issuer_domain_field="issuerDomain"
)
if self._token_fetcher:
self._token_fetcher.token_request_data.update({
'client_id': client_id,
'scope':
'trusted' if self._token_fetcher.auth_method is AuthMethod.SELF
else 'offline_access openid profile email0'
})
self._token_fetcher.refresh_request_data.update({
"grant_type": "refresh_token",
'client_id': client_id,
'scope':
'trusted' if self._token_fetcher.auth_method is AuthMethod.SELF
else 'offline_access openid profile email0'
})
if username and password:
self._token_fetcher.token_request_data.update({
'grant_type': 'password',
'username': username,
'password':
sha256(password.encode('utf-8')).hexdigest()
if self._token_fetcher.auth_method is AuthMethod.SELF
else password
})
if client_secret:
self._token_fetcher.token_request_data.update({'client_secret': client_secret})
elif client_secret:
self._token_fetcher.token_request_data.update({
'grant_type': 'client_credentials',
'client_secret': client_secret
})
else:
raise ValueError(
"Incompatible arguments passed to connect to secured Evolve App Server. "
"You must specify at least (username, password) or (client_secret) for a secure connection "
"with token based auth.")
elif token_fetcher:
self._token_fetcher = token_fetcher
else:
self._token_fetcher = None
if session is None:
conn = aiohttp.TCPConnector(limit=200, limit_per_host=0)
timeout = aiohttp.ClientTimeout(total=60)
self.session = aiohttp.ClientSession(json_serialize=json_serialiser or json.dumps, connector=conn,
timeout=timeout)
else:
self.session = session
def close(self):
return get_event_loop().run_until_complete(self.aclose())
async def aclose(self):
await self.session.close()
def _get_request_headers(self, content_type: str = "application/json") -> dict:
headers = {"content-type": content_type}
if self._token_fetcher is None:
return headers
else:
headers["authorization"] = self._token_fetcher.fetch_token()
return headers
def run_hosting_capacity_work_package(self, work_package: WorkPackageConfig):
"""
Send request to hosting capacity service to run work package
:param work_package: An instance of the `WorkPackageConfig` data class representing the work package configuration for the run
:return: The HTTP response received from the Evolve App Server after attempting to run work package
"""
return get_event_loop().run_until_complete(self.async_run_hosting_capacity_work_package(work_package))
async def async_run_hosting_capacity_work_package(self, work_package: WorkPackageConfig):
"""
Send asynchronous request to hosting capacity service to run work package
:param work_package: An instance of the `WorkPackageConfig` data class representing the work package configuration for the run
:return: The HTTP response received from the Evolve App Server after attempting to run work package
"""
with warnings.catch_warnings():
if not self._verify_certificate:
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
json = {
"query": """
mutation runHostingCapacity($input: WorkPackageInput!) {
runHostingCapacity(input: $input)
}
""",
"variables": {
"input": {
"feeders": work_package.feeders,
"years": work_package.years,
"scenarios": work_package.scenarios,
"modelConfig": {
"vmPu": work_package.modelConfig.vmPu if work_package.modelConfig.vmPu is not None else None,
"vMinPu": work_package.modelConfig.vMinPu if work_package.modelConfig.vMinPu is not None else None,
"vMaxPu": work_package.modelConfig.vMaxPu if work_package.modelConfig.vMaxPu is not None else None,
"loadModel": work_package.modelConfig.loadModel if work_package.modelConfig.loadModel is not None else None,
"collapseSWER": work_package.modelConfig.collapseSWER if work_package.modelConfig.collapseSWER is not None else None,
"meterAtHVSource": work_package.modelConfig.meterAtHVSource if work_package.modelConfig.meterAtHVSource is not None else None,
"metersAtDistTransformers": work_package.modelConfig.metersAtDistTransformers if work_package.modelConfig.metersAtDistTransformers is not None else None,
"switchMeterPlacementConfigs": [{
"meterSwitchClass": spc.meterSwitchClass.name if spc.meterSwitchClass is not None else None,
"namePattern": spc.namePattern if spc.namePattern is not None else None,
} for spc in
work_package.modelConfig.switchMeterPlacementConfigs] if work_package.modelConfig.switchMeterPlacementConfigs is not None else None,
} if work_package.modelConfig is not None else None,
"solveConfig": {
"normVMinPu": work_package.solveConfig.normVMinPu if work_package.solveConfig.normVMinPu is not None else None,
"normVMaxPu": work_package.solveConfig.normVMaxPu if work_package.solveConfig.normVMaxPu is not None else None,
"emergVMinPu": work_package.solveConfig.emergVMinPu if work_package.solveConfig.emergVMinPu is not None else None,
"emergVMaxPu": work_package.solveConfig.emergVMaxPu if work_package.solveConfig.emergVMaxPu is not None else None,
"baseFrequency": work_package.solveConfig.baseFrequency if work_package.solveConfig.baseFrequency is not None else None,
"voltageBases": work_package.solveConfig.voltageBases if work_package.solveConfig.voltageBases is not None else None,
"maxIter": work_package.solveConfig.maxIter if work_package.solveConfig.maxIter is not None else None,
"maxControlIter": work_package.solveConfig.maxControlIter if work_package.solveConfig.maxControlIter is not None else None,
"mode": work_package.solveConfig.mode.name if work_package.solveConfig.mode is not None else None,
"stepSizeMinutes": work_package.solveConfig.stepSizeMinutes if work_package.solveConfig.stepSizeMinutes is not None else None,
} if work_package.solveConfig is not None else None,
"resultsDetailLevel": work_package.resultsDetailLevel.name if work_package.resultsDetailLevel is not None else None,
"qualityAssuranceProcessing": work_package.qualityAssuranceProcessing if work_package.qualityAssuranceProcessing is not None else None
}
}
}
if self._verify_certificate:
sslcontext = ssl.create_default_context(cafile=self._ca_filename)
async with self.session.post(
construct_url(protocol=self._protocol, host=self._host, port=self._port, path="/api/graphql"),
headers=self._get_request_headers(),
json=json,
ssl=sslcontext if self._verify_certificate else False
) as response:
if response.ok:
response = await response.json()
else:
response = await response.text()
return response
def upload_study(self, study: Study):
"""
Uploads a new study to the Evolve App Server
:param study: An instance of a data class representing a new study
"""
return get_event_loop().run_until_complete(self.async_upload_study(study))
async def async_upload_study(self, study: Study):
"""
Uploads a new study to the Evolve App Server
:param study: An instance of a data class representing a new study
:return: The HTTP response received from the Evolve App Server after attempting to upload the study
"""
with warnings.catch_warnings():
if not self._verify_certificate:
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
json = {
"query": """
mutation uploadStudy($study: StudyInput!) {
addStudies(studies: [$study])
}
""",
"variables": {
"study": {
"name": study.name,
"description": study.description,
"tags": study.tags,
"styles": study.styles,
"results": [{
"name": result.name,
"geoJsonOverlay": {
"data": result.geo_json_overlay.data,
"sourceProperties": result.geo_json_overlay.source_properties,
"styles": result.geo_json_overlay.styles
} if result.geo_json_overlay else None,
"stateOverlay": {
"data": result.state_overlay.data,
"styles": result.state_overlay.styles
} if result.state_overlay else None,
"sections": [{
"type": section.type,
"name": section.name,
"description": section.description,
"columns": section.columns,
"data": section.data
} for section in result.sections]
} for result in study.results]
}
}
}
if self._verify_certificate:
sslcontext = ssl.create_default_context(cafile=self._ca_filename)
async with self.session.post(
construct_url(protocol=self._protocol, host=self._host, port=self._port, path="/api/graphql"),
headers=self._get_request_headers(),
json=json,
ssl=sslcontext if self._verify_certificate else False
) as response:
if response.ok:
response = await response.json()
else:
response = await response.text()
return response | zepben.eas | /zepben.eas-0.12.0b1-py3-none-any.whl/zepben/eas/client/eas_client.py | eas_client.py |
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
__all__ = ["WorkPackageConfig",
"SwitchClass",
"SwitchMeterPlacementConfig",
"ModelConfig",
"SolveMode",
"SolveConfig",
"ResultsDetailLevel"]
class SwitchClass(Enum):
BREAKER = "BREAKER",
DISCONNECTOR = "DISCONNECTOR",
FUSE = "FUSE",
JUMPER = "JUMPER",
LOAD_BREAK_SWITCH = "LOAD_BREAK_SWITCH",
RECLOSER = "RECLOSER"
@dataclass
class SwitchMeterPlacementConfig:
meterSwitchClass: Optional[SwitchClass] = None
namePattern: Optional[str] = None
@dataclass
class ModelConfig:
vmPu: Optional[float] = None
vMinPu: Optional[float] = None
vMaxPu: Optional[float] = None
loadModel: Optional[int] = None
collapseSWER: Optional[bool] = None
meterAtHVSource: Optional[bool] = None
metersAtDistTransformers: Optional[bool] = None
switchMeterPlacementConfigs: Optional[List[SwitchMeterPlacementConfig]] = None
class SolveMode(Enum):
YEARLY = "YEARLY"
DAILY = "DAILY"
@dataclass
class SolveConfig:
normVMinPu: Optional[float] = None
normVMaxPu: Optional[float] = None
emergVMinPu: Optional[float] = None
emergVMaxPu: Optional[float] = None
baseFrequency: Optional[int] = None
voltageBases: Optional[List[float]] = None
maxIter: Optional[int] = None
maxControlIter: Optional[int] = None
mode: Optional[SolveMode] = None
stepSizeMinutes: Optional[float] = None
class ResultsDetailLevel(Enum):
STANDARD = "STANDARD"
BASIC = "BASIC"
EXTENDED = "EXTENDED"
RAW = "RAW"
@dataclass
class WorkPackageConfig:
""" A data class representing the configuration for a hosting capacity work package """
feeders: List[str]
years: List[int]
scenarios: List[str]
modelConfig: Optional[ModelConfig] = None
solveConfig: Optional[SolveConfig] = None
resultsDetailLevel: Optional[ResultsDetailLevel] = None
qualityAssuranceProcessing: Optional[bool] = None | zepben.eas | /zepben.eas-0.12.0b1-py3-none-any.whl/zepben/eas/client/work_package.py | work_package.py |
from dataclasses import dataclass
from typing import List
__all__ = ["TRANSFORMER_CATALOGUE"]
@dataclass
class XfmrCode:
name: str
phases: int
windings: int
kvas: List[int]
kvs: List[float]
xhl: float
load_loss: float
conns: List[str]
tap: float
TRANSFORMER_CATALOGUE: List[XfmrCode] = [
XfmrCode(name='E_16KVA_11KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[16, 16], kvs=[11, 22], xhl=3.3,
load_loss=1.513, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_11KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[16, 16], kvs=[11, 0.433], xhl=3.3,
load_loss=1.513, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[16, 16], kvs=[22, 11], xhl=3.3,
load_loss=1.288, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_22KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[16, 16], kvs=[22, 22], xhl=3.3,
load_loss=1.288, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_22KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[16, 16], kvs=[22, 0.433], xhl=3.3,
load_loss=1.288, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_33KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[16, 16], kvs=[33, 22], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[16, 16], kvs=[33, 33], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_33KV_19.1kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[16, 16], kvs=[33, 33], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_33KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[16, 16], kvs=[33, 0.433], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_6.6KV_250V_1PH_POLEMED', phases=1, windings=2, kvas=[16, 16], kvs=[6.6, 0.5], xhl=3.3,
load_loss=1.513, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_16KVA_6.6KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[16, 16], kvs=[6.6, 0.433], xhl=3.3,
load_loss=1.513, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_11KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[11, 0.5], xhl=3.3,
load_loss=1.513, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_11KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[11, 0.5], xhl=3.3,
load_loss=1.513, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_12.7KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[22, 0.5], xhl=3.3,
load_loss=1.288, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_22KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[22, 0.5], xhl=3.3,
load_loss=1.288, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_33KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[33, 0.5], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_33KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[33, 0.5], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_9.1KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[33, 0.5], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_16KVA_9.1KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[16, 16], kvs=[33, 0.5], xhl=3.3,
load_loss=1.281, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_11KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[25, 25], kvs=[11, 22], xhl=3.3,
load_loss=1.912, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_22KV__11kV_HV1_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[25, 25], kvs=[22, 11],
xhl=3.3, load_loss=1.552, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_22KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[25, 25], kvs=[22, 22], xhl=3.3,
load_loss=1.552, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_22KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[25, 25], kvs=[22, 33], xhl=3.3,
load_loss=1.552, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[25, 25], kvs=[33, 33], xhl=3.3,
load_loss=1.44, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_33KV_19.1kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[25, 25], kvs=[33, 33], xhl=3.3,
load_loss=1.44, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_25KVA_6.6KV_433V_3PH_PAD_MOUNT', phases=3, windings=2, kvas=[25, 25], kvs=[6.6, 0.433], xhl=3.3,
load_loss=1.912, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_11KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[11, 0.5], xhl=3.3,
load_loss=1.324, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_11KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[11, 0.5], xhl=3.3,
load_loss=1.324, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_11KV_433V_3PH_PAD_MOUNT_Tyree', phases=3, windings=2, kvas=[25, 25], kvs=[11, 0.433],
xhl=3.3, load_loss=1.912, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_11KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[25, 25], kvs=[11, 0.433], xhl=3.3,
load_loss=1.912, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_12.7KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[22, 0.5], xhl=3.3,
load_loss=1.272, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_22KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[22, 0.5], xhl=3.3,
load_loss=1.272, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_22KV_433V_3PH_PAD_MOUNT_Tyree', phases=3, windings=2, kvas=[25, 25], kvs=[22, 0.433],
xhl=3.3, load_loss=1.552, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_22KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[25, 25], kvs=[22, 0.433], xhl=3.3,
load_loss=1.552, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_33KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[33, 0.5], xhl=3.3,
load_loss=1.376, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_33KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[33, 0.5], xhl=3.3,
load_loss=1.376, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_33KV_433V_3PH_PAD_MOUNT_Tyree', phases=3, windings=2, kvas=[25, 25], kvs=[33, 0.433],
xhl=3.3, load_loss=1.44, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_33KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[25, 25], kvs=[33, 0.433], xhl=3.3,
load_loss=1.44, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_9.1KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[33, 0.5], xhl=3.3,
load_loss=1.376, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_25KVA_9.1KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[25, 25], kvs=[33, 0.5], xhl=3.3,
load_loss=1.376, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA 3.3KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[3.3, 33], xhl=3.3,
load_loss=0.9, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_11KV_19.1kV_HV1 Iso_TXo POLE', phases=1, windings=2, kvas=[50, 50], kvs=[11, 33], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[11, 33], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_11KV_6.35kV_HV1 Iso_TXo POLE', phases=1, windings=2, kvas=[50, 50], kvs=[11, 11], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_22KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[22, 22], xhl=3.14,
load_loss=1.34, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_22KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[22, 33], xhl=3.14,
load_loss=1.34, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_22KV_19.1kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[22, 33], xhl=3.14,
load_loss=1.34, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_33KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[33, 22], xhl=2.26,
load_loss=1.1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[33, 33], xhl=2.26,
load_loss=1.1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_33KV_6.6kV_HV1 Step_Down_Tx_PAD', phases=3, windings=2, kvas=[50, 50], kvs=[33, 6.6],
xhl=2.26, load_loss=1.1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_6.6KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[50, 50], kvs=[6.6, 33], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_6.6KV_250V_1PH_POLEMED', phases=1, windings=2, kvas=[50, 50], kvs=[6.6, 0.5], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_50KVA_6.6KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[50, 50], kvs=[6.6, 0.433], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA 6.35KV_250V SWER PADMOUNT_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[11, 0.5],
xhl=3.3, load_loss=0.884, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_11KV_12.7kV_HV1_Iso_Tx_POLE_Wilson', phases=1, windings=2, kvas=[50, 50], kvs=[11, 22],
xhl=3.3, load_loss=0.9, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_11KV_250V_1PH_PAD_MED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[11, 0.5], xhl=3.3,
load_loss=0.884, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_11KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[11, 0.5], xhl=3.3,
load_loss=0.884, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_11KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[50, 50], kvs=[11, 0.433], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_11KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[50, 50], kvs=[11, 0.433], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_12.7KV_250V SWER PAD MED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[22, 0.5], xhl=3.3,
load_loss=0.836, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_12.7KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[22, 0.5], xhl=3.3,
load_loss=0.836, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_22KV_250V_1PH_PAD_MED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[22, 0.5], xhl=3.3,
load_loss=0.836, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_22KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[22, 0.5], xhl=3.3,
load_loss=0.836, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_22KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[50, 50], kvs=[22, 0.433],
xhl=3.14, load_loss=1.34, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_22KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[50, 50], kvs=[22, 0.433], xhl=3.14,
load_loss=1.34, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_33KV_250V_1PH_POLEMED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[33, 0.5], xhl=3.3,
load_loss=0.91, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_33KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[50, 50], kvs=[33, 0.433],
xhl=2.26, load_loss=1.1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_33KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[50, 50], kvs=[33, 0.433], xhl=2.26,
load_loss=1.1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_9.1KV_250V SWER PAD MED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[33, 0.5], xhl=3.3,
load_loss=0.91, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_50KVA_9.1KV_250V_SWER_POLEMED_Tyree', phases=1, windings=2, kvas=[50, 50], kvs=[33, 0.5], xhl=3.3,
load_loss=0.91, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_55KVA_11kV_Vol Reg,_1PH_POLEMED', phases=1, windings=2, kvas=[55, 55], kvs=[11, 11], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_11KV_250V_1PH_POLEMED', phases=1, windings=2, kvas=[63, 63], kvs=[11, 0.5], xhl=3.3,
load_loss=1.657, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_11KV_250V_SWER_POLEMED', phases=1, windings=2, kvas=[63, 63], kvs=[11, 0.5], xhl=3.3,
load_loss=1.657, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_11KV_250V_SWER_POLEMED', phases=1, windings=2, kvas=[63, 63], kvs=[33, 0.5], xhl=3.3,
load_loss=1.927, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_22KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[63, 63], kvs=[22, 33], xhl=3.3,
load_loss=1.551, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_22KV_250V_1PH_POLEMED', phases=1, windings=2, kvas=[63, 63], kvs=[22, 0.5], xhl=3.3,
load_loss=1.551, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[63, 63], kvs=[33, 33], xhl=3.3,
load_loss=1.927, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_33KV_250V_1PH_POLEMED', phases=1, windings=2, kvas=[63, 63], kvs=[33, 0.5], xhl=3.3,
load_loss=1.927, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_63KVA_6.6KV_433V_3PH_PADMOUNT', phases=3, windings=2, kvas=[63, 63], kvs=[6.6, 0.433], xhl=3.6,
load_loss=1.52, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_63KVA_11KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[63, 63], kvs=[11, 0.433], xhl=3.3,
load_loss=1.657, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_63KVA_11KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[63, 63], kvs=[11, 0.433], xhl=3.3,
load_loss=1.657, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_63KVA_22KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[63, 63], kvs=[22, 0.433], xhl=3.3,
load_loss=1.551, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_63KVA_22KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[63, 63], kvs=[22, 0.433], xhl=3.3,
load_loss=1.551, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_63KVA_33KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[63, 63], kvs=[33, 0.433], xhl=3.3,
load_loss=1.927, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_63KVA_33KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[63, 63], kvs=[33, 0.433], xhl=3.3,
load_loss=1.927, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[100, 100], kvs=[11, 33], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[100, 100], kvs=[11, 33], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_250V_1PH_POLE_MOUNT', phases=1, windings=2, kvas=[100, 100], kvs=[11, 0.5], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_33kV__Step_Up_Txs_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[11, 33], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_6.35kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[100, 100], kvs=[11, 11], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_6.35kV_SWER_Iso_Tx_PAD', phases=1, windings=2, kvas=[100, 100], kvs=[11, 11], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_11KV_6.35kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[100, 100], kvs=[11, 11], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_12.7KV_250V_SWER_POLEMED', phases=1, windings=2, kvas=[100, 100], kvs=[22, 0.5], xhl=4.1,
load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_22KV__11kV_HV1_Step_Down_Tx_DDN0_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[22, 11],
xhl=4.1, load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_22KV__11kV_HV1_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[22, 11],
xhl=4.1, load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[22, 11], xhl=4.1,
load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[22, 11], xhl=4.1,
load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_22KV_250V_1PH_POLEMED', phases=1, windings=2, kvas=[100, 100], kvs=[22, 0.5], xhl=4.1,
load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_33KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[33, 11],
xhl=4.36, load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_33KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[100, 100], kvs=[33, 22], xhl=4.36,
load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_33KV_22kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[33, 22], xhl=4.36,
load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_6.6KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[100, 100], kvs=[6.6, 0.433], xhl=4,
load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_100KVA_66KV_33kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[100, 100], kvs=[66, 33], xhl=3.7,
load_loss=1.199, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_11KV_12.7kV_HV1_Iso_Tx_PAD_Tyree', phases=1, windings=2, kvas=[100, 100], kvs=[11, 22],
xhl=4, load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_11KV_12.7kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[100, 100], kvs=[11, 22],
xhl=4, load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_11KV_22kV_Step_Up_Tx_Pole_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[11, 22],
xhl=4, load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_11KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[11, 0.433],
xhl=4.09, load_loss=1.011, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_11KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[11, 0.433],
xhl=4.09, load_loss=1.011, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_22KV_12.7kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[100, 100], kvs=[22, 22],
xhl=4, load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_22KV_12.7kV_SWER_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[100, 100], kvs=[22, 22],
xhl=4, load_loss=1.4, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_22KV_19.1kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[100, 100], kvs=[22, 33],
xhl=4, load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_22KV_33kV_Step_Up_Tx_Pole_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[22, 33],
xhl=4, load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_22KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[22, 0.433],
xhl=4.1, load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_22KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[22, 0.433],
xhl=4.1, load_loss=1.381, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_33KV_19.1kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[100, 100], kvs=[33, 33],
xhl=4, load_loss=1.3, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_33KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[33, 0.433],
xhl=4.36, load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_100KVA_33KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[100, 100], kvs=[33, 0.433],
xhl=4.36, load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_11KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[200, 200], kvs=[11, 22], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[200, 200], kvs=[11, 33], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_11KV_22kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[200, 200], kvs=[11, 22], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_11KV_6.35kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[200, 200], kvs=[11, 11], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_11KV19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[200, 200], kvs=[11, 33], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_22KV__11kV_1PH Step_Down_Tx_PAD', phases=3, windings=2, kvas=[200, 200], kvs=[22, 11],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_22KV__11kV_3PH Step_Down_Tx_PAD', phases=3, windings=2, kvas=[200, 200], kvs=[22, 11],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_22KV__11kV_HV1_Step_Down_Tx_DDN0_POLE', phases=3, windings=2, kvas=[200, 200], kvs=[22, 11],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_22KV__11kV_HV1_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[200, 200], kvs=[22, 11],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[200, 200], kvs=[22, 11],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_33KV_19.1kV_HV1_Iso_Tx_YN0_POLE', phases=1, windings=2, kvas=[200, 200], kvs=[33, 33],
xhl=4, load_loss=0.9, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_200KVA_6.6KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[200, 200], kvs=[6.6, 0.433], xhl=3.97,
load_loss=1.12, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_11KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[200, 200], kvs=[11, 0.433],
xhl=4.21, load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_11KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[200, 200], kvs=[11, 0.433],
xhl=4.21, load_loss=0.976, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_12.7kV_HV1_Iso_Tx_PAD_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[22, 22],
xhl=4, load_loss=0.75, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_12.7kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[22, 22],
xhl=4, load_loss=0.75, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_12.7kV_SWER_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[22, 22],
xhl=4, load_loss=0.75, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_19.1kV_HV1_Iso_Tx_PAD_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[22, 33],
xhl=4, load_loss=0.85, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_19.1kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[22, 33],
xhl=4, load_loss=0.85, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_19.1kV_SWER_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[22, 33],
xhl=4, load_loss=0.85, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[200, 200], kvs=[22, 0.433],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_22KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[200, 200], kvs=[22, 0.433],
xhl=3.93, load_loss=0.864, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_33KV_12.7kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[33, 22],
xhl=4, load_loss=0.9, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_33KV_19.1kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[33, 33],
xhl=4, load_loss=0.9, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_33KV_19.1kV_SWER_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[200, 200], kvs=[33, 33],
xhl=4, load_loss=0.9, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_33KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[200, 200], kvs=[33, 0.433],
xhl=3.81, load_loss=0.706, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_200KVA_33KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[200, 200], kvs=[33, 0.433],
xhl=3.81, load_loss=0.706, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_11KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[250, 250], kvs=[11, 22], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[250, 250], kvs=[11, 33], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[250, 250], kvs=[11, 33], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_11KV_22kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[250, 250], kvs=[11, 22], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_11KV_33kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[250, 250], kvs=[11, 33], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_11KV_6.35kV_HV1_Iso_Tx_PAD', phases=1, windings=2, kvas=[250, 250], kvs=[11, 11], xhl=4.21,
load_loss=0.975, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[250, 250], kvs=[22, 11], xhl=4,
load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_22KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[250, 250], kvs=[22, 22], xhl=4,
load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_33KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[250, 250], kvs=[33, 11], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_33KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[250, 250], kvs=[33, 22], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_33KV_22kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[250, 250], kvs=[33, 22], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_250KVA_66KV_33kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[250, 250], kvs=[66, 33], xhl=5.2,
load_loss=1.001, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_250KVA_22KV_19.1kV_HV1_Iso_Tx_PAD_Tyree', phases=1, windings=2, kvas=[250, 250], kvs=[22, 33],
xhl=4, load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_250KVA_22KV_19.1kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[250, 250], kvs=[22, 33],
xhl=4, load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_250KVA_22KV_33kV_Step_Up_Tx_Pole_Tyree', phases=3, windings=2, kvas=[250, 250], kvs=[22, 33],
xhl=4, load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_250KVA_33KV_19.1kV_HV1_Iso_Tx_PAD_Tyree', phases=1, windings=2, kvas=[250, 250], kvs=[33, 33],
xhl=4, load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_250KVA_33KV_19.1kV_HV1_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[250, 250], kvs=[33, 33],
xhl=4, load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_250KVA_33KV_19.1kV_SWER_Iso_Tx_POLE_Tyree', phases=1, windings=2, kvas=[250, 250], kvs=[33, 33],
xhl=4, load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_11KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[11, 22], xhl=4.1,
load_loss=1.235, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[11, 33], xhl=4.1,
load_loss=1.235, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_11KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[11, 33], xhl=4.1,
load_loss=1.235, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[300, 300], kvs=[22, 11], xhl=4,
load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_22KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[22, 22], xhl=4,
load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_22KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[22, 33], xhl=4,
load_loss=0.92, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_33KV_12.7kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[33, 22], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[33, 33], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_33KV_19.1kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[33, 33], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_300KVA_33KV_19.1kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[300, 300], kvs=[33, 33], xhl=4,
load_loss=1, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_315KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[315, 315], kvs=[22, 11], xhl=4,
load_loss=0.857, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_315KVA_33KV_19.1kV_HV1_Iso_Tx_YN0_POLE', phases=1, windings=2, kvas=[315, 315], kvs=[33, 33],
xhl=4, load_loss=0.857, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_315KVA_6.6KV_433V_3PH_PADMOUNT', phases=3, windings=2, kvas=[315, 315], kvs=[6.6, 0.433], xhl=4,
load_loss=0.921, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_315KVA_6.6KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[315, 315], kvs=[6.6, 0.433], xhl=4,
load_loss=0.921, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_315KVA_11KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[315, 315], kvs=[11, 0.433],
xhl=4, load_loss=0.921, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_315KVA_11KV_433V_3PH_POLEMED_Wilson', phases=3, windings=2, kvas=[315, 315], kvs=[11, 0.433],
xhl=4, load_loss=0.921, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_315KVA_22KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[315, 315], kvs=[22, 0.433],
xhl=4, load_loss=0.857, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_315KVA_22KV_433V_3PH_POLEMED_Wilson', phases=3, windings=2, kvas=[315, 315], kvs=[22, 0.433],
xhl=4, load_loss=0.857, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_315KVA_33KV_433V_3PH_PADMOUNT_Tyree', phases=3, windings=2, kvas=[315, 315], kvs=[33, 0.433],
xhl=3.94, load_loss=0.712, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_315KVA_33KV_433V_3PH_POLEMED_Tyree', phases=3, windings=2, kvas=[315, 315], kvs=[33, 0.433],
xhl=3.94, load_loss=0.712, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_350KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[350, 350], kvs=[33, 33], xhl=3.94,
load_loss=0.712, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_11KV_22kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[500, 500], kvs=[11, 22], xhl=4,
load_loss=0.821, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_11KV_33kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[500, 500], kvs=[11, 33], xhl=4,
load_loss=0.821, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_22KV__11kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[500, 500], kvs=[22, 11], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[500, 500], kvs=[22, 11], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_22KV_19.1kV_HV1_Iso_Tx_PAD', phases=1, windings=2, kvas=[500, 500], kvs=[22, 33], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_22KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[500, 500], kvs=[22, 33], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_22KV_19.1kV_SWER_Iso_Tx_POLE', phases=1, windings=2, kvas=[500, 500], kvs=[22, 33], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_22KV_33kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[500, 500], kvs=[22, 33], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_33KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[500, 500], kvs=[33, 11], xhl=4,
load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_33KV_19.1kV_HV1_Iso_Tx_POLE', phases=1, windings=2, kvas=[500, 500], kvs=[33, 33], xhl=4,
load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_33KV_22kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[500, 500], kvs=[33, 22], xhl=4,
load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_6.6KV_433V_3PH_POLEMED', phases=3, windings=2, kvas=[500, 500], kvs=[6.6, 0.433], xhl=4,
load_loss=0.821, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_500KVA_66KV_33kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[500, 500], kvs=[66, 33], xhl=5.2,
load_loss=1.001, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_11KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[11, 0.433],
xhl=4, load_loss=0.821, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_11KV_433V_3PH_POLEMED_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[11, 0.433],
xhl=4, load_loss=0.821, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_22KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[22, 0.433],
xhl=4, load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_22KV_433V_3PH_POLEMED,_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[22, 0.433],
xhl=4, load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_22KV_433V_3PH_POLEMED_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[22, 0.433],
xhl=4, load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_33KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[33, 0.433],
xhl=4, load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_500KVA_33KV_433V_3PH_POLEMED_Wilson', phases=3, windings=2, kvas=[500, 500], kvs=[33, 0.433],
xhl=4, load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_11KV_22 kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[750, 750], kvs=[11, 22], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_22KV__11kV_HV1_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[750, 750], kvs=[22, 11],
xhl=4, load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[750, 750], kvs=[22, 11], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_22KV_433V 3PH POLE MOUNT', phases=3, windings=2, kvas=[750, 750], kvs=[22, 0.433], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_22KV_433V_3PH_PADMOUNT', phases=3, windings=2, kvas=[750, 750], kvs=[22, 0.433], xhl=4,
load_loss=0.977, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_33KV_433V 3PH POLE MOUNT', phases=3, windings=2, kvas=[750, 750], kvs=[33, 0.433], xhl=4,
load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_750KVA_33KV_433V_3PH_PADMOUNT', phases=3, windings=2, kvas=[750, 750], kvs=[33, 0.433], xhl=4,
load_loss=0.718, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_750KVA_11KV_433V 3PH POLE MOUNT_Wilson', phases=3, windings=2, kvas=[750, 750], kvs=[11, 0.433],
xhl=5, load_loss=1.075, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_750KVA_11KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[750, 750], kvs=[11, 0.433],
xhl=5, load_loss=1.075, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_11KV_22kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[11, 22], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_11KV_22kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[1000, 1000], kvs=[11, 22], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_11KV_33kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[11, 33], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_11KV_6.35kV_HV1_Iso_Tx_PAD', phases=1, windings=2, kvas=[1000, 1000], kvs=[11, 11], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_11KV_6.35kV_SWER_Iso_Tx_PAD', phases=1, windings=2, kvas=[1000, 1000], kvs=[11, 11], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_11KV_6.35kV_SWER_Iso_Tx_PAD', phases=1, windings=2, kvas=[1000, 1000], kvs=[11, 11], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_22KV__11kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[22, 11], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[1000, 1000], kvs=[22, 11],
xhl=5, load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_22KV_19.1kV_HV1_Iso_TX PAD', phases=1, windings=2, kvas=[1000, 1000], kvs=[22, 33], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_22KV_33kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[22, 33], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_22KV_33kV_Step_Up_Tx_Pole', phases=3, windings=2, kvas=[1000, 1000], kvs=[22, 33], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_33KV__11kV_3PH_POLEMED', phases=3, windings=2, kvas=[1000, 1000], kvs=[33, 11], xhl=5,
load_loss=0.799, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_33KV__11kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[33, 11], xhl=5,
load_loss=0.799, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_33KV_22kV_3PH_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[1000, 1000], kvs=[33, 22],
xhl=5, load_loss=0.799, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_33KV_22kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[33, 22], xhl=5,
load_loss=0.799, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1000KVA_66KV_33kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1000, 1000], kvs=[66, 33],
xhl=6.25, load_loss=0.902, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_1000KVA_11KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[1000, 1000], kvs=[11, 0.433],
xhl=5, load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_1000KVA_22KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[1000, 1000], kvs=[22, 0.433],
xhl=5, load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_1000KVA_22KV_433V_3PH_POLEMED_Wilson', phases=3, windings=2, kvas=[1000, 1000], kvs=[22, 0.433],
xhl=5, load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_1000KVA_33KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[1000, 1000], kvs=[33, 0.433],
xhl=5, load_loss=0.8, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_11KV_22kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[11, 22], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_11KV_22kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[11, 22], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_11KV_33kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[11, 33], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_11KV_433V_3PH_PADMOUNT', phases=3, windings=2, kvas=[1500, 1500], kvs=[11, 0.433], xhl=5,
load_loss=0.945, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_22KV__11kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[22, 11], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_22KV__11kV_Step_Down_Tx_POLE', phases=3, windings=2, kvas=[1500, 1500], kvs=[22, 11],
xhl=5, load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_22KV_33kV_Step_Up_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[22, 33], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_22KV_433V_3PH_PADMOUNT', phases=3, windings=2, kvas=[1500, 1500], kvs=[22, 0.433], xhl=5,
load_loss=0.96, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_33KV__11kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[33, 11],
xhl=6.25, load_loss=0.902, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_33KV_22kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[33, 22],
xhl=6.25, load_loss=0.902, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='E_1500KVA_66KV_33kV_Step_Down_Tx_PAD', phases=3, windings=2, kvas=[1500, 1500], kvs=[66, 33],
xhl=6.25, load_loss=0.902, conns=['delta', 'wye'], tap=1.0),
XfmrCode(name='M_1500KVA_33KV_433V_3PH_PADMOUNT_Wilson', phases=3, windings=2, kvas=[1500, 1500], kvs=[33, 0.433],
xhl=6.25, load_loss=0.902, conns=['delta', 'wye'], tap=1.0),
] | zepben.edith | /zepben.edith-0.3.0b2-py3-none-any.whl/zepben/edith/transformer_catalogue.py | transformer_catalogue.py |
from dataclasses import dataclass
__all__ = ["LINECODE_CATALOGUE"]
@dataclass
class LC(object):
name: str
phases: int
norm_amps: float
emerg_amps: float
r0: float
r1: float
x0: float
x1: float
hv: bool = False
LINECODE_CATALOGUE = [
LC("Flourine_7/3.00_AAAC/1120_3W", phases=3, norm_amps=165.38, emerg_amps=248.07, r1=0.0006016, r0=0.0007516,
x1=0.000384, x0=0.001599, hv=True),
LC("Flourine_7/3.00_AAAC/1120_2W", phases=2, norm_amps=165.38, emerg_amps=248.07, r1=0.0006016, r0=0.0007016,
x1=0.0004013, x0=0.0011761, hv=True),
LC("Flourine_7/3.00_AAAC/1120_1W", phases=1, norm_amps=165.38, emerg_amps=248.07, r1=0.0006516, r0=0.0006516,
x1=0.0007887, x0=0.0007887, hv=True),
LC("Helium_7/3.75_AAAC/1120_3W", phases=3, norm_amps=215.62, emerg_amps=323.43, r1=0.0003853, r0=0.0005353,
x1=0.0003712, x0=0.0015862, hv=True),
LC("Helium_7/3.75_AAAC/1120_2W", phases=2, norm_amps=215.62, emerg_amps=323.43, r1=0.0003853, r0=0.0004853,
x1=0.0003885, x0=0.0011633, hv=True),
LC("Helium_7/3.75_AAAC/1120_1W", phases=1, norm_amps=215.62, emerg_amps=323.43, r1=0.0004353, r0=0.0004353,
x1=0.0007759, x0=0.0007759, hv=True),
LC("Hydrogen_7/4.50_AAAC/1120_3W", phases=3, norm_amps=267.14, emerg_amps=400.71, r1=0.0002676, r0=0.0004176,
x1=0.0003586, x0=0.0015736, hv=True),
LC("Hydrogen_7/4.50_AAAC/1120_2W", phases=2, norm_amps=267.14, emerg_amps=400.71, r1=0.0002676, r0=0.0003676,
x1=0.0003759, x0=0.0011507, hv=True),
LC("Hydrogen_7/4.50_AAAC/1120_1W", phases=1, norm_amps=267.14, emerg_amps=400.71, r1=0.0003176, r0=0.0003176,
x1=0.0007633, x0=0.0007633, hv=True),
LC("Neon_19/3.75_AAAC/1120_3W", phases=3, norm_amps=386.19, emerg_amps=579.285, r1=0.0001433, r0=0.0002933,
x1=0.0003353, x0=0.0015503, hv=True),
LC("Neon_19/3.75_AAAC/1120_2W", phases=2, norm_amps=386.19, emerg_amps=579.285, r1=0.0001433, r0=0.0002433,
x1=0.0003527, x0=0.0011274, hv=True),
LC("Neon_19/3.75_AAAC/1120_1W", phases=1, norm_amps=386.19, emerg_amps=579.285, r1=0.0001933, r0=0.0001933,
x1=0.00074, x0=0.00074, hv=True),
LC("Nitrogen_37/3.00_AAAC/1120_3W", phases=3, norm_amps=438.21, emerg_amps=657.315, r1=0.0001153, r0=0.0002653,
x1=0.0003274, x0=0.0015423, hv=True),
LC("Nitrogen_37/3.00_AAAC/1120_2W", phases=2, norm_amps=438.21, emerg_amps=657.315, r1=0.0001153, r0=0.0002153,
x1=0.0003447, x0=0.0011195, hv=True),
LC("Nitrogen_37/3.00_AAAC/1120_1W", phases=1, norm_amps=438.21, emerg_amps=657.315, r1=0.0001653, r0=0.0001653,
x1=0.0007321, x0=0.0007321, hv=True),
LC("Neptune_19/3.25_AAC/1350_3W", phases=3, norm_amps=333.38, emerg_amps=500.07, r1=0.0001825, r0=0.0003325,
x1=0.0003443, x0=0.0015592, hv=True),
LC("Neptune_19/3.25_AAC/1350_2W", phases=2, norm_amps=333.38, emerg_amps=500.07, r1=0.0001825, r0=0.0002825,
x1=0.0003616, x0=0.0011364, hv=True),
LC("Neptune_19/3.25_AAC/1350_1W", phases=1, norm_amps=333.38, emerg_amps=500.07, r1=0.0002325, r0=0.0002325,
x1=0.000749, x0=0.000749, hv=True),
LC("Pluto_19/3.75_AAC/1350_3W", phases=3, norm_amps=393.27, emerg_amps=589.905, r1=0.0001375, r0=0.0002875,
x1=0.0003353, x0=0.0015503, hv=True),
LC("Pluto_19/3.75_AAC/1350_2W", phases=2, norm_amps=393.27, emerg_amps=589.905, r1=0.0001375, r0=0.0002375,
x1=0.0003527, x0=0.0011274, hv=True),
LC("Pluto_19/3.75_AAC/1350_1W", phases=1, norm_amps=393.27, emerg_amps=589.905, r1=0.0001875, r0=0.0001875,
x1=0.00074, x0=0.00074, hv=True),
LC("Mercury_7/4.50_AAC/1350_3W", phases=3, norm_amps=271.92, emerg_amps=407.88, r1=0.000257, r0=0.000407,
x1=0.0003586, x0=0.0015736, hv=True),
LC("Mercury_7/4.50_AAC/1350_2W", phases=2, norm_amps=271.92, emerg_amps=407.88, r1=0.000257, r0=0.000357,
x1=0.0003759, x0=0.0011507, hv=True),
LC("Mercury_7/4.50_AAC/1350_1W", phases=1, norm_amps=271.92, emerg_amps=407.88, r1=0.000307, r0=0.000307,
x1=0.0007633, x0=0.0007633, hv=True),
LC("Raisin_3/4/2.50_ACSR/GZ_3W", phases=3, norm_amps=96.2, emerg_amps=144.3, r1=0.0016264, r0=0.0017764,
x1=0.0004584, x0=0.0016735, hv=True),
LC("Raisin_3/4/2.50_ACSR/GZ_2W", phases=2, norm_amps=96.2, emerg_amps=144.3, r1=0.0016264, r0=0.0017264,
x1=0.0004757, x0=0.0012505, hv=True),
LC("Raisin_3/4/2.50_ACSR/GZ_1W", phases=1, norm_amps=96.2, emerg_amps=144.3, r1=0.0016764, r0=0.0016764,
x1=0.0008631, x0=0.0008631, hv=True),
LC("Rosella_4/3/0.093_ACSR/GZ_3W", phases=3, norm_amps=94.03, emerg_amps=141.045, r1=0.0016651, r0=0.0018151,
x1=0.0003946, x0=0.0016096, hv=True),
LC("Rosella_4/3/0.093_ACSR/GZ_2W", phases=2, norm_amps=94.03, emerg_amps=141.045, r1=0.0016651, r0=0.0017651,
x1=0.000412, x0=0.0011868, hv=True),
LC("Rosella_4/3/0.093_ACSR/GZ_1W", phases=1, norm_amps=94.03, emerg_amps=141.045, r1=0.0017151, r0=0.0017151,
x1=0.0007994, x0=0.0007994, hv=True),
LC("ACSR/GZ_2/5/3.25_ACSR/GZ_3W", phases=3, norm_amps=108.21, emerg_amps=162.315, r1=0.0014211, r0=0.0015711,
x1=0.0003746, x0=0.0015896, hv=True),
LC("ACSR/GZ_2/5/3.25_ACSR/GZ_2W", phases=2, norm_amps=108.21, emerg_amps=162.315, r1=0.0014211, r0=0.0015211,
x1=0.000392, x0=0.0011667, hv=True),
LC("ACSR/GZ_2/5/3.25_ACSR/GZ_1W", phases=1, norm_amps=108.21, emerg_amps=162.315, r1=0.0014711, r0=0.0014711,
x1=0.0007794, x0=0.0007794, hv=True),
LC("ACSR/GZ_6/1/0.089_ACSR/GZ_3W", phases=3, norm_amps=110.93, emerg_amps=166.395, r1=0.0011755, r0=0.0013255,
x1=0.0004034, x0=0.0016184, hv=True),
LC("ACSR/GZ_6/1/0.089_ACSR/GZ_2W", phases=2, norm_amps=110.93, emerg_amps=166.395, r1=0.0011755, r0=0.0012755,
x1=0.0004208, x0=0.0011956, hv=True),
LC("ACSR/GZ_6/1/0.089_ACSR/GZ_1W", phases=1, norm_amps=110.93, emerg_amps=166.395, r1=0.0012255, r0=0.0012255,
x1=0.0008082, x0=0.0008082, hv=True),
LC("Almond_6/1/2.50_ACSR/GZ_3W", phases=3, norm_amps=121.32, emerg_amps=181.98, r1=0.0010225, r0=0.0011725,
x1=0.0004022, x0=0.0016172, hv=True),
LC("Almond_6/1/2.50_ACSR/GZ_2W", phases=2, norm_amps=121.32, emerg_amps=181.98, r1=0.0010225, r0=0.0011225,
x1=0.0004195, x0=0.0011943, hv=True),
LC("Almond_6/1/2.50_ACSR/GZ_1W", phases=1, norm_amps=121.32, emerg_amps=181.98, r1=0.0010725, r0=0.0010725,
x1=0.0008069, x0=0.0008069, hv=True),
LC("Banana_6/1/3.75_ACSR/GZ_3W", phases=3, norm_amps=190.58, emerg_amps=285.87, r1=0.0004839, r0=0.0006339,
x1=0.0003771, x0=0.0015921, hv=True),
LC("Banana_6/1/3.75_ACSR/GZ_2W", phases=2, norm_amps=190.58, emerg_amps=285.87, r1=0.0004839, r0=0.0005839,
x1=0.0003944, x0=0.0011692, hv=True),
LC("Banana_6/1/3.75_ACSR/GZ_1W", phases=1, norm_amps=190.58, emerg_amps=285.87, r1=0.0005339, r0=0.0005339,
x1=0.0007818, x0=0.0007818, hv=True),
LC("2_Core_Al_LV_XLPE_ABC_OH_2W", phases=2, norm_amps=105, emerg_amps=157.5, r1=0.0014176, r0=0.0014176,
x1=0.000089, x0=0.000089),
LC("4_Core_Al_LV_XLPE_ABC_OH_4W", phases=3, norm_amps=97, emerg_amps=145.5, r1=0.0014176, r0=0.00595151,
x1=0.000097, x0=0.000097),
LC("AAAC:7/4.50", phases=3, norm_amps=383, emerg_amps=574.5, r1=0.000315100014, r0=0.000315100014,
x1=0.000305000007, x0=0.000915000021),
LC("AAAC:19/3.25", phases=3, norm_amps=473, emerg_amps=709.5, r1=0.000225400001, r0=0.000225400001,
x1=0.000290600002, x0=0.000871800006),
LC("AAAC:19/3.75", phases=3, norm_amps=562, emerg_amps=843, r1=0.000171200007, r0=0.000171200007, x1=0.000281699985,
x0=0.000845099955),
LC("AAAC:19/4.75", phases=3, norm_amps=747, emerg_amps=1120.5, r1=0.000110600002, r0=0.000110600002,
x1=0.000266799986, x0=0.000800399958),
LC("AAAC:37/3.00", phases=3, norm_amps=642, emerg_amps=963, r1=0.000138500005, r0=0.000138500005, x1=0.000273900002,
x0=0.000821700006),
LC("ABC2w:25ABC", phases=2, norm_amps=105, emerg_amps=157.5, r1=0.001417600036, r0=0.001417600036, x1=0.000089,
x0=0.000267),
LC("ABC2w:95ABC", phases=2, norm_amps=230, emerg_amps=345, r1=0.000378600001, r0=0.000378600001, x1=0.00008,
x0=0.00024),
LC("ABC4w:25ABC", phases=3, norm_amps=97, emerg_amps=145.5, r1=0.001417600036, r0=0.001417600036, x1=0.000097,
x0=0.000291),
LC("ABC4w:50ABC", phases=3, norm_amps=140, emerg_amps=210, r1=0.000757300019, r0=0.000757300019, x1=0.000093,
x0=0.000279),
LC("ABC4w:70ABC", phases=3, norm_amps=175, emerg_amps=262.5, r1=0.000524200022, r0=0.000524200022, x1=0.000088,
x0=0.000264),
LC("ABC4w:95ABC", phases=3, norm_amps=215, emerg_amps=322.5, r1=0.000378600001, r0=0.000378600001, x1=0.000087,
x0=0.000261),
LC("ABC4w:150ABC", phases=3, norm_amps=280, emerg_amps=420, r1=0.000244499996, r0=0.000244499996, x1=0.000084,
x0=0.000252),
LC("Cu_U/G:16C/4c", phases=3, norm_amps=105, emerg_amps=157.5, r1=0.001399999976, r0=0.001399999976, x1=0.0000805,
x0=0.0002415),
LC("Cu_U/G:25C/4c", phases=3, norm_amps=150, emerg_amps=225, r1=0.000884000003, r0=0.000884000003, x1=0.0000808,
x0=0.0002424),
LC("Cu_U/G:50C/4c", phases=3, norm_amps=215, emerg_amps=322.5, r1=0.000470999986, r0=0.000470999986, x1=0.0000751,
x0=0.0002253),
LC("Cu_U/G:70C/1c", phases=3, norm_amps=260, emerg_amps=390, r1=0.000326999992, r0=0.000326999992,
x1=0.000104000002, x0=0.000312000006),
LC("Cu_U/G:35mm/4C", phases=3, norm_amps=135, emerg_amps=202.5, r1=0.000667999983, r0=0.000667999983,
x1=0.000136999995, x0=0.000410999985),
LC("Cu_U/G:50mm/4C", phases=3, norm_amps=160, emerg_amps=240, r1=0.000493999988, r0=0.000493999988,
x1=0.000129999995, x0=0.000389999985),
LC("Al_UG:120A/4C", phases=3, norm_amps=255, emerg_amps=382.5, r1=0.000310000002, r0=0.000310000002, x1=0.0000685,
x0=0.0002055),
LC("Al_UG:185A/4C", phases=3, norm_amps=325, emerg_amps=487.5, r1=0.000202000007, r0=0.000202000007, x1=0.0000686,
x0=0.0002058),
LC("Al_UG:240A/4C", phases=3, norm_amps=380, emerg_amps=570, r1=0.000153999999, r0=0.000153999999, x1=0.0000678,
x0=0.0002034),
LC("CONSAC:70mm", phases=3, norm_amps=170, emerg_amps=255, r1=0.000541000009, r0=0.000541000009, x1=0.0000646,
x0=0.0001938),
LC("CONSAC:185mm", phases=3, norm_amps=305, emerg_amps=457.5, r1=0.000201000005, r0=0.000201000005, x1=0.0000622,
x0=0.0001866),
LC("CONSAC:300mm", phases=3, norm_amps=395, emerg_amps=592.5, r1=0.000123999998, r0=0.000123999998, x1=0.0000614,
x0=0.0001842),
LC('line-237A-aac-7-3w', phases=3, norm_amps=237, emerg_amps=355.5, r1=0.000684800029, r0=0.000684800029,
x1=0.000330500007, x0=0.000330500007),
LC('line-388A-aac-7-4.5-1w', phases=1, norm_amps=388, emerg_amps=582, r1=0.000307099998, r0=0.000307099998,
x1=0.000305, x0=0.000305),
LC('line-479A-aac-19-3.25-3w', phases=3, norm_amps=479, emerg_amps=582, r1=0.000219400004, r0=0.000219400004,
x1=0.000290600002, x0=0.000290600002),
LC('line-479A-aac-19-3.25-1w', phases=1, norm_amps=479, emerg_amps=582, r1=0.000219400004, r0=0.000219400004,
x1=0.000290600002, x0=0.000290600002),
LC('test-linecode-1w', phases=1, norm_amps=600, emerg_amps=800, r1=0.000219400004, r0=0.000219400004,
x1=0.000290600002, x0=0.000290600002),
LC('test-linecode-3w', phases=3, norm_amps=600, emerg_amps=800, r1=0.000219400004, r0=0.000219400004,
x1=0.000290600002, x0=0.000290600002),
] | zepben.edith | /zepben.edith-0.3.0b2-py3-none-any.whl/zepben/edith/linecode_catalogue.py | linecode_catalogue.py |
import itertools
import random
from asyncio import get_event_loop
from zepben.evolve import *
from zepben.protobuf.nc.nc_requests_pb2 import INCLUDE_ENERGIZED_LV_FEEDERS
from zepben.edith.linecode_catalogue import LINECODE_CATALOGUE
__all__ = ["line_weakener", "transformer_weakener",
"usage_point_proportional_allocator", "NetworkConsumerClient", "SyncNetworkConsumerClient"]
from zepben.edith.transformer_catalogue import TRANSFORMER_CATALOGUE
def line_weakener(
weakening_percentage: int,
use_weakest_when_necessary: bool = True,
callback: Optional[Callable[[Set[str]], Any]] = None
) -> Callable[[NetworkService], None]:
"""
Returns a mutator function that downgrades lines based on their amp rating. Both the amp rating and impedance is
updated using an entry in the built-in catalogue of linecodes. The linecode must match the voltage category (HV/LV)
and phase count (e.g. 2 for AB, 3 for ABCN). If the target amp rating is lower than the amp rating of every
candidate linecode, the one with the lowest amp rating will be used if `use_weakest_when_necessary` is `True`.
:param weakening_percentage: Percentage to reduce amp rating of lines by. The linecode chosen for a line with an amp
rating of N should have an amp rating of at most (100 - weakening_percentage)% of N.
:param use_weakest_when_necessary: Whether to use the linecode with the lowest amp rating if the target amp rating
for a line is too low. Defaults to `True`.
:param callback: An optional callback that acts on the set of mRIDs of modified lines.
:return: A mutator function that downgrades lines.
"""
if not 1 <= weakening_percentage <= 100:
raise ValueError("Weakening percentage must be between 1 and 100")
amp_rating_ratio = (100 - weakening_percentage) / 100
hv_linecodes = [lc for lc in LINECODE_CATALOGUE if lc.hv]
lv_linecodes = [lc for lc in LINECODE_CATALOGUE if not lc.hv]
def mutate(feeder_network: NetworkService):
# Add wire info and plsi for each linecode
for lc in LINECODE_CATALOGUE:
feeder_network.add(CableInfo(mrid=f"{lc.name}-ug", rated_current=int(lc.norm_amps)))
feeder_network.add(OverheadWireInfo(mrid=f"{lc.name}-oh", rated_current=int(lc.norm_amps)))
feeder_network.add(PerLengthSequenceImpedance(mrid=f"{lc.name}-plsi", r0=lc.r0, x0=lc.x0, r=lc.r1, x=lc.x1))
lines_modified = set()
for acls in feeder_network.objects(AcLineSegment):
try:
terminal = acls.get_terminal_by_sn(1)
except IndexError:
continue
if acls.wire_info is None or acls.wire_info.rated_current is None:
continue
wire_info: WireInfo = acls.wire_info
if acls.base_voltage_value > 1000:
correct_voltage_lcs = hv_linecodes
else:
correct_voltage_lcs = lv_linecodes
correct_phases_lcs = [
lc for lc in correct_voltage_lcs if lc.phases == terminal.phases.without_neutral.num_phases
]
viable_lcs = filter(
lambda lc: lc.norm_amps <= wire_info.rated_current * amp_rating_ratio,
correct_phases_lcs
)
if use_weakest_when_necessary:
fallback_lc = min(correct_phases_lcs, key=lambda lc: lc.norm_amps, default=None)
else:
fallback_lc = None
linecode = max(viable_lcs, key=lambda lc: lc.norm_amps, default=fallback_lc)
if linecode is None:
continue
acls.per_length_sequence_impedance = feeder_network.get(f"{linecode.name}-plsi", PerLengthSequenceImpedance)
if isinstance(acls.wire_info, CableInfo):
acls.wire_info = feeder_network.get(f"{linecode.name}-ug", CableInfo)
else:
acls.wire_info = feeder_network.get(f"{linecode.name}-oh", OverheadWireInfo)
lines_modified.add(acls.mrid)
if callback is not None:
callback(lines_modified)
return mutate
def transformer_weakener(
weakening_percentage: int,
use_weakest_when_necessary: bool = True,
match_voltages: bool = True,
callback: Optional[Callable[[Set[str]], Any]] = None
) -> Callable[[NetworkService], None]:
"""
Returns a mutator function that downgrades transformers based on their VA rating. The VA rating of transformer ends
are updated using an entry in the built-in catalogue of transformer models. The model must match the number of
windings (usually 2), number of phases on each winding, and the operating voltages of each winding unless
`match_voltages` is `False`. If the target VA rating is lower than the VA rating of every candidate transformer
model, the one with the lowest VA rating will be used if `use_weakest_when_necessary` is `True`.
:param weakening_percentage: Percentage to reduce VA rating of transformer ends by. The transformer model chosen
for a line with an VA rating of N should have a VA rating of at most
(100 - weakening_percentage)% of N.
:param use_weakest_when_necessary: Whether to use the transformer model with the lowest VA rating if the target
VA rating for a line is too low. Defaults to `True`.
:param match_voltages: Whether to match the operating voltage of transformer windings when selecting a transformer
model. Defaults to `True`.
:param callback: An optional callback is called on the set of mRIDs of modified transformers.
:return: A mutator function that downgrades transformers.
"""
if not 1 <= weakening_percentage <= 100:
raise ValueError("Weakening percentage must be between 1 and 100")
amp_rating_ratio = (100 - weakening_percentage) / 100
def mutate(feeder_network: NetworkService):
modified_txs = set()
for tx in feeder_network.objects(PowerTransformer):
ends = list(tx.ends)
if len(ends) == 0:
continue
for end in ends:
if end.rated_s is not None:
target_rated_va = end.rated_s * amp_rating_ratio
break
else:
continue
correct_num_windings = filter(lambda xfmr: xfmr.windings == len(ends), TRANSFORMER_CATALOGUE)
num_cores = ends[0].terminal.phases.without_neutral.num_phases
correct_cores_xfmrs = filter(lambda xfmr: xfmr.phases == num_cores, correct_num_windings)
if match_voltages:
end_voltages = [end.rated_u/1000 for end in ends]
good_voltage_xfmrs = [xfmr for xfmr in correct_cores_xfmrs if xfmr.kvs == end_voltages]
else:
good_voltage_xfmrs = list(correct_cores_xfmrs)
viable_xfmrs = filter(lambda xfmr: max(xfmr.kvas) * 1000 <= target_rated_va, good_voltage_xfmrs)
if use_weakest_when_necessary:
fallback_xfmr = min(good_voltage_xfmrs, key=lambda xfmr: max(xfmr.kvas), default=None)
else:
fallback_xfmr = None
xfmr = max(viable_xfmrs, key=lambda xfmr: max(xfmr.kvas), default=fallback_xfmr)
if xfmr is None:
continue
for end, new_kva_rating in zip(ends, xfmr.kvas):
end.rated_s = new_kva_rating * 1000
modified_txs.add(tx.mrid)
if callback is not None:
callback(modified_txs)
return mutate
def usage_point_proportional_allocator(
proportion: int,
edith_customers: List[str],
allow_duplicate_customers: bool = False,
seed: Optional[int] = None,
callback: Optional[Callable[[Set[str]], Any]] = None
) -> Callable[[NetworkService], None]:
"""
Creates a mutator function that distributes a `proportion` of NMIs from `edith_customers`
to the `UsagePoint`s in the network.
:param proportion: The percentage of Edith customers to distribute to an `LvFeeder`. Must be between 1 and 100
:param edith_customers: The Edith NMIs to distribute to the `UsagePoint`s in the network.
:param allow_duplicate_customers: Reuse customers from the list to reach the proportion if necessary. Defaults to
`False`.
:param seed: A number to seed the random number generator with. Defaults to not seeding.
:param callback: An optional function that is called on the set of mRIDs of `UsagePoint`s that are named.
:return: A mutator function that distributes NMIs across `proportion`% of the `UsagePoint`s, and returns the set
of mRIDs of modified `UsagePoint`s.
"""
if not 1 <= proportion <= 100:
raise ValueError("Proportion must be between 1 and 100")
if allow_duplicate_customers:
nmi_generator = itertools.cycle(edith_customers)
else:
nmi_generator = iter(edith_customers)
def mutate(feeder_network: NetworkService):
random.seed(seed)
try:
nmi_name_type = feeder_network.get_name_type("NMI")
except KeyError:
# noinspection PyArgumentList
nmi_name_type = NameType(name="NMI")
feeder_network.add_name_type(nmi_name_type)
usage_points_named = set()
for lv_feeder in feeder_network.objects(LvFeeder):
usage_points = []
for eq in lv_feeder.equipment:
usage_points.extend(eq.usage_points)
usage_points.sort(key=lambda up: up.mrid)
usage_points_to_name = random.sample(usage_points, int(len(usage_points) * proportion / 100))
for usage_point in usage_points_to_name:
try:
next_nmi = next(nmi_generator)
except StopIteration:
break
for name in usage_point.names:
if name.type.name == "NMI":
usage_point.remove_name(name)
name.type.remove_name(name)
break
usage_point.add_name(nmi_name_type.get_or_add_name(next_nmi, usage_point))
usage_points_named.add(usage_point.mrid)
else:
continue
break
if callback is not None:
callback(usage_points_named)
return mutate
async def _create_synthetic_feeder(
self: NetworkConsumerClient,
feeder_mrid: str,
mutators: Iterable[Callable[[NetworkService], None]] = ()
):
"""
Creates a copy of the given `feeder_mrid` and runs `mutator` to the copied network.
:param feeder_mrid: The mRID of the feeder to create a synthetic version of.
:param mutators: The mutator functions to use to modify the feeder network. Defaults to no mutator functions.
:return: The mRIDs of the mutated objects in the feeder network.
"""
(await self.get_equipment_container(feeder_mrid, Feeder, include_energized_containers=INCLUDE_ENERGIZED_LV_FEEDERS)).throw_on_error()
for mutator in mutators:
mutator(self.service)
NetworkConsumerClient.create_synthetic_feeder = _create_synthetic_feeder
def _sync_create_synthetic_feeder(
self: SyncNetworkConsumerClient,
feeder_mrid: str,
mutators: Iterable[Callable[[NetworkService], None]] = ()
):
"""
Creates a copy of the given `feeder_mrid` and runs `mutator` to the copied network.
:param feeder_mrid: The mRID of the feeder to create a synthetic version of.
:param mutator: The mutator to use to modify the feeder network. Default will do nothing to the feeder.
:return: The mRIDs of the mutated objects in the feeder network.
"""
return get_event_loop().run_until_complete(_create_synthetic_feeder(self, feeder_mrid, mutators))
SyncNetworkConsumerClient.create_synthetic_feeder = _sync_create_synthetic_feeder | zepben.edith | /zepben.edith-0.3.0b2-py3-none-any.whl/zepben/edith/__init__.py | __init__.py |
from __future__ import annotations
import os
import re
from collections.abc import Sized
from typing import List, Optional, Iterable, Callable, Any, TypeVar, Generator, Dict
from uuid import UUID
__all__ = ["get_by_mrid", "contains_mrid", "safe_remove", "safe_remove_by_id", "nlen", "ngen", "is_none_or_empty", "require", "pb_or_none", "CopyableUUID"]
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from zepben.evolve import IdentifiedObject
TIdentifiedObject = TypeVar('TIdentifiedObject', bound=IdentifiedObject)
T = TypeVar('T')
def snake2camelback(name: str):
return ''.join(word.title() for word in name.split('_'))
_camel_pattern = re.compile(r'(?<!^)(?=[A-Z])')
def camel2snake(name: str):
return _camel_pattern.sub('_', name).lower()
def iter_but_not_str(obj: Any):
return isinstance(obj, Iterable) and not isinstance(obj, (str, bytes, bytearray, dict))
def get_by_mrid(collection: Optional[Iterable[TIdentifiedObject]], mrid: str) -> TIdentifiedObject:
"""
Get an `IdentifiedObject` from `collection` based on
its mRID.
`collection` The collection to operate on
`mrid` The mRID of the `IdentifiedObject` to lookup in the collection
Returns The `IdentifiedObject`
Raises `KeyError` if `mrid` was not found in the collection.
"""
if not collection:
raise KeyError(mrid)
for io in collection:
if io.mrid == mrid:
return io
raise KeyError(mrid)
def contains_mrid(collection: Optional[Iterable[IdentifiedObject]], mrid: str) -> bool:
"""
Check if a collection of `IdentifiedObject` contains an
object with a specified mRID.
`collection` The collection to operate on
`mrid` The mRID to look up.
Returns True if an `IdentifiedObject` is found in the collection with the specified mRID, False otherwise.
"""
if not collection:
return False
try:
if get_by_mrid(collection, mrid):
return True
except KeyError:
return False
def safe_remove(collection: Optional[List[T]], obj: T):
"""
Remove an IdentifiedObject from a collection safely.
Raises `ValueError` if `obj` is not in the collection.
Returns The collection if successfully removed or None if after removal the collection was empty.
"""
if collection is not None:
collection.remove(obj)
if not collection:
return None
return collection
else:
raise ValueError(obj)
def safe_remove_by_id(collection: Optional[Dict[str, IdentifiedObject]], obj: Optional[IdentifiedObject]):
"""
Remove an IdentifiedObject from a collection safely.
Raises `ValueError` if `obj` is not in the collection.
Returns The collection if successfully removed or None if after removal the collection was empty.
"""
if not obj or not collection:
raise KeyError(obj)
del collection[obj.mrid]
if not collection:
return None
return collection
def nlen(sized: Optional[Sized]) -> int:
"""
Get the len of a nullable sized type.
`sized` The object to get length of
Returns 0 if `sized` is None, otherwise len(`sized`)
"""
return 0 if sized is None else len(sized)
def ngen(collection: Optional[Iterable[T]]) -> Generator[T, None, None]:
if collection:
for item in collection:
yield item
def is_none_or_empty(sized: Optional[Sized]) -> bool:
"""
Check if a given object is empty and return None if it is.
`sized` Any type implementing `__len__`
Returns `sized` if len(sized) > 0, or None if sized is None or len(sized) == 0.
"""
return sized is None or not len(sized)
def require(condition: bool, lazy_message: Callable[[], Any]):
"""
Raise a `ValueError` if condition is not met, with the result of calling `lazy_message` as the message,
if the result is false.
"""
if not condition:
raise ValueError(str(lazy_message()))
def pb_or_none(cim: Optional[Any]):
""" Convert to a protobuf type or return None if cim was None """
return cim.to_pb() if cim is not None else None
class CopyableUUID(UUID):
def __init__(self):
super().__init__(bytes=os.urandom(16), version=4)
@staticmethod
def copy():
return str(UUID(bytes=os.urandom(16), version=4)) | zepben.evolve | /zepben.evolve-0.35.0b2-py3-none-any.whl/zepben/evolve/util.py | util.py |
from zepben.evolve.model.cim.iec61968.customers.pricing_structure import *
from zepben.evolve.model.cim.iec61968.customers.customer_agreement import *
from zepben.evolve.model.cim.iec61968.customers.customer_kind import *
from zepben.evolve.model.cim.iec61968.customers.customer import *
from zepben.evolve.model.cim.iec61968.customers.tariff import *
from zepben.evolve.model.cim.iec61968.assets.structure import *
from zepben.evolve.model.cim.iec61968.assets.asset import *
from zepben.evolve.model.cim.iec61968.assets.pole import *
from zepben.evolve.model.cim.iec61968.assets.asset_organisation_role import *
from zepben.evolve.model.cim.iec61968.assets.asset_info import *
from zepben.evolve.model.cim.iec61968.assets.streetlight import *
from zepben.evolve.model.cim.iec61968.operations.operational_restriction import *
from zepben.evolve.model.cim.iec61968.assetinfo.wire_info import *
from zepben.evolve.model.cim.iec61968.assetinfo.power_transformer_info import *
from zepben.evolve.model.cim.iec61968.assetinfo.wire_material_kind import *
from zepben.evolve.model.cim.iec61968.assetinfo.transformer_test import *
from zepben.evolve.model.cim.iec61968.assetinfo.no_load_test import *
from zepben.evolve.model.cim.iec61968.assetinfo.open_circuit_test import *
from zepben.evolve.model.cim.iec61968.assetinfo.short_circuit_test import *
from zepben.evolve.model.cim.iec61968.assetinfo.shunt_compensator_info import *
from zepben.evolve.model.cim.iec61968.assetinfo.transformer_end_info import *
from zepben.evolve.model.cim.iec61968.assetinfo.transformer_tank_info import *
from zepben.evolve.model.cim.iec61968.infiec61968.infassetinfo.current_transformer_info import *
from zepben.evolve.model.cim.iec61968.infiec61968.infassetinfo.potential_transformer_info import *
from zepben.evolve.model.cim.iec61968.infiec61968.infassetinfo.transformer_construction_kind import *
from zepben.evolve.model.cim.iec61968.infiec61968.infassetinfo.transformer_function_kind import *
from zepben.evolve.model.cim.iec61968.infiec61968.infcommon.ratio import *
from zepben.evolve.model.cim.iec61968.metering.metering import *
from zepben.evolve.model.cim.iec61968.common.organisation import *
from zepben.evolve.model.cim.iec61968.common.document import *
from zepben.evolve.model.cim.iec61968.common.organisation_role import *
from zepben.evolve.model.cim.iec61968.common.location import *
from zepben.evolve.model.cim.iec61970.base.auxiliaryequipment.current_transformer import *
from zepben.evolve.model.cim.iec61970.base.auxiliaryequipment.potential_transformer import *
from zepben.evolve.model.cim.iec61970.base.auxiliaryequipment.potential_transformer_kind import *
from zepben.evolve.model.cim.iec61970.base.auxiliaryequipment.sensor import *
from zepben.evolve.model.cim.iec61970.base.equivalents.equivalent_branch import *
from zepben.evolve.model.cim.iec61970.base.equivalents.equivalent_equipment import *
from zepben.evolve.model.cim.iec61970.base.meas.control import *
from zepben.evolve.model.cim.iec61970.base.meas.measurement import *
from zepben.evolve.model.cim.iec61970.base.meas.value import *
from zepben.evolve.model.cim.iec61970.base.meas.iopoint import *
from zepben.evolve.model.cim.iec61970.base.diagramlayout.diagram_layout import *
from zepben.evolve.model.cim.iec61970.base.diagramlayout.orientation_kind import *
from zepben.evolve.model.cim.iec61970.base.diagramlayout.diagram_style import *
from zepben.evolve.model.cim.iec61970.base.scada.remote_point import *
from zepben.evolve.model.cim.iec61970.base.scada.remote_source import *
from zepben.evolve.model.cim.iec61970.base.scada.remote_control import *
from zepben.evolve.model.cim.iec61970.base.domain.unit_symbol import *
from zepben.evolve.model.cim.iec61970.base.auxiliaryequipment.auxiliary_equipment import *
from zepben.evolve.model.cim.iec61970.base.wires.generation.production.power_electronics_unit import *
from zepben.evolve.model.cim.iec61970.base.wires.generation.production.battery_state_kind import *
from zepben.evolve.model.cim.iec61970.base.wires.line import *
from zepben.evolve.model.cim.iec61970.base.wires.energy_consumer import *
from zepben.evolve.model.cim.iec61970.base.wires.aclinesegment import *
from zepben.evolve.model.cim.iec61970.base.wires.per_length import *
from zepben.evolve.model.cim.iec61970.base.wires.vector_group import *
from zepben.evolve.model.cim.iec61970.base.wires.winding_connection import *
from zepben.evolve.model.cim.iec61970.base.wires.shunt_compensator import *
from zepben.evolve.model.cim.iec61970.base.wires.power_electronics_connection import *
from zepben.evolve.model.cim.iec61970.base.wires.power_transformer import *
from zepben.evolve.model.cim.iec61970.base.wires.energy_source_phase import *
from zepben.evolve.model.cim.iec61970.base.wires.phase_shunt_connection_kind import *
from zepben.evolve.model.cim.iec61970.base.wires.connectors import *
from zepben.evolve.model.cim.iec61970.base.wires.switch import *
from zepben.evolve.model.cim.iec61970.base.wires.energy_source import *
from zepben.evolve.model.cim.iec61970.base.wires.single_phase_kind import *
from zepben.evolve.model.cim.iec61970.base.wires.energy_connection import *
from zepben.evolve.model.cim.iec61970.base.wires.transformer_star_impedance import *
from zepben.evolve.model.cim.iec61970.base.core.substation import *
from zepben.evolve.model.cim.iec61970.base.core.terminal import *
from zepben.evolve.model.cim.iec61970.base.core.equipment import *
from zepben.evolve.model.cim.iec61970.base.core.conducting_equipment import *
from zepben.evolve.model.cim.iec61970.base.core.identified_object import *
from zepben.evolve.model.cim.iec61970.base.core.base_voltage import *
from zepben.evolve.model.cim.iec61970.base.core.power_system_resource import *
from zepben.evolve.model.cim.iec61970.base.core.connectivity_node_container import *
from zepben.evolve.model.cim.iec61970.base.core.regions import *
from zepben.evolve.model.cim.iec61970.base.core.phase_code import *
from zepben.evolve.model.cim.iec61970.base.core.equipment_container import *
from zepben.evolve.model.cim.iec61970.base.core.connectivity_node import *
from zepben.evolve.model.cim.iec61970.base.core.name import *
from zepben.evolve.model.cim.iec61970.base.core.name_type import *
from zepben.evolve.model.cim.iec61970.infiec61970.feeder.circuit import *
from zepben.evolve.model.cim.iec61970.infiec61970.feeder.loop import *
from zepben.evolve.model.cim.iec61970.infiec61970.feeder.lv_feeder import *
from zepben.evolve.model.phases import *
from zepben.evolve.model.resistance_reactance import *
from zepben.evolve.services.network.tracing.traversals.tracker import *
from zepben.evolve.services.network.tracing.traversals.basic_tracker import *
from zepben.evolve.services.network.tracing.traversals.traversal import *
from zepben.evolve.services.network.tracing.traversals.basic_traversal import *
from zepben.evolve.services.network.tracing.traversals.queue import *
from zepben.evolve.services.network.tracing.traversals.branch_recursive_tracing import *
from zepben.evolve.services.network.tracing.feeder.feeder_direction import *
from zepben.evolve.services.network.tracing.util import *
from zepben.evolve.services.network.translator.network_proto2cim import *
from zepben.evolve.services.network.translator.network_cim2proto import *
from zepben.evolve.services.network.network_service import *
from zepben.evolve.services.network.tracing.connectivity.conducting_equipment_step import *
from zepben.evolve.services.network.tracing.connectivity.conducting_equipment_step_tracker import *
from zepben.evolve.services.network.tracing.connectivity.connected_equipment_trace import *
from zepben.evolve.services.network.tracing.connectivity.connectivity_result import *
from zepben.evolve.services.network.tracing.connectivity.connectivity_trace import *
from zepben.evolve.services.network.tracing.connectivity.limited_connected_equipment_trace import *
from zepben.evolve.services.network.tracing.connectivity.phase_paths import *
from zepben.evolve.services.network.tracing.connectivity.terminal_connectivity_connected import *
from zepben.evolve.services.network.tracing.connectivity.terminal_connectivity_internal import *
from zepben.evolve.services.network.tracing.connectivity.transformer_phase_paths import *
from zepben.evolve.services.network.tracing.connectivity.xy_candidate_phase_paths import *
from zepben.evolve.services.network.tracing.connectivity.xy_phase_step import *
from zepben.evolve.services.network.tracing.feeder.direction_status import *
from zepben.evolve.services.network.tracing.feeder.assign_to_feeders import *
from zepben.evolve.services.network.tracing.feeder.assign_to_lv_feeders import *
from zepben.evolve.services.network.tracing.feeder.associated_terminal_trace import *
from zepben.evolve.services.network.tracing.feeder.associated_terminal_tracker import *
from zepben.evolve.services.network.tracing.feeder.set_direction import *
from zepben.evolve.services.network.tracing.feeder.remove_direction import *
from zepben.evolve.services.network.tracing.phases.phase_step import *
from zepben.evolve.services.network.tracing.phases.phase_status import *
from zepben.evolve.services.network.tracing.phases.phase_step_tracker import *
from zepben.evolve.services.network.tracing.phases.phase_trace import *
from zepben.evolve.services.network.tracing.phases.set_phases import *
from zepben.evolve.services.network.tracing.phases.phase_inferrer import *
from zepben.evolve.services.network.tracing.phases.remove_phases import *
from zepben.evolve.services.network.tracing.find import *
from zepben.evolve.services.network.tracing.find_swer_equipment import *
from zepben.evolve.services.network.tracing.tracing import *
from zepben.evolve.services.network.tracing import tracing
from zepben.evolve.services.common.meta.data_source import *
from zepben.evolve.services.common.meta.metadata_collection import *
from zepben.evolve.services.common.translator.base_proto2cim import *
from zepben.evolve.services.common.base_service import *
from zepben.evolve.services.common.reference_resolvers import BoundReferenceResolver, ReferenceResolver, UnresolvedReference
from zepben.evolve.services.common import resolver
from zepben.evolve.services.diagram.translator.diagram_proto2cim import *
from zepben.evolve.services.diagram.translator.diagram_cim2proto import *
from zepben.evolve.services.diagram.diagrams import *
from zepben.evolve.services.customer.translator.customer_cim2proto import *
from zepben.evolve.services.customer.translator.customer_proto2cim import *
from zepben.evolve.services.customer.customers import *
from zepben.evolve.services.measurement.translator.measurement_cim2proto import *
from zepben.evolve.services.measurement.translator.measurement_proto2cim import *
from zepben.evolve.services.measurement.measurements import *
from zepben.evolve.streaming.exceptions import *
from zepben.evolve.streaming.get.hierarchy.data import *
from zepben.evolve.streaming.get.consumer import *
from zepben.evolve.streaming.get.customer_consumer import *
from zepben.evolve.streaming.get.diagram_consumer import *
from zepben.evolve.streaming.get.network_consumer import *
from zepben.evolve.streaming.grpc.auth_token_plugin import *
from zepben.evolve.streaming.grpc.grpc import *
from zepben.evolve.streaming.grpc.grpc_channel_builder import *
from zepben.evolve.streaming.grpc.connect import *
from zepben.evolve.util import *
from zepben.evolve.services.network.network_extensions import *
from zepben.evolve.model.busbranch.bus_branch import *
from zepben.evolve.services.common.difference import *
from zepben.evolve.services.common.translator.service_differences import *
from zepben.evolve.services.common.base_service_comparator import BaseServiceComparator
from zepben.evolve.services.network.network_service_comparator import NetworkServiceComparator
from zepben.evolve.database.sqlite.tables.column import *
from zepben.evolve.database.sqlite.tables.sqlite_table import *
from zepben.evolve.database.sqlite.tables.metadata_tables import *
from zepben.evolve.database.sqlite.tables.associations.loop_association_tables import *
from zepben.evolve.database.sqlite.tables.associations.circuit_association_tables import *
from zepben.evolve.database.sqlite.tables.associations.customeragreements_association_tables import *
from zepben.evolve.database.sqlite.tables.associations.equipment_association_tables import *
from zepben.evolve.database.sqlite.tables.associations.usagepoints_association_tables import *
from zepben.evolve.database.sqlite.tables.associations.assetorganisationroles_association_tables import *
from zepben.evolve.database.sqlite.tables.associations.pricingstructure_association_tables import *
from zepben.evolve.database.sqlite.tables.iec61968.common_tables import *
from zepben.evolve.database.sqlite.tables.iec61968.asset_tables import *
from zepben.evolve.database.sqlite.tables.iec61968.customer_tables import *
from zepben.evolve.database.sqlite.tables.iec61968.metering_tables import *
from zepben.evolve.database.sqlite.tables.iec61968.assetinfo_tables import *
from zepben.evolve.database.sqlite.tables.iec61968.operations_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.core_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.meas_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.scada_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.equivalent_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.auxiliaryequipment_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.diagramlayout_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.container_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.switch_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.energyconnection_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.transformer_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.conductor_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.connector_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.perlength_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.wires.generation.production_tables import *
from zepben.evolve.database.sqlite.tables.iec61970.base.infiec61970.feeder_tables import *
from zepben.evolve.database.sqlite.tables.database_tables import *
from zepben.evolve.database.sqlite.tables.exceptions import *
from zepben.evolve.database.sqlite.writers.base_cim_writer import *
from zepben.evolve.database.sqlite.writers.network_cim_writer import *
from zepben.evolve.database.sqlite.writers.customer_cim_writer import *
from zepben.evolve.database.sqlite.writers.diagram_cim_writer import *
from zepben.evolve.database.sqlite.writers.metadata_entry_writer import *
from zepben.evolve.database.sqlite.writers.metadata_collection_writer import *
from zepben.evolve.database.sqlite.writers.base_service_writer import *
from zepben.evolve.database.sqlite.writers.network_service_writer import *
from zepben.evolve.database.sqlite.writers.customer_service_writer import *
from zepben.evolve.database.sqlite.writers.diagram_service_writer import *
from zepben.evolve.database.sqlite.database_writer import *
from zepben.evolve.database.sqlite.readers.result_set import ResultSet
from zepben.evolve.database.sqlite.readers.base_cim_reader import *
from zepben.evolve.database.sqlite.readers.base_service_reader import *
from zepben.evolve.database.sqlite.readers.customer_cim_reader import *
from zepben.evolve.database.sqlite.readers.customer_service_reader import *
from zepben.evolve.database.sqlite.readers.diagram_cim_reader import *
from zepben.evolve.database.sqlite.readers.diagram_service_reader import *
from zepben.evolve.database.sqlite.readers.metadata_entry_reader import *
from zepben.evolve.database.sqlite.readers.metadata_collection_reader import *
from zepben.evolve.database.sqlite.readers.network_cim_reader import *
from zepben.evolve.database.sqlite.readers.network_service_reader import *
from zepben.evolve.database.sqlite.database_reader import *
from zepben.evolve.testing.test_network_builder import *
from zepben.evolve.testing.test_traversal import * | zepben.evolve | /zepben.evolve-0.35.0b2-py3-none-any.whl/zepben/evolve/__init__.py | __init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.