code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
try: # >= python3.8 from functools import cached_property except ImportError: # copied from django.utils.functional.cached_property class cached_property: """ Decorator that converts a method with a single self argument into a property cached on the instance. A cached property can be made out of an existing method: (e.g. ``url = cached_property(get_absolute_url)``). """ name = None @staticmethod def func(instance): raise TypeError( "Cannot use cached_property instance without calling " "__set_name__() on it." ) def __init__(self, func): self.real_func = func self.__doc__ = getattr(func, "__doc__") def __set_name__(self, owner, name): if self.name is None: self.name = name self.func = self.real_func elif name != self.name: raise TypeError( "Cannot assign the same cached_property to two different names " "(%r and %r)." % (self.name, name) ) def __get__(self, instance, cls=None): """ Call the function and put the return value in instance.__dict__ so that subsequent attribute access on the instance returns the cached value instead of calling cached_property.__get__(). """ if instance is None: return self res = instance.__dict__[self.name] = self.func(instance) return res # copied from django.utils.functional.classproperty class classproperty: """ Decorator that converts a method with a single cls argument into a property that can be accessed directly from the class. """ def __init__(self, method=None): self.fget = method def __get__(self, instance, cls=None): return self.fget(cls) def getter(self, method): self.fget = method return self
yz-core2
/yz-core2-1.0.61b2.tar.gz/yz-core2-1.0.61b2/yzcore/utils/decorator.py
decorator.py
""" Django's standard crypto functions and utilities. """ import hashlib import hmac import random import time from .encoding import force_bytes # from yzcore.core.default_settings import get_settings # # settings = get_settings() # Use the system PRNG if possible try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: import warnings warnings.warn('A secure pseudo-random number generator is not available ' 'on your system. Falling back to Mersenne Twister.') using_sysrandom = False def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Return a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ # if not using_sysrandom: # # This is ugly, and a hack, but it makes things better than # # the alternative of predictability. This re-seeds the PRNG # # using a value that is hard for an attacker to predict, every # # time a random string is required. This may change the # # properties of the chosen random sequence slightly, but this # # is better than absolute predictability. # random.seed( # hashlib.sha256( # ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode() # ).digest() # ) return ''.join(random.choice(allowed_chars) for i in range(length)) def constant_time_compare(val1, val2): """Return True if the two strings are equal, False otherwise.""" return hmac.compare_digest(force_bytes(val1), force_bytes(val2)) def pbkdf2(password, salt, iterations, dklen=0, digest=None): """Return the hash of password using pbkdf2.""" if digest is None: digest = hashlib.sha256 dklen = dklen or None password = force_bytes(password) salt = force_bytes(salt) return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
yz-core2
/yz-core2-1.0.61b2.tar.gz/yz-core2-1.0.61b2/yzcore/utils/crypto.py
crypto.py
import asyncio from concurrent import futures from socket import AF_INET from typing import TypeVar, Union, Optional, List, Dict, AnyStr try: import json as _json except (ImportError, ModuleNotFoundError): import json as _json try: import aiohttp from pydantic import BaseModel, Field except (ImportError, ModuleNotFoundError): AioHttpParams = List[Dict[str, Union[str, int, Dict[str, Union[str, int]]]]] else: class AioHttpParams(BaseModel): method: AnyStr url: AnyStr params: Optional[Dict] data: Optional[Dict] json_: Optional[Dict] = Field(alias='json') headers: Optional[Dict] timeout: Optional[int] RequestParams = TypeVar("RequestParams", bound=AioHttpParams) SIZE_POOL_AIOHTTP = 100 CONCURRENCY = 100 # 限制并发量为1024 TIMEOUT_KEEP_ALIVE = 5 # 取决于用的web服务器设置的tcp keepalive时长,uvicorn默认5秒 class AioHTTP: """ 注意: 在FastAPI中使用时,在事件处理的勾子中全局设置 AioHTTP 的开启和关闭: app = FastAPI( on_startup=[AioHTTP.on_startup], on_shutdown=[AioHTTP.on_shutdown] ) """ semaphore: asyncio.Semaphore = asyncio.Semaphore(CONCURRENCY) session: aiohttp.ClientSession = None # def __init__(self, cookies=None, json_serialize=_json.dumps): # self.session = aiohttp.ClientSession( # cookies=cookies, # json_serialize=json_serialize # ) @classmethod def get_session(cls, cookies=None, json_serialize=_json.dumps) -> aiohttp.ClientSession: if cls.session is None or cls.session.closed: timeout = aiohttp.ClientTimeout(total=2) connector = aiohttp.TCPConnector( family=AF_INET, limit_per_host=SIZE_POOL_AIOHTTP, keepalive_timeout=TIMEOUT_KEEP_ALIVE ) cls.session = aiohttp.ClientSession( timeout=timeout, connector=connector, cookies=cookies, json_serialize=json_serialize, ) return cls.session @classmethod async def get(cls, url, params=None, data=None, json=None, headers=None, timeout=30, **kwargs): """异步GET请求""" return await cls.fetch( 'get', url, params, data, json, headers, timeout, **kwargs) @classmethod async def post(cls, url, params=None, data=None, json=None, headers=None, timeout=30, **kwargs): """异步POST请求""" return await cls.fetch( 'post', url, params, data, json, headers, timeout, **kwargs) @classmethod async def put(cls, url, params=None, data=None, json=None, headers=None, timeout=30, **kwargs): """异步PUT请求""" return await cls.fetch( 'put', url, params, data, json, headers, timeout, **kwargs) @classmethod async def patch(cls, url, params=None, data=None, json=None, headers=None, timeout=30, **kwargs): """异步PATCH请求""" return await cls.fetch( 'patch', url, params, data, json, headers, timeout, **kwargs) @classmethod async def delete(cls, url, params=None, data=None, json=None, headers=None, timeout=30, **kwargs): """异步DELETE请求""" return await cls.fetch( 'delete', url, params, data, json, headers, timeout, **kwargs) @classmethod async def fetch( cls, method: str, url: str, params=None, data=None, json=None, headers=None, timeout=30, is_close_sesion: bool = False, **kwargs ): """ 公共请求调用方法 :param method: 请求方法 :param url: 请求路由 :param params: 请求参数 :param data: 请求的Form表单参数 :param json: 请求的Json参数 :param headers: 请求头参数 :param timeout: 超时时间 :param is_close_sesion: 是否关闭Session :return: """ client_session = cls.get_session() __request = getattr(client_session, method.lower()) if params: params = {key: str(value) for key, value in params.items() if value is not None} async with cls.semaphore: try: async with __request( url, params=params, data=data, json=json, headers=headers, timeout=timeout, **kwargs ) as response: if response.content_type == 'application/json': result = await response.json() elif response.content_type == 'text/plain': result = await response.text() # elif response.content_type == 'application/octet=stream': # result = await response.read() else: result = await response.read() except Exception as e: import traceback traceback.print_exc() return {'detail': e}, 500 else: if is_close_sesion: await cls.session.close() return result, response.status @classmethod async def bulk_request(cls, querys: List[RequestParams]): """ 异步批量请求 :param querys: [ {'method': 'get', 'url': 'http://httpbin.org/get', 'params': {'key': 'value{}'.format(1)}}, {'method': 'get', 'url': 'http://httpbin.org/get', 'params': {'key': 'value{}'.format(2)}}, {'method': 'get', 'url': 'http://httpbin.org/get', 'params': {'key': 'value{}'.format(3)}}, {'method': 'get', 'url': 'http://httpbin.org/get', 'params': {'key': 'value{}'.format(4)}}, {'method': 'get', 'url': 'http://httpbin.org/get', 'params': {'key': 'value{}'.format(5)}}, {'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'key': 'value{}'.format(6)}}, {'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'key': 'value{}'.format(7)}}, {'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'key': 'value{}'.format(8)}}, {'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'key': 'value{}'.format(9)}}, {'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'key': 'value{}'.format(10)}}, ] :return: """ tasks = [asyncio.ensure_future(cls.fetch(**kw)) for kw in querys] responses = await asyncio.gather(*tasks) return responses @classmethod async def close(cls): if cls.session: await cls.session.close() @classmethod async def on_startup(cls): cls.get_session() @classmethod async def on_shutdown(cls): await cls.close() def request(method: str, url: str, params=None, data=None, json=None, headers=None, timeout=30): # _func = getattr(AioHTTP, method.lower()) loop = asyncio.get_event_loop() result = loop.run_until_complete( AioHTTP.fetch( method, url, params, data, json, headers, timeout, is_close_sesion=True) ) return result if __name__ == '__main__': resp = request('get', 'http://httpbin.org/get') print(111, resp)
yz-core2
/yz-core2-1.0.61b2.tar.gz/yz-core2-1.0.61b2/yzcore/request/aio_http.py
aio_http.py
# readme-template -------------- ## Introduction yzcore 目的为了开发后端服务时,提供一种代码结构规范参考。 可以通过`startproject`和`startapp`两个命令快速创建工程和内部的接口应用模块。 **安装模块** ```shell $ pip install yz-core ``` 示例: - 创建工程: ```shell $ yzcore startproject myproject ``` - 创建工程内部应用: ```shell $ yzcore startapp myapp ./src/apps/ ``` 代码结构介绍: ``` . ├── docs 说明文档、接口文档等文档的存放目录 ├── migrations 数据表迁移文件存放目录 ├── src │   ├── apps 接口应用程序的主目录 │   │   ├── __init__.py │   │   ├── myapp01 │   │   │   ├── __init__.py │   │   │   ├── controllers.py 控制层:封装数据交互操作 │   │   │   ├── models.py 模型层:实现数据表与模型的定义 │   │   │   ├── schemas.py 模式层:定义接口数据参数 │   │   │   ├── tests.py 测试文件 │   │   │   └── views.py 视图层:接口定义层 │   │   └── myapp02 │   ├── conf 配置文件的存放目录 │   ├── const 公共常量存放目录 │   ├── tests 测试文件的存放目录 │   ├── main.py 程序的入口文件 │   ├── settings.py 程序的设置文件 │   └── utils 抽离出的公共代码模块存放目录 ├── .gitignore ├── requirements.txt └── README.md ``` ## Quick start Quick Start 部分主要包括两部分内容:简易的安装部署说明(Deployment)和使用案例(Example)。特别是对于一些基础库,必须包括Example模块。 ## Documentation Documentation 部分是核心的文档,对于大型项目可以使用超链接,如使用以下这种形式: For the full story, head over to the [documentation](https://git.k8s.io/community/contributors/devel#readme). ## 数据库迁移操作 ``` # pip install alembic alembic init migrations # 创建迁移环境 alembic revision --autogenerate -m "commit content" # 自动生成迁移文件 alembic upgrade head # 升级到最近版本 alembic upgrade <revision_id> # 升级到指定版本 alembic downgrade <revision_id> # 回退到指定版本 ```
yz-core2
/yz-core2-1.0.61b2.tar.gz/yz-core2-1.0.61b2/yzcore/templates/project_template/README.md
README.md
yzconfig ======== ![build](https://travis-ci.org/ykshatroff/yzconfig.svg?branch=master) Simple application configuration tool for Django (and others) Summary ------- `yzconfig` allows you to: * Define all settings for all of your Django project's applications in one python object (usually, a module) * Use name prefixes to instantiate the settings object of an application Usage ----- `yzconfig` takes an arbitrary object and populates `settings` with values from its attributes whose names are constructed as `prefix + attr` where `attr` is a `settings` class attribute and `prefix` is given as argument to `settings` constructor. An application's settings are defined in a class which inherits from `YzConfig`, then a settings object is instantiated with the desired prefix: ```python from yzconfig import YzConfig class Settings(YzConfig): VALUE = "default" _SKIPPED_VALUE = 'skipped' settings = Settings('TEST_') ``` If your Django settings contain a `TEST_VALUE` property, then the `settings` object's `VALUE` will contain its value, otherwise it will remain with `"default"`. Attributes beginning with `_` will not be overwritten. `yzconfig` can be used with Django or standalone. For the latter case, it's possible to provide a python dotted path to the settings object in `YZCONFIG_MODULE` environment variable. The default is to import `settings`. To be used with Django, no extra actions are required.
yzconfig
/yzconfig-1.0-py3-none-any.whl/yzconfig-1.0.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
The main goal of this Python library is to propose an object to emulate Year Zero Engine dice throwing. # System supported: - [X] Mutant: Year Zero - [X] Forbidden Lands - [ ] Twilight 2000 - [X] Alien - [ ] Blade Runner # Example ``` . my_py_venv/bin/activate git clone https://github.com/nlegrand/yze.git cd yze python -m pip install -e . python Python 3.11.3 (main, Apr 8 2023, 02:16:51) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from yze.dice import MutantDicePool >>> d = MutantDicePool(attr=3, skill=2, gear=2) >>> d.throw() {'attr': [5, 6, 6], 'skill': [1, 4], 'gear': [6, 2]} >>> d.push() {'attr': [2, 6, 6], 'skill': [5, 2], 'gear': [6, 1]} >>> from yze.dice import FBLDicePool >>> fbl = FBLDicePool(attr=2, skill=1, artefact=12) >>> fbl.throw() {'attr': [2, 2], 'skill': [2], 'gear': [], 'artefact': (8, 2)} >>> fbl.push() {'attr': [2, 6], 'skill': [3], 'gear': [], 'artefact': (8, 2)} >>> from yze.dice import AlienDicePool >>> alien = AlienDicePool(pool=4, stress=1) >>> alien.throw() {'pool': [4, 1, 6, 1], 'stress': [2]} >>> alien.push() {'pool': [1, 3, 6, 2], 'stress': [1, 1]} ``` # Benchmark You can also benchmark dice throw to see what are your chances to get some successes or damage. ``` benchmark_mutant --throw 10000 --attribute 4 --skill 2 --gear 1 Throwing dice 10000 times ! at least one success : 7243 at least one pushed success : 9096 at least one damage to attribute : 7245 at least one damage to gear : 2767 { 'atleast_one': 7243, 'atleast_one_attr_botch': 7245, 'atleast_one_gear_botch': 2767, 'atleast_one_pushed': 9096, 'attribute_botched': {1: 4158, 2: 2404, 3: 622, 4: 61}, 'gear_botched': {1: 2767}, 'pushed_successes': {1: 2666, 2: 3304, 3: 2070, 4: 843, 5: 194, 6: 19}, 'successes': {1: 3895, 2: 2424, 3: 757, 4: 154, 5: 13}} ``` Yes I know, I can improve this output :). I'll do it!
yze
/yze-0.0.1.tar.gz/yze-0.0.1/README.md
README.md
# 云账户 SDK for Python 欢迎使用云账户 SDK for Python。 云账户是一家专注为平台企业和新就业形态劳动者提供高质量灵活就业服务的新时代企业。云账户 SDK 对云账户综合服务平台 API 接口进行封装,让您不必关心过多参数请求,帮助您快速接入到云账户综合服务平台。云账户 SDK for Python 为您提供签约、下单、回调、数据查询等功能,帮助您完成与云账户综合服务平台的接口对接及业务开发。 如果您在使用过程中遇到任何问题,欢迎在当前 GitHub 提交 Issues,或发送邮件至技术支持组 [[email protected]](mailto:[email protected])。 ### 环境要求 云账户 SDK for Python 支持 Python3 及其以上版本。 ### 配置密钥 #### 1、获取配置 使用云账户 SDK for Python 前,您需先获取 dealer_id、broker_id、3DES Key、App Key 信息。 获取方式:使用开户邮件中的账号登录【[云账户综合服务平台](https://service.yunzhanghu.com/user/login)】,选择“业务中心 > 业务管理 > 对接信息”,查看并获取以上配置信息。 ![获取配置信息](https://infra-engineering-yos-prod.obs.cn-north-1.myhuaweicloud.com/3edacfcb8f2f689d3ee6e9e7aba983139a8ec869-duijiexinxi.png) #### 2、生成密钥 - 方式一:使用 OpenSSL 生成 RSA 公私钥 ``` ① ⽣成私钥 private_key.pem Openssl-> genrsa -out private_key.pem 2048 位 // 建议密钥⻓度⾄少为 2048 位 OpenSSL-> pkcs8 -topk8 -inform PEM -in private_key.pem -outform PEM -nocrypt -out private_key_pkcs8.pem // 将私钥转为 PKCS8 格式 ② ⽣成公钥⽂件 pubkey.pem Openssl-> rsa -in private_key.pem -pubout -out pubkey.pem ``` - 方式二:使用工具生成 请联系云账户技术支持获取 RSA 密钥生成工具 #### 3、配置密钥 登录【[云账户综合服务平台](https://service.yunzhanghu.com/user/login)】,选择“业务中心 > 业务管理 > 对接信息”,单击页面右上角的“编辑”,配置平台企业公钥。 ![配置平台企业公钥信息](https://infra-engineering-yos-prod.obs.cn-north-1.myhuaweicloud.com/6cfd4c1c6560b7ae99d5c3cb358aea23b9433c58-dujiexinxi-2.png) ### 安装Python SDK 1、pip install yzh_py 如有特殊需求需要源码,请联系云账户技术支持。 ### 快速使用 #### 示例 ``` from yzh_py.client.api.model.payment import GetOrderRequest from yzh_py.client.api.payment_client import PaymentClient from yzh_py.config import * if __name__ == "__main__": config = Config( host="https://api-service.yunzhanghu.com", dealer_id="", sign_type="", app_key="", des3key="", private_key="", public_key="", ) # 获取订单详情 request = GetOrderRequest( order_id="", channel="微信", data_type="encryption" ) client = PaymentClient(config) resp = client.get_order(request) print(resp.code, resp.message, resp.data) ```
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/README.md
README.md
from __future__ import absolute_import, unicode_literals import abc import base64 import hashlib import hmac import json import random import time import pyDes import rsa from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5 class Encrypt(abc.ABC): @abc.abstractmethod def encrypt(self, data): return NotImplemented @abc.abstractmethod def sign(self, mess, timestamp, data): return NotImplemented @abc.abstractmethod def encrypt_type(self): return NotImplemented def decrypt(des3key, data): data = bytes(data, encoding="utf8") key = bytes(des3key[0:8], encoding="utf8") return pyDes.triple_des(des3key, pyDes.CBC, key, pad=None, padmode=pyDes.PAD_PKCS5).decrypt(base64.b64decode(data)) def verify_sign_rsa(public_key, app_key, data, mess, timestamp, signature): sign_pairs = "data=" + data + "&mess=" + mess + "&timestamp=" + timestamp + "&key=" + app_key rsa.verify(sign_pairs, signature, public_key) def verify_sign_hmac(des3key, app_key, data, mess, timestamp, signature): sign_pairs = "data=%s&mess=%s&timestamp=%d&key=%s" % (data, mess, timestamp, app_key) return hmac.new(app_key.encode('utf-8'), msg=sign_pairs, digestmod=hashlib.sha256).hexdigest() == signature def gen_key(): x = RSA.generate(2048) s_key = x.export_key() # 私钥 g_key = x.publickey().export_key() # 公钥 public_key = g_key.decode("utf-8") private_key = s_key.decode("utf-8") return public_key, private_key class EncryptHmac(Encrypt): def __init__(self, app_key, des3key): self.__app_key = app_key self.__des3key = des3key def encrypt_type(self): return "sha256" def encrypt(self, data): data = bytes(data, encoding="utf8") key = bytes(self.__des3key[0:8], encoding="utf8") return base64.b64encode( pyDes.triple_des(self.__des3key, pyDes.CBC, key, pad=None, padmode=pyDes.PAD_PKCS5).encrypt(data)) def sign(self, mess, timestamp, encrypt_data): signPairs = "data=%s&mess=%s&timestamp=%d&key=%s" % ( str(encrypt_data, encoding="utf-8"), mess, timestamp, self.__app_key) app_key = bytes(self.__app_key, encoding="utf8") signPairs = bytes(signPairs, encoding="utf8") return hmac.new(app_key, msg=signPairs, digestmod=hashlib.sha256).hexdigest() class EncryptRsa(Encrypt): def __init__(self, app_key, public_key, private_key, des3key): self.__public_key = RSA.importKey(public_key) self.__private_key = RSA.importKey(private_key) self.__app_key = app_key self.__des3key = des3key def encrypt_type(self): return "rsa" def encrypt(self, data): data = bytes(data, encoding="utf8") key = bytes(self.__des3key[0:8], encoding="utf8") return base64.b64encode( pyDes.triple_des(self.__des3key, pyDes.CBC, key, pad=None, padmode=pyDes.PAD_PKCS5).encrypt(data)) def sign(self, mess, timestamp, encrypt_data): sign_pairs = "data=%s&mess=%s&timestamp=%d&key=%s" % ( bytes.decode(encrypt_data), mess, timestamp, self.__app_key) signer = Signature_pkcs1_v1_5.new(self.__private_key) digest = SHA256.new() digest.update(sign_pairs.encode("utf8")) sign = signer.sign(digest) return base64.b64encode(sign) class ReqMessage(object): """ ReqMessage 请求消息体 """ def __init__(self, encrypt, data): """ :param encrypt: 加密方式 :type data: {} 请求信息 :param data: 请求信息 """ self.__encrypt = encrypt self.data = None if data is not None: self.data = json.dumps(data, ensure_ascii=False) def pack(self): if self.data is None: return None timestamp = int(time.time()) mess = ''.join(random.sample('1234567890abcdefghijklmnopqrstuvwxy', 10)) encrypt_data = self.__encrypt.encrypt(self.data) return { "data": encrypt_data, "mess": mess, 'timestamp': timestamp, "sign": self.__encrypt.sign(mess, timestamp, encrypt_data), "sign_type": self.__encrypt.encrypt_type() } class RespMessage(object): """ RespMessage 返回信息 """ def __init__(self, des3key, content, req_data, req_param, headers): self.__des3key = des3key self.__content = content dic = json.loads(content) self.__req_param = req_param self.__req_data = req_data self.__code = dic['code'] if 'code' in dic else None self.__message = dic['message'] if 'message' in dic else None self.__data = dic['data'] if 'data' in dic else None self.__request_id = headers['request-id'] def decrypt(self): if self.__data is None: return self if self.__des3key is not None and self.__req_param is not None \ and 'data_type' in self.__req_param and \ self.__req_param['data_type'] == 'encryption': self.__data = json.loads(decrypt(self.__des3key, self.__data)) return self @property def code(self): return self.__code @property def message(self): return self.__message @property def data(self): return self.__data @property def content(self): return self.__content @property def request_id(self): return self.__request_id
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/message.py
message.py
import platform import uuid import requests from .. import __version__ from ..message import * class BaseClient(object): def __init__(self, config, timeout=30): """ :type config: Config :param config: 配置信息 :type timeout: int :param timeout: 非必填 """ encrypt_type = config.sign_type if encrypt_type != "sha256" and encrypt_type != "rsa": raise ValueError('wrong encrypt type') self.__des3key = config.des3key self.__encrypt = None if encrypt_type == "sha256": self.__encrypt = EncryptHmac( config.app_key, config.des3key) if encrypt_type == "rsa": self.__encrypt = EncryptRsa( config.app_key, config.public_key, config.private_key, config.des3key) self.__dealer_id = config.dealer_id self.__base_url = config.host self.__timeout = timeout def __header(self, request_id): if type(request_id) is not str or request_id == "": request_id = str(int(time.time())) return { 'dealer-id': self.__dealer_id, 'request-id': request_id, "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "yunzhanghu-sdk-python/%s/%s/%s" % ( __version__, platform.platform(), platform.python_version()), } def __request(self, method, url, **kwargs): data = kwargs['data'] if 'data' in kwargs else None param = kwargs['param'] if 'param' in kwargs else None headers = self.__header(kwargs['request_id']) return self.__handle_resp( data, param, headers, requests.request(method=method, url=self.__base_url + url, headers=headers, data=ReqMessage(self.__encrypt, data).pack(), params=ReqMessage(self.__encrypt, param).pack(), timeout=self.__timeout)) def _post(self, url, request_id, data): kwargs = {'data': data, 'request_id': request_id} return self.__request(method='POST', url=url, **kwargs) def _get(self, url, request_id, param): kwargs = {'param': param, 'request_id': request_id} return self.__request(method='GET', url=url, **kwargs) def __handle_resp(self, req_data, req_param, headers, resp): if resp is None: raise ValueError('resp is None') # 抛出status异常 resp.raise_for_status() return RespMessage(self.__des3key, resp.text, req_data, req_param, headers).decrypt() class BaseRequest(object): def __init__(self): self.__request_id = uuid.uuid1() @property def request_id(self): """ Get 请求ID :return: str, dealer_id """ if self.__request_id is None or self.__request_id == "": self.__request_id = uuid.uuid1() return self.__request_id.__str__() @request_id.setter def request_id(self, request_id): """ Set 请求ID :type request_id: str :param request_id: 请求ID """ self.__request_id = request_id
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/base.py
base.py
from .model.dataservice import * from ..base import * from ...utils import * class DataserviceClient(BaseClient): def __init__(self, config): super().__init__(config) def list_daily_order(self, request: ListDailyOrderRequest): """ 查询日订单数据 :type request: ListDailyOrderRequest :param request: the ListDailyOrderRequest request parameters class. :return: ListDailyOrderResponse """ return self._get("/api/dataservice/v1/orders", request.request_id, Utils.copy_dict(request.__dict__)) def get_daily_order_file(self, request: GetDailyOrderFileRequest): """ 查询日订单文件 :type request: GetDailyOrderFileRequest :param request: the GetDailyOrderFileRequest request parameters class. :return: GetDailyOrderFileResponse """ return self._get("/api/dataservice/v1/order/downloadurl", request.request_id, Utils.copy_dict(request.__dict__)) def get_daily_order_file_v2(self, request: GetDailyOrderFileV2Request): """ 查询日订单文件(支付和退款订单) :type request: GetDailyOrderFileV2Request :param request: the GetDailyOrderFileV2Request request parameters class. :return: GetDailyOrderFileV2Response """ return self._get("/api/dataservice/v1/order/day/url", request.request_id, Utils.copy_dict(request.__dict__)) def list_daily_bill(self, request: ListDailyBillRequest): """ 查询日流水数据 :type request: ListDailyBillRequest :param request: the ListDailyBillRequest request parameters class. :return: ListDailyBillResponse """ return self._get("/api/dataservice/v1/bills", request.request_id, Utils.copy_dict(request.__dict__)) def get_daily_bill_file_v2(self, request: GetDailyBillFileV2Request): """ 查询日流水文件 :type request: GetDailyBillFileV2Request :param request: the GetDailyBillFileV2Request request parameters class. :return: GetDailyBillFileV2Response """ return self._get("/api/dataservice/v2/bill/downloadurl", request.request_id, Utils.copy_dict(request.__dict__)) def list_dealer_recharge_record_v2(self, request: ListDealerRechargeRecordV2Request): """ 查询平台企业预付业务服务费记录 :type request: ListDealerRechargeRecordV2Request :param request: the ListDealerRechargeRecordV2Request request parameters class. :return: ListDealerRechargeRecordV2Response """ return self._get("/api/dataservice/v2/recharge-record", request.request_id, Utils.copy_dict(request.__dict__)) def list_balance_daily_statement(self, request: ListBalanceDailyStatementRequest): """ 获取余额日账单 :type request: ListBalanceDailyStatementRequest :param request: the ListBalanceDailyStatementRequest request parameters class. :return: ListBalanceDailyStatementResponse """ return self._get("/api/dataservice/v1/statements-daily", request.request_id, Utils.copy_dict(request.__dict__))
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/dataservice_client.py
dataservice_client.py
from .model.authentication import * from ..base import * from ...utils import * class AuthenticationClient(BaseClient): def __init__(self, config): super().__init__(config) def bank_card_four_auth_verify(self, request: BankCardFourAuthVerifyRequest): """ 银行卡四要素鉴权请求(下发短信验证码) :type request: BankCardFourAuthVerifyRequest :param request: the BankCardFourAuthVerifyRequest request parameters class. :return: BankCardFourAuthVerifyResponse """ return self._post("/authentication/verify-request", request.request_id, Utils.copy_dict(request.__dict__)) def bank_card_four_auth_confirm(self, request: BankCardFourAuthConfirmRequest): """ 银行卡四要素确认鉴权(上传短信验证码) :type request: BankCardFourAuthConfirmRequest :param request: the BankCardFourAuthConfirmRequest request parameters class. :return: BankCardFourAuthConfirmResponse """ return self._post("/authentication/verify-confirm", request.request_id, Utils.copy_dict(request.__dict__)) def bank_card_four_verify(self, request: BankCardFourVerifyRequest): """ 银行卡四要素验证 :type request: BankCardFourVerifyRequest :param request: the BankCardFourVerifyRequest request parameters class. :return: BankCardFourVerifyResponse """ return self._post("/authentication/verify-bankcard-four-factor", request.request_id, Utils.copy_dict(request.__dict__)) def bank_card_three_verify(self, request: BankCardThreeVerifyRequest): """ 银行卡三要素验证 :type request: BankCardThreeVerifyRequest :param request: the BankCardThreeVerifyRequest request parameters class. :return: BankCardThreeVerifyResponse """ return self._post("/authentication/verify-bankcard-three-factor", request.request_id, Utils.copy_dict(request.__dict__)) def i_d_card_verify(self, request: IDCardVerifyRequest): """ 身份证实名验证 :type request: IDCardVerifyRequest :param request: the IDCardVerifyRequest request parameters class. :return: IDCardVerifyResponse """ return self._post("/authentication/verify-id", request.request_id, Utils.copy_dict(request.__dict__)) def user_exempted_info(self, request: UserExemptedInfoRequest): """ 上传免验证用户名单信息 :type request: UserExemptedInfoRequest :param request: the UserExemptedInfoRequest request parameters class. :return: UserExemptedInfoResponse """ return self._post("/api/payment/v1/user/exempted/info", request.request_id, Utils.copy_dict(request.__dict__)) def user_white_check(self, request: UserWhiteCheckRequest): """ 查看免验证用户名单是否存在 :type request: UserWhiteCheckRequest :param request: the UserWhiteCheckRequest request parameters class. :return: UserWhiteCheckResponse """ return self._post("/api/payment/v1/user/white/check", request.request_id, Utils.copy_dict(request.__dict__)) def get_bank_card_info(self, request: GetBankCardInfoRequest): """ 银行卡信息查询接口 :type request: GetBankCardInfoRequest :param request: the GetBankCardInfoRequest request parameters class. :return: GetBankCardInfoResponse """ return self._get("/api/payment/v1/card", request.request_id, Utils.copy_dict(request.__dict__))
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/authentication_client.py
authentication_client.py
from .model.payment import * from ..base import * from ...utils import * class PaymentClient(BaseClient): def __init__(self, config): super().__init__(config) def create_bankpay_order(self, request: CreateBankpayOrderRequest): """ 银行卡实时下单 :type request: CreateBankpayOrderRequest :param request: the CreateBankpayOrderRequest request parameters class. :return: CreateBankpayOrderResponse """ return self._post("/api/payment/v1/order-bankpay", request.request_id, Utils.copy_dict(request.__dict__)) def create_alipay_order(self, request: CreateAlipayOrderRequest): """ 支付宝实时下单 :type request: CreateAlipayOrderRequest :param request: the CreateAlipayOrderRequest request parameters class. :return: CreateAlipayOrderResponse """ return self._post("/api/payment/v1/order-alipay", request.request_id, Utils.copy_dict(request.__dict__)) def create_wxpay_order(self, request: CreateWxpayOrderRequest): """ 微信实时下单 :type request: CreateWxpayOrderRequest :param request: the CreateWxpayOrderRequest request parameters class. :return: CreateWxpayOrderResponse """ return self._post("/api/payment/v1/order-wxpay", request.request_id, Utils.copy_dict(request.__dict__)) def get_order(self, request: GetOrderRequest): """ 查询单笔订单信息 :type request: GetOrderRequest :param request: the GetOrderRequest request parameters class. :return: GetOrderResponse """ return self._get("/api/payment/v1/query-order", request.request_id, Utils.copy_dict(request.__dict__)) def get_dealer_v_a_recharge_account(self, request: GetDealerVARechargeAccountRequest): """ 查询平台企业汇款信息 :type request: GetDealerVARechargeAccountRequest :param request: the GetDealerVARechargeAccountRequest request parameters class. :return: GetDealerVARechargeAccountResponse """ return self._get("/api/payment/v1/va-account", request.request_id, Utils.copy_dict(request.__dict__)) def list_account(self, request: ListAccountRequest): """ 查询平台企业余额 :type request: ListAccountRequest :param request: the ListAccountRequest request parameters class. :return: ListAccountResponse """ return self._get("/api/payment/v1/query-accounts", request.request_id, Utils.copy_dict(request.__dict__)) def get_ele_receipt_file(self, request: GetEleReceiptFileRequest): """ 查询电子回单 :type request: GetEleReceiptFileRequest :param request: the GetEleReceiptFileRequest request parameters class. :return: GetEleReceiptFileResponse """ return self._get("/api/payment/v1/receipt/file", request.request_id, Utils.copy_dict(request.__dict__)) def cancel_order(self, request: CancelOrderRequest): """ 取消待支付订单 :type request: CancelOrderRequest :param request: the CancelOrderRequest request parameters class. :return: CancelOrderResponse """ return self._post("/api/payment/v1/order/fail", request.request_id, Utils.copy_dict(request.__dict__)) def create_batch_order(self, request: CreateBatchOrderRequest): """ 批次下单 :type request: CreateBatchOrderRequest :param request: the CreateBatchOrderRequest request parameters class. :return: CreateBatchOrderResponse """ return self._post("/api/payment/v1/order-batch", request.request_id, Utils.copy_dict(request.__dict__)) def confirm_batch_order(self, request: ConfirmBatchOrderRequest): """ 批次确认 :type request: ConfirmBatchOrderRequest :param request: the ConfirmBatchOrderRequest request parameters class. :return: ConfirmBatchOrderResponse """ return self._post("/api/payment/v1/confirm-batch", request.request_id, Utils.copy_dict(request.__dict__))
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/payment_client.py
payment_client.py
from .model.invoice import * from ..base import * from ...utils import * class InvoiceClient(BaseClient): def __init__(self, config): super().__init__(config) def get_invoice_stat(self, request: GetInvoiceStatRequest): """ 查询平台企业已开具和待开具发票金额 :type request: GetInvoiceStatRequest :param request: the GetInvoiceStatRequest request parameters class. :return: GetInvoiceStatResponse """ return self._get("/api/payment/v1/invoice-stat", request.request_id, Utils.copy_dict(request.__dict__)) def get_invoice_amount(self, request: GetInvoiceAmountRequest): """ 查询可开票额度和开票信息 :type request: GetInvoiceAmountRequest :param request: the GetInvoiceAmountRequest request parameters class. :return: GetInvoiceAmountResponse """ return self._post("/api/invoice/v2/invoice-amount", request.request_id, Utils.copy_dict(request.__dict__)) def apply_invoice(self, request: ApplyInvoiceRequest): """ 开票申请 :type request: ApplyInvoiceRequest :param request: the ApplyInvoiceRequest request parameters class. :return: ApplyInvoiceResponse """ return self._post("/api/invoice/v2/apply", request.request_id, Utils.copy_dict(request.__dict__)) def get_invoice_status(self, request: GetInvoiceStatusRequest): """ 查询开票申请状态 :type request: GetInvoiceStatusRequest :param request: the GetInvoiceStatusRequest request parameters class. :return: GetInvoiceStatusResponse """ return self._post("/api/invoice/v2/invoice/invoice-status", request.request_id, Utils.copy_dict(request.__dict__)) def get_invoice_file(self, request: GetInvoiceFileRequest): """ 下载 PDF 版发票 :type request: GetInvoiceFileRequest :param request: the GetInvoiceFileRequest request parameters class. :return: GetInvoiceFileResponse """ return self._post("/api/invoice/v2/invoice/invoice-pdf", request.request_id, Utils.copy_dict(request.__dict__)) def send_reminder_email(self, request: SendReminderEmailRequest): """ 发送发票扫描件压缩包下载链接邮件 :type request: SendReminderEmailRequest :param request: the SendReminderEmailRequest request parameters class. :return: SendReminderEmailResponse """ return self._post("/api/invoice/v2/invoice/reminder/email", request.request_id, Utils.copy_dict(request.__dict__))
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/invoice_client.py
invoice_client.py
from ...base import BaseRequest class GetInvoiceStatRequest(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type year: int :param year: 查询年份 """ def __init__(self, broker_id=None, dealer_id=None, year=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id self.year = year def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_year(self): """ Get 查询年份 :return: int, year """ return self.year def set_year(self, year): """ Set 查询年份 :type year: int :param year: 查询年份 """ self.year = year class GetInvoiceStatResponse(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type invoiced: string :param invoiced: 已开具发票金额 :type not_invoiced: string :param not_invoiced: 待开具发票金额 """ def __init__(self, dealer_id=None, broker_id=None, invoiced=None, not_invoiced=None): super().__init__() self.dealer_id = dealer_id self.broker_id = broker_id self.invoiced = invoiced self.not_invoiced = not_invoiced def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_invoiced(self): """ Get 已开具发票金额 :return: string, invoiced """ return self.invoiced def set_invoiced(self, invoiced): """ Set 已开具发票金额 :type invoiced: string :param invoiced: 已开具发票金额 """ self.invoiced = invoiced def get_not_invoiced(self): """ Get 待开具发票金额 :return: string, not_invoiced """ return self.not_invoiced def set_not_invoiced(self, not_invoiced): """ Set 待开具发票金额 :type not_invoiced: string :param not_invoiced: 待开具发票金额 """ self.not_invoiced = not_invoiced class GetInvoiceAmountRequest(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ def __init__(self, broker_id=None, dealer_id=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id class GetInvoiceAmountResponse(BaseRequest): """ :type amount: string :param amount: 可开票额度 :type bank_name_account: list :param bank_name_account: 系统支持的开户行及账号 :type goods_services_name: list :param goods_services_name: 系统支持的货物或应税劳务、服务名称 """ def __init__(self, amount=None, bank_name_account=None, goods_services_name=None): super().__init__() self.amount = amount self.bank_name_account = bank_name_account self.goods_services_name = goods_services_name def get_amount(self): """ Get 可开票额度 :return: string, amount """ return self.amount def set_amount(self, amount): """ Set 可开票额度 :type amount: string :param amount: 可开票额度 """ self.amount = amount def get_bank_name_account(self): """ Get 系统支持的开户行及账号 :return: list, bank_name_account """ return self.bank_name_account def set_bank_name_account(self, bank_name_account): """ Set 系统支持的开户行及账号 :type bank_name_account: list :param bank_name_account: 系统支持的开户行及账号 """ self.bank_name_account = bank_name_account def get_goods_services_name(self): """ Get 系统支持的货物或应税劳务、服务名称 :return: list, goods_services_name """ return self.goods_services_name def set_goods_services_name(self, goods_services_name): """ Set 系统支持的货物或应税劳务、服务名称 :type goods_services_name: list :param goods_services_name: 系统支持的货物或应税劳务、服务名称 """ self.goods_services_name = goods_services_name class ApplyInvoiceRequest(BaseRequest): """ :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type amount: string :param amount: 申请开票金额 :type invoice_type: string :param invoice_type: 发票类型 :type bank_name_account: string :param bank_name_account: 开户行及账号 :type goods_services_name: string :param goods_services_name: 货物或应税劳务、服务名称 :type remark: string :param remark: 发票备注 """ def __init__(self, invoice_apply_id=None, broker_id=None, dealer_id=None, amount=None, invoice_type=None, bank_name_account=None, goods_services_name=None, remark=None): super().__init__() self.invoice_apply_id = invoice_apply_id self.broker_id = broker_id self.dealer_id = dealer_id self.amount = amount self.invoice_type = invoice_type self.bank_name_account = bank_name_account self.goods_services_name = goods_services_name self.remark = remark def get_invoice_apply_id(self): """ Get 发票申请编号 :return: string, invoice_apply_id """ return self.invoice_apply_id def set_invoice_apply_id(self, invoice_apply_id): """ Set 发票申请编号 :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 """ self.invoice_apply_id = invoice_apply_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_amount(self): """ Get 申请开票金额 :return: string, amount """ return self.amount def set_amount(self, amount): """ Set 申请开票金额 :type amount: string :param amount: 申请开票金额 """ self.amount = amount def get_invoice_type(self): """ Get 发票类型 :return: string, invoice_type """ return self.invoice_type def set_invoice_type(self, invoice_type): """ Set 发票类型 :type invoice_type: string :param invoice_type: 发票类型 """ self.invoice_type = invoice_type def get_bank_name_account(self): """ Get 开户行及账号 :return: string, bank_name_account """ return self.bank_name_account def set_bank_name_account(self, bank_name_account): """ Set 开户行及账号 :type bank_name_account: string :param bank_name_account: 开户行及账号 """ self.bank_name_account = bank_name_account def get_goods_services_name(self): """ Get 货物或应税劳务、服务名称 :return: string, goods_services_name """ return self.goods_services_name def set_goods_services_name(self, goods_services_name): """ Set 货物或应税劳务、服务名称 :type goods_services_name: string :param goods_services_name: 货物或应税劳务、服务名称 """ self.goods_services_name = goods_services_name def get_remark(self): """ Get 发票备注 :return: string, remark """ return self.remark def set_remark(self, remark): """ Set 发票备注 :type remark: string :param remark: 发票备注 """ self.remark = remark class ApplyInvoiceResponse(BaseRequest): """ :type application_id: string :param application_id: 发票申请单 ID :type count: int :param count: 发票张数 """ def __init__(self, application_id=None, count=None): super().__init__() self.application_id = application_id self.count = count def get_application_id(self): """ Get 发票申请单 ID :return: string, application_id """ return self.application_id def set_application_id(self, application_id): """ Set 发票申请单 ID :type application_id: string :param application_id: 发票申请单 ID """ self.application_id = application_id def get_count(self): """ Get 发票张数 :return: int, count """ return self.count def set_count(self, count): """ Set 发票张数 :type count: int :param count: 发票张数 """ self.count = count class GetInvoiceStatusRequest(BaseRequest): """ :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 :type application_id: string :param application_id: 发票申请单 ID """ def __init__(self, invoice_apply_id=None, application_id=None): super().__init__() self.invoice_apply_id = invoice_apply_id self.application_id = application_id def get_invoice_apply_id(self): """ Get 发票申请编号 :return: string, invoice_apply_id """ return self.invoice_apply_id def set_invoice_apply_id(self, invoice_apply_id): """ Set 发票申请编号 :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 """ self.invoice_apply_id = invoice_apply_id def get_application_id(self): """ Get 发票申请单 ID :return: string, application_id """ return self.application_id def set_application_id(self, application_id): """ Set 发票申请单 ID :type application_id: string :param application_id: 发票申请单 ID """ self.application_id = application_id class GetInvoiceStatusResponse(BaseRequest): """ :type status: string :param status: 申请结果 :type count: int :param count: 发票张数 :type price_tax_amount: string :param price_tax_amount: 价税合计 :type price_amount: string :param price_amount: 不含税金额 :type tax_amount: string :param tax_amount: 税额 :type invoice_type: string :param invoice_type: 发票类型 :type customer_name: string :param customer_name: 购方名称 :type customer_tax_num: string :param customer_tax_num: 纳税人识别号 :type customer_address_tel: string :param customer_address_tel: 购方地址、电话 :type bank_name_account: string :param bank_name_account: 开户行及账号 :type goods_services_name: string :param goods_services_name: 货物或应税劳务、服务名称 :type remark: string :param remark: 发票备注 :type post_type: string :param post_type: 邮寄类型 :type waybill_number: list :param waybill_number: 快递单号 """ def __init__(self, status=None, count=None, price_tax_amount=None, price_amount=None, tax_amount=None, invoice_type=None, customer_name=None, customer_tax_num=None, customer_address_tel=None, bank_name_account=None, goods_services_name=None, remark=None, post_type=None, waybill_number=None): super().__init__() self.status = status self.count = count self.price_tax_amount = price_tax_amount self.price_amount = price_amount self.tax_amount = tax_amount self.invoice_type = invoice_type self.customer_name = customer_name self.customer_tax_num = customer_tax_num self.customer_address_tel = customer_address_tel self.bank_name_account = bank_name_account self.goods_services_name = goods_services_name self.remark = remark self.post_type = post_type self.waybill_number = waybill_number def get_status(self): """ Get 申请结果 :return: string, status """ return self.status def set_status(self, status): """ Set 申请结果 :type status: string :param status: 申请结果 """ self.status = status def get_count(self): """ Get 发票张数 :return: int, count """ return self.count def set_count(self, count): """ Set 发票张数 :type count: int :param count: 发票张数 """ self.count = count def get_price_tax_amount(self): """ Get 价税合计 :return: string, price_tax_amount """ return self.price_tax_amount def set_price_tax_amount(self, price_tax_amount): """ Set 价税合计 :type price_tax_amount: string :param price_tax_amount: 价税合计 """ self.price_tax_amount = price_tax_amount def get_price_amount(self): """ Get 不含税金额 :return: string, price_amount """ return self.price_amount def set_price_amount(self, price_amount): """ Set 不含税金额 :type price_amount: string :param price_amount: 不含税金额 """ self.price_amount = price_amount def get_tax_amount(self): """ Get 税额 :return: string, tax_amount """ return self.tax_amount def set_tax_amount(self, tax_amount): """ Set 税额 :type tax_amount: string :param tax_amount: 税额 """ self.tax_amount = tax_amount def get_invoice_type(self): """ Get 发票类型 :return: string, invoice_type """ return self.invoice_type def set_invoice_type(self, invoice_type): """ Set 发票类型 :type invoice_type: string :param invoice_type: 发票类型 """ self.invoice_type = invoice_type def get_customer_name(self): """ Get 购方名称 :return: string, customer_name """ return self.customer_name def set_customer_name(self, customer_name): """ Set 购方名称 :type customer_name: string :param customer_name: 购方名称 """ self.customer_name = customer_name def get_customer_tax_num(self): """ Get 纳税人识别号 :return: string, customer_tax_num """ return self.customer_tax_num def set_customer_tax_num(self, customer_tax_num): """ Set 纳税人识别号 :type customer_tax_num: string :param customer_tax_num: 纳税人识别号 """ self.customer_tax_num = customer_tax_num def get_customer_address_tel(self): """ Get 购方地址、电话 :return: string, customer_address_tel """ return self.customer_address_tel def set_customer_address_tel(self, customer_address_tel): """ Set 购方地址、电话 :type customer_address_tel: string :param customer_address_tel: 购方地址、电话 """ self.customer_address_tel = customer_address_tel def get_bank_name_account(self): """ Get 开户行及账号 :return: string, bank_name_account """ return self.bank_name_account def set_bank_name_account(self, bank_name_account): """ Set 开户行及账号 :type bank_name_account: string :param bank_name_account: 开户行及账号 """ self.bank_name_account = bank_name_account def get_goods_services_name(self): """ Get 货物或应税劳务、服务名称 :return: string, goods_services_name """ return self.goods_services_name def set_goods_services_name(self, goods_services_name): """ Set 货物或应税劳务、服务名称 :type goods_services_name: string :param goods_services_name: 货物或应税劳务、服务名称 """ self.goods_services_name = goods_services_name def get_remark(self): """ Get 发票备注 :return: string, remark """ return self.remark def set_remark(self, remark): """ Set 发票备注 :type remark: string :param remark: 发票备注 """ self.remark = remark def get_post_type(self): """ Get 邮寄类型 :return: string, post_type """ return self.post_type def set_post_type(self, post_type): """ Set 邮寄类型 :type post_type: string :param post_type: 邮寄类型 """ self.post_type = post_type def get_waybill_number(self): """ Get 快递单号 :return: list, waybill_number """ return self.waybill_number def set_waybill_number(self, waybill_number): """ Set 快递单号 :type waybill_number: list :param waybill_number: 快递单号 """ self.waybill_number = waybill_number class BankNameAccount(BaseRequest): """ :type item: string :param item: 开户行及账号 :type default: bool :param default: 是否为默认值 """ def __init__(self, item=None, default=None): super().__init__() self.item = item self.default = default def get_item(self): """ Get 开户行及账号 :return: string, item """ return self.item def set_item(self, item): """ Set 开户行及账号 :type item: string :param item: 开户行及账号 """ self.item = item def get_default(self): """ Get 是否为默认值 :return: bool, default """ return self.default def set_default(self, default): """ Set 是否为默认值 :type default: bool :param default: 是否为默认值 """ self.default = default class GoodsServicesName(BaseRequest): """ :type item: string :param item: 货物或应税劳务、服务名称 :type default: bool :param default: 是否为默认值 """ def __init__(self, item=None, default=None): super().__init__() self.item = item self.default = default def get_item(self): """ Get 货物或应税劳务、服务名称 :return: string, item """ return self.item def set_item(self, item): """ Set 货物或应税劳务、服务名称 :type item: string :param item: 货物或应税劳务、服务名称 """ self.item = item def get_default(self): """ Get 是否为默认值 :return: bool, default """ return self.default def set_default(self, default): """ Set 是否为默认值 :type default: bool :param default: 是否为默认值 """ self.default = default class GetInvoiceFileRequest(BaseRequest): """ :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 :type application_id: string :param application_id: 发票申请单 ID """ def __init__(self, invoice_apply_id=None, application_id=None): super().__init__() self.invoice_apply_id = invoice_apply_id self.application_id = application_id def get_invoice_apply_id(self): """ Get 发票申请编号 :return: string, invoice_apply_id """ return self.invoice_apply_id def set_invoice_apply_id(self, invoice_apply_id): """ Set 发票申请编号 :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 """ self.invoice_apply_id = invoice_apply_id def get_application_id(self): """ Get 发票申请单 ID :return: string, application_id """ return self.application_id def set_application_id(self, application_id): """ Set 发票申请单 ID :type application_id: string :param application_id: 发票申请单 ID """ self.application_id = application_id class GetInvoiceFileResponse(BaseRequest): """ :type url: string :param url: 下载地址 :type name: string :param name: 文件名称 """ def __init__(self, url=None, name=None): super().__init__() self.url = url self.name = name def get_url(self): """ Get 下载地址 :return: string, url """ return self.url def set_url(self, url): """ Set 下载地址 :type url: string :param url: 下载地址 """ self.url = url def get_name(self): """ Get 文件名称 :return: string, name """ return self.name def set_name(self, name): """ Set 文件名称 :type name: string :param name: 文件名称 """ self.name = name class SendReminderEmailRequest(BaseRequest): """ :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 :type application_id: string :param application_id: 发票申请单 ID """ def __init__(self, invoice_apply_id=None, application_id=None): super().__init__() self.invoice_apply_id = invoice_apply_id self.application_id = application_id def get_invoice_apply_id(self): """ Get 发票申请编号 :return: string, invoice_apply_id """ return self.invoice_apply_id def set_invoice_apply_id(self, invoice_apply_id): """ Set 发票申请编号 :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 """ self.invoice_apply_id = invoice_apply_id def get_application_id(self): """ Get 发票申请单 ID :return: string, application_id """ return self.application_id def set_application_id(self, application_id): """ Set 发票申请单 ID :type application_id: string :param application_id: 发票申请单 ID """ self.application_id = application_id class SendReminderEmailResponse(BaseRequest): """ """ def __init__(self): super().__init__() class NotifyInvoiceDoneRequest(BaseRequest): """ :type application_id: string :param application_id: 发票申请编号 :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 :type status: string :param status: 申请结果 :type count: int :param count: 发票张数 :type price_tax_amount: string :param price_tax_amount: 价税合计 :type price_amount: string :param price_amount: 不含税金额 :type tax_amount: string :param tax_amount: 税额 :type invoice_type: string :param invoice_type: 发票类型 :type customer_name: string :param customer_name: 购方名称 :type customer_tax_num: string :param customer_tax_num: 纳税人识别号 :type customer_address_tel: string :param customer_address_tel: 购方地址、电话 :type bank_name_account: string :param bank_name_account: 开户行及账号 :type goods_services_name: string :param goods_services_name: 货物或应税劳务、服务名称 :type remark: string :param remark: 发票备注 :type post_type: string :param post_type: 邮寄类型 :type waybill_number: list :param waybill_number: 快递单号 :type reject_reason: string :param reject_reason: 驳回原因 """ def __init__(self, application_id=None, invoice_apply_id=None, status=None, count=None, price_tax_amount=None, price_amount=None, tax_amount=None, invoice_type=None, customer_name=None, customer_tax_num=None, customer_address_tel=None, bank_name_account=None, goods_services_name=None, remark=None, post_type=None, waybill_number=None, reject_reason=None): super().__init__() self.application_id = application_id self.invoice_apply_id = invoice_apply_id self.status = status self.count = count self.price_tax_amount = price_tax_amount self.price_amount = price_amount self.tax_amount = tax_amount self.invoice_type = invoice_type self.customer_name = customer_name self.customer_tax_num = customer_tax_num self.customer_address_tel = customer_address_tel self.bank_name_account = bank_name_account self.goods_services_name = goods_services_name self.remark = remark self.post_type = post_type self.waybill_number = waybill_number self.reject_reason = reject_reason def get_application_id(self): """ Get 发票申请编号 :return: string, application_id """ return self.application_id def set_application_id(self, application_id): """ Set 发票申请编号 :type application_id: string :param application_id: 发票申请编号 """ self.application_id = application_id def get_invoice_apply_id(self): """ Get 发票申请编号 :return: string, invoice_apply_id """ return self.invoice_apply_id def set_invoice_apply_id(self, invoice_apply_id): """ Set 发票申请编号 :type invoice_apply_id: string :param invoice_apply_id: 发票申请编号 """ self.invoice_apply_id = invoice_apply_id def get_status(self): """ Get 申请结果 :return: string, status """ return self.status def set_status(self, status): """ Set 申请结果 :type status: string :param status: 申请结果 """ self.status = status def get_count(self): """ Get 发票张数 :return: int, count """ return self.count def set_count(self, count): """ Set 发票张数 :type count: int :param count: 发票张数 """ self.count = count def get_price_tax_amount(self): """ Get 价税合计 :return: string, price_tax_amount """ return self.price_tax_amount def set_price_tax_amount(self, price_tax_amount): """ Set 价税合计 :type price_tax_amount: string :param price_tax_amount: 价税合计 """ self.price_tax_amount = price_tax_amount def get_price_amount(self): """ Get 不含税金额 :return: string, price_amount """ return self.price_amount def set_price_amount(self, price_amount): """ Set 不含税金额 :type price_amount: string :param price_amount: 不含税金额 """ self.price_amount = price_amount def get_tax_amount(self): """ Get 税额 :return: string, tax_amount """ return self.tax_amount def set_tax_amount(self, tax_amount): """ Set 税额 :type tax_amount: string :param tax_amount: 税额 """ self.tax_amount = tax_amount def get_invoice_type(self): """ Get 发票类型 :return: string, invoice_type """ return self.invoice_type def set_invoice_type(self, invoice_type): """ Set 发票类型 :type invoice_type: string :param invoice_type: 发票类型 """ self.invoice_type = invoice_type def get_customer_name(self): """ Get 购方名称 :return: string, customer_name """ return self.customer_name def set_customer_name(self, customer_name): """ Set 购方名称 :type customer_name: string :param customer_name: 购方名称 """ self.customer_name = customer_name def get_customer_tax_num(self): """ Get 纳税人识别号 :return: string, customer_tax_num """ return self.customer_tax_num def set_customer_tax_num(self, customer_tax_num): """ Set 纳税人识别号 :type customer_tax_num: string :param customer_tax_num: 纳税人识别号 """ self.customer_tax_num = customer_tax_num def get_customer_address_tel(self): """ Get 购方地址、电话 :return: string, customer_address_tel """ return self.customer_address_tel def set_customer_address_tel(self, customer_address_tel): """ Set 购方地址、电话 :type customer_address_tel: string :param customer_address_tel: 购方地址、电话 """ self.customer_address_tel = customer_address_tel def get_bank_name_account(self): """ Get 开户行及账号 :return: string, bank_name_account """ return self.bank_name_account def set_bank_name_account(self, bank_name_account): """ Set 开户行及账号 :type bank_name_account: string :param bank_name_account: 开户行及账号 """ self.bank_name_account = bank_name_account def get_goods_services_name(self): """ Get 货物或应税劳务、服务名称 :return: string, goods_services_name """ return self.goods_services_name def set_goods_services_name(self, goods_services_name): """ Set 货物或应税劳务、服务名称 :type goods_services_name: string :param goods_services_name: 货物或应税劳务、服务名称 """ self.goods_services_name = goods_services_name def get_remark(self): """ Get 发票备注 :return: string, remark """ return self.remark def set_remark(self, remark): """ Set 发票备注 :type remark: string :param remark: 发票备注 """ self.remark = remark def get_post_type(self): """ Get 邮寄类型 :return: string, post_type """ return self.post_type def set_post_type(self, post_type): """ Set 邮寄类型 :type post_type: string :param post_type: 邮寄类型 """ self.post_type = post_type def get_waybill_number(self): """ Get 快递单号 :return: list, waybill_number """ return self.waybill_number def set_waybill_number(self, waybill_number): """ Set 快递单号 :type waybill_number: list :param waybill_number: 快递单号 """ self.waybill_number = waybill_number def get_reject_reason(self): """ Get 驳回原因 :return: string, reject_reason """ return self.reject_reason def set_reject_reason(self, reject_reason): """ Set 驳回原因 :type reject_reason: string :param reject_reason: 驳回原因 """ self.reject_reason = reject_reason
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/invoice.py
invoice.py
from ...base import BaseRequest class GetTaxFileRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type ent_id: string :param ent_id: 平台企业签约主体 :type year_month: string :param year_month: 所属期 """ def __init__(self, dealer_id=None, ent_id=None, year_month=None): super().__init__() self.dealer_id = dealer_id self.ent_id = ent_id self.year_month = year_month def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_ent_id(self): """ Get 平台企业签约主体 :return: string, ent_id """ return self.ent_id def set_ent_id(self, ent_id): """ Set 平台企业签约主体 :type ent_id: string :param ent_id: 平台企业签约主体 """ self.ent_id = ent_id def get_year_month(self): """ Get 所属期 :return: string, year_month """ return self.year_month def set_year_month(self, year_month): """ Set 所属期 :type year_month: string :param year_month: 所属期 """ self.year_month = year_month class GetTaxFileResponse(BaseRequest): """ :type file_info: list :param file_info: 文件详情 """ def __init__(self, file_info=None): super().__init__() self.file_info = file_info def get_file_info(self): """ Get 文件详情 :return: list, file_info """ return self.file_info def set_file_info(self, file_info): """ Set 文件详情 :type file_info: list :param file_info: 文件详情 """ self.file_info = file_info class FileInfo(BaseRequest): """ :type name: string :param name: 文件名称 :type url: string :param url: 下载文件临时 URL :type pwd: string :param pwd: 文件解压缩密码 """ def __init__(self, name=None, url=None, pwd=None): super().__init__() self.name = name self.url = url self.pwd = pwd def get_name(self): """ Get 文件名称 :return: string, name """ return self.name def set_name(self, name): """ Set 文件名称 :type name: string :param name: 文件名称 """ self.name = name def get_url(self): """ Get 下载文件临时 URL :return: string, url """ return self.url def set_url(self, url): """ Set 下载文件临时 URL :type url: string :param url: 下载文件临时 URL """ self.url = url def get_pwd(self): """ Get 文件解压缩密码 :return: string, pwd """ return self.pwd def set_pwd(self, pwd): """ Set 文件解压缩密码 :type pwd: string :param pwd: 文件解压缩密码 """ self.pwd = pwd class GetUserCrossRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type year: string :param year: 年份 :type id_card: string :param id_card: 身份证号码 :type ent_id: string :param ent_id: 平台企业签约主体 """ def __init__(self, dealer_id=None, year=None, id_card=None, ent_id=None): super().__init__() self.dealer_id = dealer_id self.year = year self.id_card = id_card self.ent_id = ent_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_year(self): """ Get 年份 :return: string, year """ return self.year def set_year(self, year): """ Set 年份 :type year: string :param year: 年份 """ self.year = year def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_ent_id(self): """ Get 平台企业签约主体 :return: string, ent_id """ return self.ent_id def set_ent_id(self, ent_id): """ Set 平台企业签约主体 :type ent_id: string :param ent_id: 平台企业签约主体 """ self.ent_id = ent_id class GetUserCrossResponse(BaseRequest): """ :type is_cross: bool :param is_cross: 跨集团标识 """ def __init__(self, is_cross=None): super().__init__() self.is_cross = is_cross def get_is_cross(self): """ Get 跨集团标识 :return: bool, is_cross """ return self.is_cross def set_is_cross(self, is_cross): """ Set 跨集团标识 :type is_cross: bool :param is_cross: 跨集团标识 """ self.is_cross = is_cross
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/tax.py
tax.py
from ...base import BaseRequest class H5UserPresignRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 证件号码 :type certificate_type: int :param certificate_type: 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 """ def __init__(self, dealer_id=None, broker_id=None, real_name=None, id_card=None, certificate_type=None): super().__init__() self.dealer_id = dealer_id self.broker_id = broker_id self.real_name = real_name self.id_card = id_card self.certificate_type = certificate_type def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card def get_certificate_type(self): """ Get 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 :return: int, certificate_type """ return self.certificate_type def set_certificate_type(self, certificate_type): """ Set 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 :type certificate_type: int :param certificate_type: 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 """ self.certificate_type = certificate_type class H5UserPresignResponse(BaseRequest): """ :type uid: string :param uid: 用户 ID(废弃字段) :type token: string :param token: H5 签约 token """ def __init__(self, uid=None, token=None): super().__init__() self.uid = uid self.token = token def get_uid(self): """ Get 用户 ID(废弃字段) :return: string, uid """ return self.uid def set_uid(self, uid): """ Set 用户 ID(废弃字段) :type uid: string :param uid: 用户 ID(废弃字段) """ self.uid = uid def get_token(self): """ Get H5 签约 token :return: string, token """ return self.token def set_token(self, token): """ Set H5 签约 token :type token: string :param token: H5 签约 token """ self.token = token class H5UserSignRequest(BaseRequest): """ :type token: string :param token: H5 签约 token :type color: string :param color: H5 页面主题颜色 :type url: string :param url: 回调 URL 地址 :type redirect_url: string :param redirect_url: 跳转 URL """ def __init__(self, token=None, color=None, url=None, redirect_url=None): super().__init__() self.token = token self.color = color self.url = url self.redirect_url = redirect_url def get_token(self): """ Get H5 签约 token :return: string, token """ return self.token def set_token(self, token): """ Set H5 签约 token :type token: string :param token: H5 签约 token """ self.token = token def get_color(self): """ Get H5 页面主题颜色 :return: string, color """ return self.color def set_color(self, color): """ Set H5 页面主题颜色 :type color: string :param color: H5 页面主题颜色 """ self.color = color def get_url(self): """ Get 回调 URL 地址 :return: string, url """ return self.url def set_url(self, url): """ Set 回调 URL 地址 :type url: string :param url: 回调 URL 地址 """ self.url = url def get_redirect_url(self): """ Get 跳转 URL :return: string, redirect_url """ return self.redirect_url def set_redirect_url(self, redirect_url): """ Set 跳转 URL :type redirect_url: string :param redirect_url: 跳转 URL """ self.redirect_url = redirect_url class H5UserSignResponse(BaseRequest): """ :type url: string :param url: H5 签约页面 URL """ def __init__(self, url=None): super().__init__() self.url = url def get_url(self): """ Get H5 签约页面 URL :return: string, url """ return self.url def set_url(self, url): """ Set H5 签约页面 URL :type url: string :param url: H5 签约页面 URL """ self.url = url class GetH5UserSignStatusRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 证件号码 """ def __init__(self, dealer_id=None, broker_id=None, real_name=None, id_card=None): super().__init__() self.dealer_id = dealer_id self.broker_id = broker_id self.real_name = real_name self.id_card = id_card def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card class GetH5UserSignStatusResponse(BaseRequest): """ :type signed_at: string :param signed_at: 签约时间 :type status: int :param status: 用户签约状态 """ def __init__(self, signed_at=None, status=None): super().__init__() self.signed_at = signed_at self.status = status def get_signed_at(self): """ Get 签约时间 :return: string, signed_at """ return self.signed_at def set_signed_at(self, signed_at): """ Set 签约时间 :type signed_at: string :param signed_at: 签约时间 """ self.signed_at = signed_at def get_status(self): """ Get 用户签约状态 :return: int, status """ return self.status def set_status(self, status): """ Set 用户签约状态 :type status: int :param status: 用户签约状态 """ self.status = status class H5UserReleaseRequest(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 证件号码 :type certificate_type: int :param certificate_type: 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 """ def __init__(self, broker_id=None, dealer_id=None, real_name=None, id_card=None, certificate_type=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id self.real_name = real_name self.id_card = id_card self.certificate_type = certificate_type def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card def get_certificate_type(self): """ Get 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 :return: int, certificate_type """ return self.certificate_type def set_certificate_type(self, certificate_type): """ Set 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 :type certificate_type: int :param certificate_type: 证件类型 0:身份证 2:港澳居民来往内地通行证 3:护照 5:台湾居民来往大陆通行证 """ self.certificate_type = certificate_type class H5UserReleaseResponse(BaseRequest): """ :type status: string :param status: 是否解约成功 """ def __init__(self, status=None): super().__init__() self.status = status def get_status(self): """ Get 是否解约成功 :return: string, status """ return self.status def set_status(self, status): """ Set 是否解约成功 :type status: string :param status: 是否解约成功 """ self.status = status
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/h5usersign.py
h5usersign.py
from ...base import BaseRequest class GetDailyOrderFileRequest(BaseRequest): """ :type order_date: string :param order_date: 订单查询日期, 格式:yyyy-MM-dd """ def __init__(self, order_date=None): super().__init__() self.order_date = order_date def get_order_date(self): """ Get 订单查询日期, 格式:yyyy-MM-dd :return: string, order_date """ return self.order_date def set_order_date(self, order_date): """ Set 订单查询日期, 格式:yyyy-MM-dd :type order_date: string :param order_date: 订单查询日期, 格式:yyyy-MM-dd """ self.order_date = order_date class GetDailyOrderFileResponse(BaseRequest): """ :type order_download_url: string :param order_download_url: 下载地址 """ def __init__(self, order_download_url=None): super().__init__() self.order_download_url = order_download_url def get_order_download_url(self): """ Get 下载地址 :return: string, order_download_url """ return self.order_download_url def set_order_download_url(self, order_download_url): """ Set 下载地址 :type order_download_url: string :param order_download_url: 下载地址 """ self.order_download_url = order_download_url class GetDailyBillFileV2Request(BaseRequest): """ :type bill_date: string :param bill_date: 所需获取的日流水日期,格式:yyyy-MM-dd """ def __init__(self, bill_date=None): super().__init__() self.bill_date = bill_date def get_bill_date(self): """ Get 所需获取的日流水日期,格式:yyyy-MM-dd :return: string, bill_date """ return self.bill_date def set_bill_date(self, bill_date): """ Set 所需获取的日流水日期,格式:yyyy-MM-dd :type bill_date: string :param bill_date: 所需获取的日流水日期,格式:yyyy-MM-dd """ self.bill_date = bill_date class GetDailyBillFileV2Response(BaseRequest): """ :type bill_download_url: string :param bill_download_url: 下载地址 """ def __init__(self, bill_download_url=None): super().__init__() self.bill_download_url = bill_download_url def get_bill_download_url(self): """ Get 下载地址 :return: string, bill_download_url """ return self.bill_download_url def set_bill_download_url(self, bill_download_url): """ Set 下载地址 :type bill_download_url: string :param bill_download_url: 下载地址 """ self.bill_download_url = bill_download_url class ListDealerRechargeRecordV2Request(BaseRequest): """ :type begin_at: string :param begin_at: 开始时间,格式:yyyy-MM-dd :type end_at: string :param end_at: 结束时间,格式:yyyy-MM-dd """ def __init__(self, begin_at=None, end_at=None): super().__init__() self.begin_at = begin_at self.end_at = end_at def get_begin_at(self): """ Get 开始时间,格式:yyyy-MM-dd :return: string, begin_at """ return self.begin_at def set_begin_at(self, begin_at): """ Set 开始时间,格式:yyyy-MM-dd :type begin_at: string :param begin_at: 开始时间,格式:yyyy-MM-dd """ self.begin_at = begin_at def get_end_at(self): """ Get 结束时间,格式:yyyy-MM-dd :return: string, end_at """ return self.end_at def set_end_at(self, end_at): """ Set 结束时间,格式:yyyy-MM-dd :type end_at: string :param end_at: 结束时间,格式:yyyy-MM-dd """ self.end_at = end_at class ListDealerRechargeRecordV2Response(BaseRequest): """ :type data: list :param data: 预付业务服务费记录 """ def __init__(self, data=None): super().__init__() self.data = data def get_data(self): """ Get 预付业务服务费记录 :return: list, data """ return self.data def set_data(self, data): """ Set 预付业务服务费记录 :type data: list :param data: 预付业务服务费记录 """ self.data = data class RechargeRecordInfo(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type recharge_id: string :param recharge_id: 预付业务服务费记录 ID :type amount: string :param amount: 预付业务服务费 :type actual_amount: string :param actual_amount: 实际到账金额 :type created_at: string :param created_at: 创建时间 :type recharge_channel: string :param recharge_channel: 资金用途 :type remark: string :param remark: 预付业务服务费备注 :type recharge_account_no: string :param recharge_account_no: 平台企业付款银行账号 """ def __init__(self, dealer_id=None, broker_id=None, recharge_id=None, amount=None, actual_amount=None, created_at=None, recharge_channel=None, remark=None, recharge_account_no=None): super().__init__() self.dealer_id = dealer_id self.broker_id = broker_id self.recharge_id = recharge_id self.amount = amount self.actual_amount = actual_amount self.created_at = created_at self.recharge_channel = recharge_channel self.remark = remark self.recharge_account_no = recharge_account_no def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_recharge_id(self): """ Get 预付业务服务费记录 ID :return: string, recharge_id """ return self.recharge_id def set_recharge_id(self, recharge_id): """ Set 预付业务服务费记录 ID :type recharge_id: string :param recharge_id: 预付业务服务费记录 ID """ self.recharge_id = recharge_id def get_amount(self): """ Get 预付业务服务费 :return: string, amount """ return self.amount def set_amount(self, amount): """ Set 预付业务服务费 :type amount: string :param amount: 预付业务服务费 """ self.amount = amount def get_actual_amount(self): """ Get 实际到账金额 :return: string, actual_amount """ return self.actual_amount def set_actual_amount(self, actual_amount): """ Set 实际到账金额 :type actual_amount: string :param actual_amount: 实际到账金额 """ self.actual_amount = actual_amount def get_created_at(self): """ Get 创建时间 :return: string, created_at """ return self.created_at def set_created_at(self, created_at): """ Set 创建时间 :type created_at: string :param created_at: 创建时间 """ self.created_at = created_at def get_recharge_channel(self): """ Get 资金用途 :return: string, recharge_channel """ return self.recharge_channel def set_recharge_channel(self, recharge_channel): """ Set 资金用途 :type recharge_channel: string :param recharge_channel: 资金用途 """ self.recharge_channel = recharge_channel def get_remark(self): """ Get 预付业务服务费备注 :return: string, remark """ return self.remark def set_remark(self, remark): """ Set 预付业务服务费备注 :type remark: string :param remark: 预付业务服务费备注 """ self.remark = remark def get_recharge_account_no(self): """ Get 平台企业付款银行账号 :return: string, recharge_account_no """ return self.recharge_account_no def set_recharge_account_no(self, recharge_account_no): """ Set 平台企业付款银行账号 :type recharge_account_no: string :param recharge_account_no: 平台企业付款银行账号 """ self.recharge_account_no = recharge_account_no class ListDailyOrderRequest(BaseRequest): """ :type order_date: string :param order_date: 订单查询日期, 格式:yyyy-MM-dd格式:yyyy-MM-dd :type offset: int :param offset: 偏移量 :type length: int :param length: 长度 :type channel: string :param channel: 支付路径名,银行卡(默认)、支付宝、微信 :type data_type: string :param data_type: 如果为 encryption,则对返回的 data 进行加密 """ def __init__(self, order_date=None, offset=None, length=None, channel=None, data_type=None): super().__init__() self.order_date = order_date self.offset = offset self.length = length self.channel = channel self.data_type = data_type def get_order_date(self): """ Get 订单查询日期, 格式:yyyy-MM-dd格式:yyyy-MM-dd :return: string, order_date """ return self.order_date def set_order_date(self, order_date): """ Set 订单查询日期, 格式:yyyy-MM-dd格式:yyyy-MM-dd :type order_date: string :param order_date: 订单查询日期, 格式:yyyy-MM-dd格式:yyyy-MM-dd """ self.order_date = order_date def get_offset(self): """ Get 偏移量 :return: int, offset """ return self.offset def set_offset(self, offset): """ Set 偏移量 :type offset: int :param offset: 偏移量 """ self.offset = offset def get_length(self): """ Get 长度 :return: int, length """ return self.length def set_length(self, length): """ Set 长度 :type length: int :param length: 长度 """ self.length = length def get_channel(self): """ Get 支付路径名,银行卡(默认)、支付宝、微信 :return: string, channel """ return self.channel def set_channel(self, channel): """ Set 支付路径名,银行卡(默认)、支付宝、微信 :type channel: string :param channel: 支付路径名,银行卡(默认)、支付宝、微信 """ self.channel = channel def get_data_type(self): """ Get 如果为 encryption,则对返回的 data 进行加密 :return: string, data_type """ return self.data_type def set_data_type(self, data_type): """ Set 如果为 encryption,则对返回的 data 进行加密 :type data_type: string :param data_type: 如果为 encryption,则对返回的 data 进行加密 """ self.data_type = data_type class ListDailyOrderResponse(BaseRequest): """ :type total_num: int :param total_num: 总数目 :type list: list :param list: 条目信息 """ def __init__(self, total_num=None, list=None): super().__init__() self.total_num = total_num self.list = list def get_total_num(self): """ Get 总数目 :return: int, total_num """ return self.total_num def set_total_num(self, total_num): """ Set 总数目 :type total_num: int :param total_num: 总数目 """ self.total_num = total_num def get_list(self): """ Get 条目信息 :return: list, list """ return self.list def set_list(self, list): """ Set 条目信息 :type list: list :param list: 条目信息 """ self.list = list class DealerOrderInfo(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 订单流水号 :type batch_id: string :param batch_id: 批次ID :type real_name: string :param real_name: 姓名 :type card_no: string :param card_no: 收款账号 :type broker_amount: string :param broker_amount: 综合服务主体订单金额 :type broker_fee: string :param broker_fee: 综合服务主体加成服务费 :type bill: string :param bill: 支付路径流水号 :type status: string :param status: 订单状态 :type status_detail: string :param status_detail: 订单详情 :type status_detail_message: string :param status_detail_message: 订单详细状态码描述 :type statement_id: string :param statement_id: 短周期授信账单号 :type fee_statement_id: string :param fee_statement_id: 服务费账单号 :type bal_statement_id: string :param bal_statement_id: 余额账单号 :type channel: string :param channel: 支付路径 :type created_at: string :param created_at: 创建时间 :type finished_time: string :param finished_time: 完成时间 """ def __init__(self, broker_id=None, dealer_id=None, order_id=None, ref=None, batch_id=None, real_name=None, card_no=None, broker_amount=None, broker_fee=None, bill=None, status=None, status_detail=None, status_detail_message=None, statement_id=None, fee_statement_id=None, bal_statement_id=None, channel=None, created_at=None, finished_time=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id self.order_id = order_id self.ref = ref self.batch_id = batch_id self.real_name = real_name self.card_no = card_no self.broker_amount = broker_amount self.broker_fee = broker_fee self.bill = bill self.status = status self.status_detail = status_detail self.status_detail_message = status_detail_message self.statement_id = statement_id self.fee_statement_id = fee_statement_id self.bal_statement_id = bal_statement_id self.channel = channel self.created_at = created_at self.finished_time = finished_time def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 订单流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 订单流水号 :type ref: string :param ref: 订单流水号 """ self.ref = ref def get_batch_id(self): """ Get 批次ID :return: string, batch_id """ return self.batch_id def set_batch_id(self, batch_id): """ Set 批次ID :type batch_id: string :param batch_id: 批次ID """ self.batch_id = batch_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_card_no(self): """ Get 收款账号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 收款账号 :type card_no: string :param card_no: 收款账号 """ self.card_no = card_no def get_broker_amount(self): """ Get 综合服务主体订单金额 :return: string, broker_amount """ return self.broker_amount def set_broker_amount(self, broker_amount): """ Set 综合服务主体订单金额 :type broker_amount: string :param broker_amount: 综合服务主体订单金额 """ self.broker_amount = broker_amount def get_broker_fee(self): """ Get 综合服务主体加成服务费 :return: string, broker_fee """ return self.broker_fee def set_broker_fee(self, broker_fee): """ Set 综合服务主体加成服务费 :type broker_fee: string :param broker_fee: 综合服务主体加成服务费 """ self.broker_fee = broker_fee def get_bill(self): """ Get 支付路径流水号 :return: string, bill """ return self.bill def set_bill(self, bill): """ Set 支付路径流水号 :type bill: string :param bill: 支付路径流水号 """ self.bill = bill def get_status(self): """ Get 订单状态 :return: string, status """ return self.status def set_status(self, status): """ Set 订单状态 :type status: string :param status: 订单状态 """ self.status = status def get_status_detail(self): """ Get 订单详情 :return: string, status_detail """ return self.status_detail def set_status_detail(self, status_detail): """ Set 订单详情 :type status_detail: string :param status_detail: 订单详情 """ self.status_detail = status_detail def get_status_detail_message(self): """ Get 订单详细状态码描述 :return: string, status_detail_message """ return self.status_detail_message def set_status_detail_message(self, status_detail_message): """ Set 订单详细状态码描述 :type status_detail_message: string :param status_detail_message: 订单详细状态码描述 """ self.status_detail_message = status_detail_message def get_statement_id(self): """ Get 短周期授信账单号 :return: string, statement_id """ return self.statement_id def set_statement_id(self, statement_id): """ Set 短周期授信账单号 :type statement_id: string :param statement_id: 短周期授信账单号 """ self.statement_id = statement_id def get_fee_statement_id(self): """ Get 服务费账单号 :return: string, fee_statement_id """ return self.fee_statement_id def set_fee_statement_id(self, fee_statement_id): """ Set 服务费账单号 :type fee_statement_id: string :param fee_statement_id: 服务费账单号 """ self.fee_statement_id = fee_statement_id def get_bal_statement_id(self): """ Get 余额账单号 :return: string, bal_statement_id """ return self.bal_statement_id def set_bal_statement_id(self, bal_statement_id): """ Set 余额账单号 :type bal_statement_id: string :param bal_statement_id: 余额账单号 """ self.bal_statement_id = bal_statement_id def get_channel(self): """ Get 支付路径 :return: string, channel """ return self.channel def set_channel(self, channel): """ Set 支付路径 :type channel: string :param channel: 支付路径 """ self.channel = channel def get_created_at(self): """ Get 创建时间 :return: string, created_at """ return self.created_at def set_created_at(self, created_at): """ Set 创建时间 :type created_at: string :param created_at: 创建时间 """ self.created_at = created_at def get_finished_time(self): """ Get 完成时间 :return: string, finished_time """ return self.finished_time def set_finished_time(self, finished_time): """ Set 完成时间 :type finished_time: string :param finished_time: 完成时间 """ self.finished_time = finished_time class ListDailyBillRequest(BaseRequest): """ :type bill_date: string :param bill_date: 流水查询日期 :type offset: int :param offset: 偏移量 :type length: int :param length: 长度 :type data_type: string :param data_type: 如果为 encryption,则对返回的 data 进行加密 """ def __init__(self, bill_date=None, offset=None, length=None, data_type=None): super().__init__() self.bill_date = bill_date self.offset = offset self.length = length self.data_type = data_type def get_bill_date(self): """ Get 流水查询日期 :return: string, bill_date """ return self.bill_date def set_bill_date(self, bill_date): """ Set 流水查询日期 :type bill_date: string :param bill_date: 流水查询日期 """ self.bill_date = bill_date def get_offset(self): """ Get 偏移量 :return: int, offset """ return self.offset def set_offset(self, offset): """ Set 偏移量 :type offset: int :param offset: 偏移量 """ self.offset = offset def get_length(self): """ Get 长度 :return: int, length """ return self.length def set_length(self, length): """ Set 长度 :type length: int :param length: 长度 """ self.length = length def get_data_type(self): """ Get 如果为 encryption,则对返回的 data 进行加密 :return: string, data_type """ return self.data_type def set_data_type(self, data_type): """ Set 如果为 encryption,则对返回的 data 进行加密 :type data_type: string :param data_type: 如果为 encryption,则对返回的 data 进行加密 """ self.data_type = data_type class ListDailyBillResponse(BaseRequest): """ :type total_num: int :param total_num: 总条数 :type bills: list :param bills: 条目信息 """ def __init__(self, total_num=None, bills=None): super().__init__() self.total_num = total_num self.bills = bills def get_total_num(self): """ Get 总条数 :return: int, total_num """ return self.total_num def set_total_num(self, total_num): """ Set 总条数 :type total_num: int :param total_num: 总条数 """ self.total_num = total_num def get_bills(self): """ Get 条目信息 :return: list, bills """ return self.bills def set_bills(self, bills): """ Set 条目信息 :type bills: list :param bills: 条目信息 """ self.bills = bills class DealerBillInfo(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 资金流水号 :type broker_product_name: string :param broker_product_name: 综合服务主体名称 :type dealer_product_name: string :param dealer_product_name: 平台企业名称 :type biz_ref: string :param biz_ref: 业务订单流水号 :type acct_type: string :param acct_type: 账户类型 :type amount: string :param amount: 入账金额 :type balance: string :param balance: 账户余额 :type business_category: string :param business_category: 业务分类 :type business_type: string :param business_type: 业务类型 :type consumption_type: string :param consumption_type: 收支类型 :type created_at: string :param created_at: 入账时间 :type remark: string :param remark: 备注 """ def __init__(self, broker_id=None, dealer_id=None, order_id=None, ref=None, broker_product_name=None, dealer_product_name=None, biz_ref=None, acct_type=None, amount=None, balance=None, business_category=None, business_type=None, consumption_type=None, created_at=None, remark=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id self.order_id = order_id self.ref = ref self.broker_product_name = broker_product_name self.dealer_product_name = dealer_product_name self.biz_ref = biz_ref self.acct_type = acct_type self.amount = amount self.balance = balance self.business_category = business_category self.business_type = business_type self.consumption_type = consumption_type self.created_at = created_at self.remark = remark def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 资金流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 资金流水号 :type ref: string :param ref: 资金流水号 """ self.ref = ref def get_broker_product_name(self): """ Get 综合服务主体名称 :return: string, broker_product_name """ return self.broker_product_name def set_broker_product_name(self, broker_product_name): """ Set 综合服务主体名称 :type broker_product_name: string :param broker_product_name: 综合服务主体名称 """ self.broker_product_name = broker_product_name def get_dealer_product_name(self): """ Get 平台企业名称 :return: string, dealer_product_name """ return self.dealer_product_name def set_dealer_product_name(self, dealer_product_name): """ Set 平台企业名称 :type dealer_product_name: string :param dealer_product_name: 平台企业名称 """ self.dealer_product_name = dealer_product_name def get_biz_ref(self): """ Get 业务订单流水号 :return: string, biz_ref """ return self.biz_ref def set_biz_ref(self, biz_ref): """ Set 业务订单流水号 :type biz_ref: string :param biz_ref: 业务订单流水号 """ self.biz_ref = biz_ref def get_acct_type(self): """ Get 账户类型 :return: string, acct_type """ return self.acct_type def set_acct_type(self, acct_type): """ Set 账户类型 :type acct_type: string :param acct_type: 账户类型 """ self.acct_type = acct_type def get_amount(self): """ Get 入账金额 :return: string, amount """ return self.amount def set_amount(self, amount): """ Set 入账金额 :type amount: string :param amount: 入账金额 """ self.amount = amount def get_balance(self): """ Get 账户余额 :return: string, balance """ return self.balance def set_balance(self, balance): """ Set 账户余额 :type balance: string :param balance: 账户余额 """ self.balance = balance def get_business_category(self): """ Get 业务分类 :return: string, business_category """ return self.business_category def set_business_category(self, business_category): """ Set 业务分类 :type business_category: string :param business_category: 业务分类 """ self.business_category = business_category def get_business_type(self): """ Get 业务类型 :return: string, business_type """ return self.business_type def set_business_type(self, business_type): """ Set 业务类型 :type business_type: string :param business_type: 业务类型 """ self.business_type = business_type def get_consumption_type(self): """ Get 收支类型 :return: string, consumption_type """ return self.consumption_type def set_consumption_type(self, consumption_type): """ Set 收支类型 :type consumption_type: string :param consumption_type: 收支类型 """ self.consumption_type = consumption_type def get_created_at(self): """ Get 入账时间 :return: string, created_at """ return self.created_at def set_created_at(self, created_at): """ Set 入账时间 :type created_at: string :param created_at: 入账时间 """ self.created_at = created_at def get_remark(self): """ Get 备注 :return: string, remark """ return self.remark def set_remark(self, remark): """ Set 备注 :type remark: string :param remark: 备注 """ self.remark = remark class GetDailyOrderFileV2Request(BaseRequest): """ :type order_date: string :param order_date: 订单查询日期, 格式:yyyy-MM-dd """ def __init__(self, order_date=None): super().__init__() self.order_date = order_date def get_order_date(self): """ Get 订单查询日期, 格式:yyyy-MM-dd :return: string, order_date """ return self.order_date def set_order_date(self, order_date): """ Set 订单查询日期, 格式:yyyy-MM-dd :type order_date: string :param order_date: 订单查询日期, 格式:yyyy-MM-dd """ self.order_date = order_date class GetDailyOrderFileV2Response(BaseRequest): """ :type url: string :param url: 下载地址 """ def __init__(self, url=None): super().__init__() self.url = url def get_url(self): """ Get 下载地址 :return: string, url """ return self.url def set_url(self, url): """ Set 下载地址 :type url: string :param url: 下载地址 """ self.url = url class ListBalanceDailyStatementRequest(BaseRequest): """ :type statement_date: string :param statement_date: 账单查询日期 格式:yyyy-MM-dd """ def __init__(self, statement_date=None): super().__init__() self.statement_date = statement_date def get_statement_date(self): """ Get 账单查询日期 格式:yyyy-MM-dd :return: string, statement_date """ return self.statement_date def set_statement_date(self, statement_date): """ Set 账单查询日期 格式:yyyy-MM-dd :type statement_date: string :param statement_date: 账单查询日期 格式:yyyy-MM-dd """ self.statement_date = statement_date class ListBalanceDailyStatementResponse(BaseRequest): """ :type list: list :param list: 条目信息 """ def __init__(self, list=None): super().__init__() self.list = list def get_list(self): """ Get 条目信息 :return: list, list """ return self.list def set_list(self, list): """ Set 条目信息 :type list: list :param list: 条目信息 """ self.list = list class StatementDetail(BaseRequest): """ :type statement_id: string :param statement_id: 账单 ID :type statement_date: string :param statement_date: 账单日期 :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_product_name: string :param broker_product_name: 综合服务主体名称 :type dealer_product_name: string :param dealer_product_name: 平台企业名称 :type biz_type: string :param biz_type: 业务类型 :type total_money: string :param total_money: 账单金额 :type amount: string :param amount: 订单金额 :type reex_amount: string :param reex_amount: 退汇金额 :type fee_amount: string :param fee_amount: 加成服务费金额 :type deduct_rebate_fee_amount: string :param deduct_rebate_fee_amount: 加成服务费抵扣金额 :type money_adjust: string :param money_adjust: 冲补金额 :type status: string :param status: 账单状态 :type invoice_status: string :param invoice_status: 开票状态 :type project_id: string :param project_id: 项目 ID :type project_name: string :param project_name: 项目名称 """ def __init__(self, statement_id=None, statement_date=None, broker_id=None, dealer_id=None, broker_product_name=None, dealer_product_name=None, biz_type=None, total_money=None, amount=None, reex_amount=None, fee_amount=None, deduct_rebate_fee_amount=None, money_adjust=None, status=None, invoice_status=None, project_id=None, project_name=None): super().__init__() self.statement_id = statement_id self.statement_date = statement_date self.broker_id = broker_id self.dealer_id = dealer_id self.broker_product_name = broker_product_name self.dealer_product_name = dealer_product_name self.biz_type = biz_type self.total_money = total_money self.amount = amount self.reex_amount = reex_amount self.fee_amount = fee_amount self.deduct_rebate_fee_amount = deduct_rebate_fee_amount self.money_adjust = money_adjust self.status = status self.invoice_status = invoice_status self.project_id = project_id self.project_name = project_name def get_statement_id(self): """ Get 账单 ID :return: string, statement_id """ return self.statement_id def set_statement_id(self, statement_id): """ Set 账单 ID :type statement_id: string :param statement_id: 账单 ID """ self.statement_id = statement_id def get_statement_date(self): """ Get 账单日期 :return: string, statement_date """ return self.statement_date def set_statement_date(self, statement_date): """ Set 账单日期 :type statement_date: string :param statement_date: 账单日期 """ self.statement_date = statement_date def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_product_name(self): """ Get 综合服务主体名称 :return: string, broker_product_name """ return self.broker_product_name def set_broker_product_name(self, broker_product_name): """ Set 综合服务主体名称 :type broker_product_name: string :param broker_product_name: 综合服务主体名称 """ self.broker_product_name = broker_product_name def get_dealer_product_name(self): """ Get 平台企业名称 :return: string, dealer_product_name """ return self.dealer_product_name def set_dealer_product_name(self, dealer_product_name): """ Set 平台企业名称 :type dealer_product_name: string :param dealer_product_name: 平台企业名称 """ self.dealer_product_name = dealer_product_name def get_biz_type(self): """ Get 业务类型 :return: string, biz_type """ return self.biz_type def set_biz_type(self, biz_type): """ Set 业务类型 :type biz_type: string :param biz_type: 业务类型 """ self.biz_type = biz_type def get_total_money(self): """ Get 账单金额 :return: string, total_money """ return self.total_money def set_total_money(self, total_money): """ Set 账单金额 :type total_money: string :param total_money: 账单金额 """ self.total_money = total_money def get_amount(self): """ Get 订单金额 :return: string, amount """ return self.amount def set_amount(self, amount): """ Set 订单金额 :type amount: string :param amount: 订单金额 """ self.amount = amount def get_reex_amount(self): """ Get 退汇金额 :return: string, reex_amount """ return self.reex_amount def set_reex_amount(self, reex_amount): """ Set 退汇金额 :type reex_amount: string :param reex_amount: 退汇金额 """ self.reex_amount = reex_amount def get_fee_amount(self): """ Get 加成服务费金额 :return: string, fee_amount """ return self.fee_amount def set_fee_amount(self, fee_amount): """ Set 加成服务费金额 :type fee_amount: string :param fee_amount: 加成服务费金额 """ self.fee_amount = fee_amount def get_deduct_rebate_fee_amount(self): """ Get 加成服务费抵扣金额 :return: string, deduct_rebate_fee_amount """ return self.deduct_rebate_fee_amount def set_deduct_rebate_fee_amount(self, deduct_rebate_fee_amount): """ Set 加成服务费抵扣金额 :type deduct_rebate_fee_amount: string :param deduct_rebate_fee_amount: 加成服务费抵扣金额 """ self.deduct_rebate_fee_amount = deduct_rebate_fee_amount def get_money_adjust(self): """ Get 冲补金额 :return: string, money_adjust """ return self.money_adjust def set_money_adjust(self, money_adjust): """ Set 冲补金额 :type money_adjust: string :param money_adjust: 冲补金额 """ self.money_adjust = money_adjust def get_status(self): """ Get 账单状态 :return: string, status """ return self.status def set_status(self, status): """ Set 账单状态 :type status: string :param status: 账单状态 """ self.status = status def get_invoice_status(self): """ Get 开票状态 :return: string, invoice_status """ return self.invoice_status def set_invoice_status(self, invoice_status): """ Set 开票状态 :type invoice_status: string :param invoice_status: 开票状态 """ self.invoice_status = invoice_status def get_project_id(self): """ Get 项目 ID :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目 ID :type project_id: string :param project_id: 项目 ID """ self.project_id = project_id def get_project_name(self): """ Get 项目名称 :return: string, project_name """ return self.project_name def set_project_name(self, project_name): """ Set 项目名称 :type project_name: string :param project_name: 项目名称 """ self.project_name = project_name
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/dataservice.py
dataservice.py
from ...base import BaseRequest class BankCardFourAuthVerifyRequest(BaseRequest): """ :type card_no: string :param card_no: 银行卡号 :type id_card: string :param id_card: 身份证号码 :type real_name: string :param real_name: 姓名 :type mobile: string :param mobile: 银行预留手机号 """ def __init__(self, card_no=None, id_card=None, real_name=None, mobile=None): super().__init__() self.card_no = card_no self.id_card = id_card self.real_name = real_name self.mobile = mobile def get_card_no(self): """ Get 银行卡号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 银行卡号 :type card_no: string :param card_no: 银行卡号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_mobile(self): """ Get 银行预留手机号 :return: string, mobile """ return self.mobile def set_mobile(self, mobile): """ Set 银行预留手机号 :type mobile: string :param mobile: 银行预留手机号 """ self.mobile = mobile class BankCardFourAuthVerifyResponse(BaseRequest): """ :type ref: string :param ref: 交易凭证 """ def __init__(self, ref=None): super().__init__() self.ref = ref def get_ref(self): """ Get 交易凭证 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 交易凭证 :type ref: string :param ref: 交易凭证 """ self.ref = ref class BankCardFourAuthConfirmRequest(BaseRequest): """ :type card_no: string :param card_no: 银行卡号 :type id_card: string :param id_card: 身份证号码 :type real_name: string :param real_name: 姓名 :type mobile: string :param mobile: 银行预留手机号 :type captcha: string :param captcha: 短信验证码 :type ref: string :param ref: 交易凭证 """ def __init__(self, card_no=None, id_card=None, real_name=None, mobile=None, captcha=None, ref=None): super().__init__() self.card_no = card_no self.id_card = id_card self.real_name = real_name self.mobile = mobile self.captcha = captcha self.ref = ref def get_card_no(self): """ Get 银行卡号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 银行卡号 :type card_no: string :param card_no: 银行卡号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_mobile(self): """ Get 银行预留手机号 :return: string, mobile """ return self.mobile def set_mobile(self, mobile): """ Set 银行预留手机号 :type mobile: string :param mobile: 银行预留手机号 """ self.mobile = mobile def get_captcha(self): """ Get 短信验证码 :return: string, captcha """ return self.captcha def set_captcha(self, captcha): """ Set 短信验证码 :type captcha: string :param captcha: 短信验证码 """ self.captcha = captcha def get_ref(self): """ Get 交易凭证 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 交易凭证 :type ref: string :param ref: 交易凭证 """ self.ref = ref class BankCardFourAuthConfirmResponse(BaseRequest): """ """ def __init__(self): super().__init__() class BankCardFourVerifyRequest(BaseRequest): """ :type card_no: string :param card_no: 银行卡号 :type id_card: string :param id_card: 身份证号码 :type real_name: string :param real_name: 姓名 :type mobile: string :param mobile: 银行预留手机号 """ def __init__(self, card_no=None, id_card=None, real_name=None, mobile=None): super().__init__() self.card_no = card_no self.id_card = id_card self.real_name = real_name self.mobile = mobile def get_card_no(self): """ Get 银行卡号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 银行卡号 :type card_no: string :param card_no: 银行卡号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_mobile(self): """ Get 银行预留手机号 :return: string, mobile """ return self.mobile def set_mobile(self, mobile): """ Set 银行预留手机号 :type mobile: string :param mobile: 银行预留手机号 """ self.mobile = mobile class BankCardFourVerifyResponse(BaseRequest): """ """ def __init__(self): super().__init__() class BankCardThreeVerifyRequest(BaseRequest): """ :type card_no: string :param card_no: 银行卡号 :type id_card: string :param id_card: 身份证号码 :type real_name: string :param real_name: 姓名 """ def __init__(self, card_no=None, id_card=None, real_name=None): super().__init__() self.card_no = card_no self.id_card = id_card self.real_name = real_name def get_card_no(self): """ Get 银行卡号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 银行卡号 :type card_no: string :param card_no: 银行卡号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name class BankCardThreeVerifyResponse(BaseRequest): """ """ def __init__(self): super().__init__() class IDCardVerifyRequest(BaseRequest): """ :type id_card: string :param id_card: 身份证号码 :type real_name: string :param real_name: 姓名 """ def __init__(self, id_card=None, real_name=None): super().__init__() self.id_card = id_card self.real_name = real_name def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name class IDCardVerifyResponse(BaseRequest): """ """ def __init__(self): super().__init__() class UserExemptedInfoRequest(BaseRequest): """ :type card_type: string :param card_type: 证件类型码 :type id_card: string :param id_card: 证件号码 :type real_name: string :param real_name: 姓名 :type comment_apply: string :param comment_apply: 申请备注 :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type user_images: list :param user_images: 人员信息图片 :type country: string :param country: 国别(地区)代码 :type birthday: string :param birthday: 出生日期 :type gender: string :param gender: 性别 :type notify_url: string :param notify_url: 回调地址 :type ref: string :param ref: 请求流水号 """ def __init__(self, card_type=None, id_card=None, real_name=None, comment_apply=None, broker_id=None, dealer_id=None, user_images=None, country=None, birthday=None, gender=None, notify_url=None, ref=None): super().__init__() self.card_type = card_type self.id_card = id_card self.real_name = real_name self.comment_apply = comment_apply self.broker_id = broker_id self.dealer_id = dealer_id self.user_images = user_images self.country = country self.birthday = birthday self.gender = gender self.notify_url = notify_url self.ref = ref def get_card_type(self): """ Get 证件类型码 :return: string, card_type """ return self.card_type def set_card_type(self, card_type): """ Set 证件类型码 :type card_type: string :param card_type: 证件类型码 """ self.card_type = card_type def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_comment_apply(self): """ Get 申请备注 :return: string, comment_apply """ return self.comment_apply def set_comment_apply(self, comment_apply): """ Set 申请备注 :type comment_apply: string :param comment_apply: 申请备注 """ self.comment_apply = comment_apply def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_user_images(self): """ Get 人员信息图片 :return: list, user_images """ return self.user_images def set_user_images(self, user_images): """ Set 人员信息图片 :type user_images: list :param user_images: 人员信息图片 """ self.user_images = user_images def get_country(self): """ Get 国别(地区)代码 :return: string, country """ return self.country def set_country(self, country): """ Set 国别(地区)代码 :type country: string :param country: 国别(地区)代码 """ self.country = country def get_birthday(self): """ Get 出生日期 :return: string, birthday """ return self.birthday def set_birthday(self, birthday): """ Set 出生日期 :type birthday: string :param birthday: 出生日期 """ self.birthday = birthday def get_gender(self): """ Get 性别 :return: string, gender """ return self.gender def set_gender(self, gender): """ Set 性别 :type gender: string :param gender: 性别 """ self.gender = gender def get_notify_url(self): """ Get 回调地址 :return: string, notify_url """ return self.notify_url def set_notify_url(self, notify_url): """ Set 回调地址 :type notify_url: string :param notify_url: 回调地址 """ self.notify_url = notify_url def get_ref(self): """ Get 请求流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 请求流水号 :type ref: string :param ref: 请求流水号 """ self.ref = ref class UserExemptedInfoResponse(BaseRequest): """ :type ok: string :param ok: 是否上传成功 """ def __init__(self, ok=None): super().__init__() self.ok = ok def get_ok(self): """ Get 是否上传成功 :return: string, ok """ return self.ok def set_ok(self, ok): """ Set 是否上传成功 :type ok: string :param ok: 是否上传成功 """ self.ok = ok class UserWhiteCheckRequest(BaseRequest): """ :type id_card: string :param id_card: 证件号码 :type real_name: string :param real_name: 姓名 """ def __init__(self, id_card=None, real_name=None): super().__init__() self.id_card = id_card self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name class UserWhiteCheckResponse(BaseRequest): """ :type ok: bool :param ok: """ def __init__(self, ok=None): super().__init__() self.ok = ok def get_ok(self): """ Get :return: bool, ok """ return self.ok def set_ok(self, ok): """ Set :type ok: bool :param ok: """ self.ok = ok class GetBankCardInfoRequest(BaseRequest): """ :type card_no: string :param card_no: 银行卡号 :type bank_name: string :param bank_name: 银行名称 """ def __init__(self, card_no=None, bank_name=None): super().__init__() self.card_no = card_no self.bank_name = bank_name def get_card_no(self): """ Get 银行卡号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 银行卡号 :type card_no: string :param card_no: 银行卡号 """ self.card_no = card_no def get_bank_name(self): """ Get 银行名称 :return: string, bank_name """ return self.bank_name def set_bank_name(self, bank_name): """ Set 银行名称 :type bank_name: string :param bank_name: 银行名称 """ self.bank_name = bank_name class GetBankCardInfoResponse(BaseRequest): """ :type bank_code: string :param bank_code: 银行代码 :type bank_name: string :param bank_name: 银行名称 :type card_type: string :param card_type: 卡类型 :type is_support: bool :param is_support: 云账户是否支持向该银行支付 """ def __init__(self, bank_code=None, bank_name=None, card_type=None, is_support=None): super().__init__() self.bank_code = bank_code self.bank_name = bank_name self.card_type = card_type self.is_support = is_support def get_bank_code(self): """ Get 银行代码 :return: string, bank_code """ return self.bank_code def set_bank_code(self, bank_code): """ Set 银行代码 :type bank_code: string :param bank_code: 银行代码 """ self.bank_code = bank_code def get_bank_name(self): """ Get 银行名称 :return: string, bank_name """ return self.bank_name def set_bank_name(self, bank_name): """ Set 银行名称 :type bank_name: string :param bank_name: 银行名称 """ self.bank_name = bank_name def get_card_type(self): """ Get 卡类型 :return: string, card_type """ return self.card_type def set_card_type(self, card_type): """ Set 卡类型 :type card_type: string :param card_type: 卡类型 """ self.card_type = card_type def get_is_support(self): """ Get 云账户是否支持向该银行支付 :return: bool, is_support """ return self.is_support def set_is_support(self, is_support): """ Set 云账户是否支持向该银行支付 :type is_support: bool :param is_support: 云账户是否支持向该银行支付 """ self.is_support = is_support
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/authentication.py
authentication.py
from ...base import BaseRequest class ApiUseSignContractRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ def __init__(self, dealer_id=None, broker_id=None): super().__init__() self.dealer_id = dealer_id self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id class ApiUseSignContractResponse(BaseRequest): """ :type url: string :param url: 预览跳转 URL :type title: string :param title: 协议名称 """ def __init__(self, url=None, title=None): super().__init__() self.url = url self.title = title def get_url(self): """ Get 预览跳转 URL :return: string, url """ return self.url def set_url(self, url): """ Set 预览跳转 URL :type url: string :param url: 预览跳转 URL """ self.url = url def get_title(self): """ Get 协议名称 :return: string, title """ return self.title def set_title(self, title): """ Set 协议名称 :type title: string :param title: 协议名称 """ self.title = title class ApiUserSignRequest(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 证件号码 :type card_type: string :param card_type: 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 """ def __init__(self, broker_id=None, dealer_id=None, real_name=None, id_card=None, card_type=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id self.real_name = real_name self.id_card = id_card self.card_type = card_type def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card def get_card_type(self): """ Get 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 :return: string, card_type """ return self.card_type def set_card_type(self, card_type): """ Set 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 :type card_type: string :param card_type: 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 """ self.card_type = card_type class ApiUserSignResponse(BaseRequest): """ :type status: string :param status: 是否签约成功 """ def __init__(self, status=None): super().__init__() self.status = status def get_status(self): """ Get 是否签约成功 :return: string, status """ return self.status def set_status(self, status): """ Set 是否签约成功 :type status: string :param status: 是否签约成功 """ self.status = status class GetApiUserSignStatusRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 证件号码 """ def __init__(self, dealer_id=None, broker_id=None, real_name=None, id_card=None): super().__init__() self.dealer_id = dealer_id self.broker_id = broker_id self.real_name = real_name self.id_card = id_card def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card class GetApiUserSignStatusResponse(BaseRequest): """ :type signed_at: string :param signed_at: 签约时间 :type status: int :param status: 用户签约状态 """ def __init__(self, signed_at=None, status=None): super().__init__() self.signed_at = signed_at self.status = status def get_signed_at(self): """ Get 签约时间 :return: string, signed_at """ return self.signed_at def set_signed_at(self, signed_at): """ Set 签约时间 :type signed_at: string :param signed_at: 签约时间 """ self.signed_at = signed_at def get_status(self): """ Get 用户签约状态 :return: int, status """ return self.status def set_status(self, status): """ Set 用户签约状态 :type status: int :param status: 用户签约状态 """ self.status = status class ApiUserSignReleaseRequest(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 证件号码 :type card_type: string :param card_type: 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 """ def __init__(self, broker_id=None, dealer_id=None, real_name=None, id_card=None, card_type=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id self.real_name = real_name self.id_card = id_card self.card_type = card_type def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 证件号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 证件号码 :type id_card: string :param id_card: 证件号码 """ self.id_card = id_card def get_card_type(self): """ Get 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 :return: string, card_type """ return self.card_type def set_card_type(self, card_type): """ Set 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 :type card_type: string :param card_type: 证件类型 idcard:身份证 mtphkm:港澳居民来往内地通行证 passport:护照 mtpt:台湾居民往来大陆通行证 """ self.card_type = card_type class ApiUserSignReleaseResponse(BaseRequest): """ :type status: string :param status: 是否解约成功 """ def __init__(self, status=None): super().__init__() self.status = status def get_status(self): """ Get 是否解约成功 :return: string, status """ return self.status def set_status(self, status): """ Set 是否解约成功 :type status: string :param status: 是否解约成功 """ self.status = status
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/apiusersign.py
apiusersign.py
from ...base import BaseRequest class CreateBankpayOrderRequest(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type real_name: string :param real_name: 姓名 :type card_no: string :param card_no: 银行卡号 :type id_card: string :param id_card: 身份证号码 :type phone_no: string :param phone_no: 手机号 :type pay: string :param pay: 订单金额 :type pay_remark: string :param pay_remark: 订单备注 :type notify_url: string :param notify_url: 回调地址 :type project_id: string :param project_id: 项目标识 """ def __init__(self, order_id=None, dealer_id=None, broker_id=None, real_name=None, card_no=None, id_card=None, phone_no=None, pay=None, pay_remark=None, notify_url=None, project_id=None): super().__init__() self.order_id = order_id self.dealer_id = dealer_id self.broker_id = broker_id self.real_name = real_name self.card_no = card_no self.id_card = id_card self.phone_no = phone_no self.pay = pay self.pay_remark = pay_remark self.notify_url = notify_url self.project_id = project_id def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_card_no(self): """ Get 银行卡号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 银行卡号 :type card_no: string :param card_no: 银行卡号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_phone_no(self): """ Get 手机号 :return: string, phone_no """ return self.phone_no def set_phone_no(self, phone_no): """ Set 手机号 :type phone_no: string :param phone_no: 手机号 """ self.phone_no = phone_no def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay def get_pay_remark(self): """ Get 订单备注 :return: string, pay_remark """ return self.pay_remark def set_pay_remark(self, pay_remark): """ Set 订单备注 :type pay_remark: string :param pay_remark: 订单备注 """ self.pay_remark = pay_remark def get_notify_url(self): """ Get 回调地址 :return: string, notify_url """ return self.notify_url def set_notify_url(self, notify_url): """ Set 回调地址 :type notify_url: string :param notify_url: 回调地址 """ self.notify_url = notify_url def get_project_id(self): """ Get 项目标识 :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目标识 :type project_id: string :param project_id: 项目标识 """ self.project_id = project_id class CreateBankpayOrderResponse(BaseRequest): """ :type order_id: string :param order_id: :type ref: string :param ref: 综合服务平台流水号 :type pay: string :param pay: 订单金额 """ def __init__(self, order_id=None, ref=None, pay=None): super().__init__() self.order_id = order_id self.ref = ref self.pay = pay def get_order_id(self): """ Get :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set :type order_id: string :param order_id: """ self.order_id = order_id def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay class CreateAlipayOrderRequest(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type real_name: string :param real_name: 姓名 :type card_no: string :param card_no: 支付宝账户 :type id_card: string :param id_card: 身份证号码 :type phone_no: string :param phone_no: 手机号 :type pay: string :param pay: 订单金额 :type pay_remark: string :param pay_remark: 订单备注 :type notify_url: string :param notify_url: 回调地址 :type project_id: string :param project_id: 项目标识 :type check_name: string :param check_name: 校验支付宝账户姓名,固定值:Check """ def __init__(self, order_id=None, dealer_id=None, broker_id=None, real_name=None, card_no=None, id_card=None, phone_no=None, pay=None, pay_remark=None, notify_url=None, project_id=None, check_name=None): super().__init__() self.order_id = order_id self.dealer_id = dealer_id self.broker_id = broker_id self.real_name = real_name self.card_no = card_no self.id_card = id_card self.phone_no = phone_no self.pay = pay self.pay_remark = pay_remark self.notify_url = notify_url self.project_id = project_id self.check_name = check_name def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_card_no(self): """ Get 支付宝账户 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 支付宝账户 :type card_no: string :param card_no: 支付宝账户 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_phone_no(self): """ Get 手机号 :return: string, phone_no """ return self.phone_no def set_phone_no(self, phone_no): """ Set 手机号 :type phone_no: string :param phone_no: 手机号 """ self.phone_no = phone_no def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay def get_pay_remark(self): """ Get 订单备注 :return: string, pay_remark """ return self.pay_remark def set_pay_remark(self, pay_remark): """ Set 订单备注 :type pay_remark: string :param pay_remark: 订单备注 """ self.pay_remark = pay_remark def get_notify_url(self): """ Get 回调地址 :return: string, notify_url """ return self.notify_url def set_notify_url(self, notify_url): """ Set 回调地址 :type notify_url: string :param notify_url: 回调地址 """ self.notify_url = notify_url def get_project_id(self): """ Get 项目标识 :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目标识 :type project_id: string :param project_id: 项目标识 """ self.project_id = project_id def get_check_name(self): """ Get 校验支付宝账户姓名,固定值:Check :return: string, check_name """ return self.check_name def set_check_name(self, check_name): """ Set 校验支付宝账户姓名,固定值:Check :type check_name: string :param check_name: 校验支付宝账户姓名,固定值:Check """ self.check_name = check_name class CreateAlipayOrderResponse(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 综合服务平台流水号 :type pay: string :param pay: 订单金额 """ def __init__(self, order_id=None, ref=None, pay=None): super().__init__() self.order_id = order_id self.ref = ref self.pay = pay def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay class CreateWxpayOrderRequest(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type dealer_id: string :param dealer_id: 平台企业 ID :type broker_id: string :param broker_id: 综合服务主体 ID :type real_name: string :param real_name: 姓名 :type openid: string :param openid: 微信用户 openid :type id_card: string :param id_card: 身份证号码 :type phone_no: string :param phone_no: 手机号 :type pay: string :param pay: 订单金额 :type pay_remark: string :param pay_remark: 订单备注 :type notify_url: string :param notify_url: 回调地址 :type wx_app_id: string :param wx_app_id: 平台企业微信 AppID :type wxpay_mode: string :param wxpay_mode: 微信支付模式,固定值:transfer :type project_id: string :param project_id: 项目标识 :type notes: string :param notes: 描述信息,该字段已废弃 """ def __init__(self, order_id=None, dealer_id=None, broker_id=None, real_name=None, openid=None, id_card=None, phone_no=None, pay=None, pay_remark=None, notify_url=None, wx_app_id=None, wxpay_mode=None, project_id=None, notes=None): super().__init__() self.order_id = order_id self.dealer_id = dealer_id self.broker_id = broker_id self.real_name = real_name self.openid = openid self.id_card = id_card self.phone_no = phone_no self.pay = pay self.pay_remark = pay_remark self.notify_url = notify_url self.wx_app_id = wx_app_id self.wxpay_mode = wxpay_mode self.project_id = project_id self.notes = notes def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_openid(self): """ Get 微信用户 openid :return: string, openid """ return self.openid def set_openid(self, openid): """ Set 微信用户 openid :type openid: string :param openid: 微信用户 openid """ self.openid = openid def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_phone_no(self): """ Get 手机号 :return: string, phone_no """ return self.phone_no def set_phone_no(self, phone_no): """ Set 手机号 :type phone_no: string :param phone_no: 手机号 """ self.phone_no = phone_no def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay def get_pay_remark(self): """ Get 订单备注 :return: string, pay_remark """ return self.pay_remark def set_pay_remark(self, pay_remark): """ Set 订单备注 :type pay_remark: string :param pay_remark: 订单备注 """ self.pay_remark = pay_remark def get_notify_url(self): """ Get 回调地址 :return: string, notify_url """ return self.notify_url def set_notify_url(self, notify_url): """ Set 回调地址 :type notify_url: string :param notify_url: 回调地址 """ self.notify_url = notify_url def get_wx_app_id(self): """ Get 平台企业微信 AppID :return: string, wx_app_id """ return self.wx_app_id def set_wx_app_id(self, wx_app_id): """ Set 平台企业微信 AppID :type wx_app_id: string :param wx_app_id: 平台企业微信 AppID """ self.wx_app_id = wx_app_id def get_wxpay_mode(self): """ Get 微信支付模式,固定值:transfer :return: string, wxpay_mode """ return self.wxpay_mode def set_wxpay_mode(self, wxpay_mode): """ Set 微信支付模式,固定值:transfer :type wxpay_mode: string :param wxpay_mode: 微信支付模式,固定值:transfer """ self.wxpay_mode = wxpay_mode def get_project_id(self): """ Get 项目标识 :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目标识 :type project_id: string :param project_id: 项目标识 """ self.project_id = project_id def get_notes(self): """ Get 描述信息,该字段已废弃 :return: string, notes """ return self.notes def set_notes(self, notes): """ Set 描述信息,该字段已废弃 :type notes: string :param notes: 描述信息,该字段已废弃 """ self.notes = notes class CreateWxpayOrderResponse(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 综合服务平台流水号,唯一 :type pay: string :param pay: 订单金额 """ def __init__(self, order_id=None, ref=None, pay=None): super().__init__() self.order_id = order_id self.ref = ref self.pay = pay def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 综合服务平台流水号,唯一 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号,唯一 :type ref: string :param ref: 综合服务平台流水号,唯一 """ self.ref = ref def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay class GetOrderRequest(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type channel: string :param channel: 支付路径名,银行卡(默认)、支付宝、微信 :type data_type: string :param data_type: 数据类型,如果为 encryption,则对返回的 data 进行加密 """ def __init__(self, order_id=None, channel=None, data_type=None): super().__init__() self.order_id = order_id self.channel = channel self.data_type = data_type def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_channel(self): """ Get 支付路径名,银行卡(默认)、支付宝、微信 :return: string, channel """ return self.channel def set_channel(self, channel): """ Set 支付路径名,银行卡(默认)、支付宝、微信 :type channel: string :param channel: 支付路径名,银行卡(默认)、支付宝、微信 """ self.channel = channel def get_data_type(self): """ Get 数据类型,如果为 encryption,则对返回的 data 进行加密 :return: string, data_type """ return self.data_type def set_data_type(self, data_type): """ Set 数据类型,如果为 encryption,则对返回的 data 进行加密 :type data_type: string :param data_type: 数据类型,如果为 encryption,则对返回的 data 进行加密 """ self.data_type = data_type class GetOrderResponse(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type pay: string :param pay: 订单金额 :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type real_name: string :param real_name: 姓名 :type card_no: string :param card_no: 收款人账号 :type id_card: string :param id_card: 身份证号码 :type phone_no: string :param phone_no: 手机号 :type status: string :param status: 订单状态码 :type status_detail: string :param status_detail: 订单详细状态码 :type status_message: string :param status_message: 订单状态码描述 :type status_detail_message: string :param status_detail_message: 订单详细状态码描述 :type broker_amount: string :param broker_amount: 综合服务主体支付金额 :type ref: string :param ref: 综合服务平台流水号 :type broker_bank_bill: string :param broker_bank_bill: 支付交易流水号 :type withdraw_platform: string :param withdraw_platform: 支付路径 :type created_at: string :param created_at: 订单接收时间,精确到秒 :type finished_time: string :param finished_time: 订单完成时间,精确到秒 :type broker_fee: string :param broker_fee: 综合服务主体加成服务费 :type broker_real_fee: string :param broker_real_fee: 余额账户支出加成服务费 :type broker_deduct_fee: string :param broker_deduct_fee: 抵扣账户支出加成服务费 :type pay_remark: string :param pay_remark: 订单备注 :type user_fee: string :param user_fee: 用户加成服务费 :type bank_name: string :param bank_name: 银行名称 :type project_id: string :param project_id: 项目标识 :type anchor_id: string :param anchor_id: 新就业形态劳动者 ID,该字段已废弃 :type notes: string :param notes: 描述信息,该字段已废弃 :type sys_amount: string :param sys_amount: 系统支付金额,该字段已废弃 :type tax: string :param tax: 税费,该字段已废弃 :type sys_fee: string :param sys_fee: 系统支付费用,该字段已废弃 """ def __init__(self, order_id=None, pay=None, broker_id=None, dealer_id=None, real_name=None, card_no=None, id_card=None, phone_no=None, status=None, status_detail=None, status_message=None, status_detail_message=None, broker_amount=None, ref=None, broker_bank_bill=None, withdraw_platform=None, created_at=None, finished_time=None, broker_fee=None, broker_real_fee=None, broker_deduct_fee=None, pay_remark=None, user_fee=None, bank_name=None, project_id=None, anchor_id=None, notes=None, sys_amount=None, tax=None, sys_fee=None): super().__init__() self.order_id = order_id self.pay = pay self.broker_id = broker_id self.dealer_id = dealer_id self.real_name = real_name self.card_no = card_no self.id_card = id_card self.phone_no = phone_no self.status = status self.status_detail = status_detail self.status_message = status_message self.status_detail_message = status_detail_message self.broker_amount = broker_amount self.ref = ref self.broker_bank_bill = broker_bank_bill self.withdraw_platform = withdraw_platform self.created_at = created_at self.finished_time = finished_time self.broker_fee = broker_fee self.broker_real_fee = broker_real_fee self.broker_deduct_fee = broker_deduct_fee self.pay_remark = pay_remark self.user_fee = user_fee self.bank_name = bank_name self.project_id = project_id self.anchor_id = anchor_id self.notes = notes self.sys_amount = sys_amount self.tax = tax self.sys_fee = sys_fee def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_card_no(self): """ Get 收款人账号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 收款人账号 :type card_no: string :param card_no: 收款人账号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_phone_no(self): """ Get 手机号 :return: string, phone_no """ return self.phone_no def set_phone_no(self, phone_no): """ Set 手机号 :type phone_no: string :param phone_no: 手机号 """ self.phone_no = phone_no def get_status(self): """ Get 订单状态码 :return: string, status """ return self.status def set_status(self, status): """ Set 订单状态码 :type status: string :param status: 订单状态码 """ self.status = status def get_status_detail(self): """ Get 订单详细状态码 :return: string, status_detail """ return self.status_detail def set_status_detail(self, status_detail): """ Set 订单详细状态码 :type status_detail: string :param status_detail: 订单详细状态码 """ self.status_detail = status_detail def get_status_message(self): """ Get 订单状态码描述 :return: string, status_message """ return self.status_message def set_status_message(self, status_message): """ Set 订单状态码描述 :type status_message: string :param status_message: 订单状态码描述 """ self.status_message = status_message def get_status_detail_message(self): """ Get 订单详细状态码描述 :return: string, status_detail_message """ return self.status_detail_message def set_status_detail_message(self, status_detail_message): """ Set 订单详细状态码描述 :type status_detail_message: string :param status_detail_message: 订单详细状态码描述 """ self.status_detail_message = status_detail_message def get_broker_amount(self): """ Get 综合服务主体支付金额 :return: string, broker_amount """ return self.broker_amount def set_broker_amount(self, broker_amount): """ Set 综合服务主体支付金额 :type broker_amount: string :param broker_amount: 综合服务主体支付金额 """ self.broker_amount = broker_amount def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref def get_broker_bank_bill(self): """ Get 支付交易流水号 :return: string, broker_bank_bill """ return self.broker_bank_bill def set_broker_bank_bill(self, broker_bank_bill): """ Set 支付交易流水号 :type broker_bank_bill: string :param broker_bank_bill: 支付交易流水号 """ self.broker_bank_bill = broker_bank_bill def get_withdraw_platform(self): """ Get 支付路径 :return: string, withdraw_platform """ return self.withdraw_platform def set_withdraw_platform(self, withdraw_platform): """ Set 支付路径 :type withdraw_platform: string :param withdraw_platform: 支付路径 """ self.withdraw_platform = withdraw_platform def get_created_at(self): """ Get 订单接收时间,精确到秒 :return: string, created_at """ return self.created_at def set_created_at(self, created_at): """ Set 订单接收时间,精确到秒 :type created_at: string :param created_at: 订单接收时间,精确到秒 """ self.created_at = created_at def get_finished_time(self): """ Get 订单完成时间,精确到秒 :return: string, finished_time """ return self.finished_time def set_finished_time(self, finished_time): """ Set 订单完成时间,精确到秒 :type finished_time: string :param finished_time: 订单完成时间,精确到秒 """ self.finished_time = finished_time def get_broker_fee(self): """ Get 综合服务主体加成服务费 :return: string, broker_fee """ return self.broker_fee def set_broker_fee(self, broker_fee): """ Set 综合服务主体加成服务费 :type broker_fee: string :param broker_fee: 综合服务主体加成服务费 """ self.broker_fee = broker_fee def get_broker_real_fee(self): """ Get 余额账户支出加成服务费 :return: string, broker_real_fee """ return self.broker_real_fee def set_broker_real_fee(self, broker_real_fee): """ Set 余额账户支出加成服务费 :type broker_real_fee: string :param broker_real_fee: 余额账户支出加成服务费 """ self.broker_real_fee = broker_real_fee def get_broker_deduct_fee(self): """ Get 抵扣账户支出加成服务费 :return: string, broker_deduct_fee """ return self.broker_deduct_fee def set_broker_deduct_fee(self, broker_deduct_fee): """ Set 抵扣账户支出加成服务费 :type broker_deduct_fee: string :param broker_deduct_fee: 抵扣账户支出加成服务费 """ self.broker_deduct_fee = broker_deduct_fee def get_pay_remark(self): """ Get 订单备注 :return: string, pay_remark """ return self.pay_remark def set_pay_remark(self, pay_remark): """ Set 订单备注 :type pay_remark: string :param pay_remark: 订单备注 """ self.pay_remark = pay_remark def get_user_fee(self): """ Get 用户加成服务费 :return: string, user_fee """ return self.user_fee def set_user_fee(self, user_fee): """ Set 用户加成服务费 :type user_fee: string :param user_fee: 用户加成服务费 """ self.user_fee = user_fee def get_bank_name(self): """ Get 银行名称 :return: string, bank_name """ return self.bank_name def set_bank_name(self, bank_name): """ Set 银行名称 :type bank_name: string :param bank_name: 银行名称 """ self.bank_name = bank_name def get_project_id(self): """ Get 项目标识 :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目标识 :type project_id: string :param project_id: 项目标识 """ self.project_id = project_id def get_anchor_id(self): """ Get 新就业形态劳动者 ID,该字段已废弃 :return: string, anchor_id """ return self.anchor_id def set_anchor_id(self, anchor_id): """ Set 新就业形态劳动者 ID,该字段已废弃 :type anchor_id: string :param anchor_id: 新就业形态劳动者 ID,该字段已废弃 """ self.anchor_id = anchor_id def get_notes(self): """ Get 描述信息,该字段已废弃 :return: string, notes """ return self.notes def set_notes(self, notes): """ Set 描述信息,该字段已废弃 :type notes: string :param notes: 描述信息,该字段已废弃 """ self.notes = notes def get_sys_amount(self): """ Get 系统支付金额,该字段已废弃 :return: string, sys_amount """ return self.sys_amount def set_sys_amount(self, sys_amount): """ Set 系统支付金额,该字段已废弃 :type sys_amount: string :param sys_amount: 系统支付金额,该字段已废弃 """ self.sys_amount = sys_amount def get_tax(self): """ Get 税费,该字段已废弃 :return: string, tax """ return self.tax def set_tax(self, tax): """ Set 税费,该字段已废弃 :type tax: string :param tax: 税费,该字段已废弃 """ self.tax = tax def get_sys_fee(self): """ Get 系统支付费用,该字段已废弃 :return: string, sys_fee """ return self.sys_fee def set_sys_fee(self, sys_fee): """ Set 系统支付费用,该字段已废弃 :type sys_fee: string :param sys_fee: 系统支付费用,该字段已废弃 """ self.sys_fee = sys_fee class GetDealerVARechargeAccountRequest(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ def __init__(self, broker_id=None, dealer_id=None): super().__init__() self.broker_id = broker_id self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id class GetDealerVARechargeAccountResponse(BaseRequest): """ :type acct_name: string :param acct_name: 账户名称 :type acct_no: string :param acct_no: 专属账户 :type bank_name: string :param bank_name: 银行名称 :type dealer_acct_name: string :param dealer_acct_name: 付款账户 """ def __init__(self, acct_name=None, acct_no=None, bank_name=None, dealer_acct_name=None): super().__init__() self.acct_name = acct_name self.acct_no = acct_no self.bank_name = bank_name self.dealer_acct_name = dealer_acct_name def get_acct_name(self): """ Get 账户名称 :return: string, acct_name """ return self.acct_name def set_acct_name(self, acct_name): """ Set 账户名称 :type acct_name: string :param acct_name: 账户名称 """ self.acct_name = acct_name def get_acct_no(self): """ Get 专属账户 :return: string, acct_no """ return self.acct_no def set_acct_no(self, acct_no): """ Set 专属账户 :type acct_no: string :param acct_no: 专属账户 """ self.acct_no = acct_no def get_bank_name(self): """ Get 银行名称 :return: string, bank_name """ return self.bank_name def set_bank_name(self, bank_name): """ Set 银行名称 :type bank_name: string :param bank_name: 银行名称 """ self.bank_name = bank_name def get_dealer_acct_name(self): """ Get 付款账户 :return: string, dealer_acct_name """ return self.dealer_acct_name def set_dealer_acct_name(self, dealer_acct_name): """ Set 付款账户 :type dealer_acct_name: string :param dealer_acct_name: 付款账户 """ self.dealer_acct_name = dealer_acct_name class CancelOrderRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 综合服务平台流水号 :type channel: string :param channel: 支付路径名,银行卡(默认)、支付宝、微信 """ def __init__(self, dealer_id=None, order_id=None, ref=None, channel=None): super().__init__() self.dealer_id = dealer_id self.order_id = order_id self.ref = ref self.channel = channel def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref def get_channel(self): """ Get 支付路径名,银行卡(默认)、支付宝、微信 :return: string, channel """ return self.channel def set_channel(self, channel): """ Set 支付路径名,银行卡(默认)、支付宝、微信 :type channel: string :param channel: 支付路径名,银行卡(默认)、支付宝、微信 """ self.channel = channel class CancelOrderResponse(BaseRequest): """ :type ok: string :param ok: """ def __init__(self, ok=None): super().__init__() self.ok = ok def get_ok(self): """ Get :return: string, ok """ return self.ok def set_ok(self, ok): """ Set :type ok: string :param ok: """ self.ok = ok class ListAccountRequest(BaseRequest): """ :type dealer_id: string :param dealer_id: 平台企业 ID """ def __init__(self, dealer_id=None): super().__init__() self.dealer_id = dealer_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id class ListAccountResponse(BaseRequest): """ :type dealer_infos: list :param dealer_infos: """ def __init__(self, dealer_infos=None): super().__init__() self.dealer_infos = dealer_infos def get_dealer_infos(self): """ Get :return: list, dealer_infos """ return self.dealer_infos def set_dealer_infos(self, dealer_infos): """ Set :type dealer_infos: list :param dealer_infos: """ self.dealer_infos = dealer_infos class AccountInfo(BaseRequest): """ :type broker_id: string :param broker_id: 综合服务主体 ID :type bank_card_balance: string :param bank_card_balance: 银行卡余额 :type is_bank_card: bool :param is_bank_card: 是否开通银行卡支付路径 :type alipay_balance: string :param alipay_balance: 支付宝余额 :type is_alipay: bool :param is_alipay: 是否开通支付宝支付路径 :type wxpay_balance: string :param wxpay_balance: 微信余额 :type is_wxpay: bool :param is_wxpay: 是否开通微信支付路径 :type rebate_fee_balance: string :param rebate_fee_balance: 加成服务费返点余额 :type acct_balance: string :param acct_balance: 业务服务费余额 :type total_balance: string :param total_balance: 总余额 """ def __init__(self, broker_id=None, bank_card_balance=None, is_bank_card=None, alipay_balance=None, is_alipay=None, wxpay_balance=None, is_wxpay=None, rebate_fee_balance=None, acct_balance=None, total_balance=None): super().__init__() self.broker_id = broker_id self.bank_card_balance = bank_card_balance self.is_bank_card = is_bank_card self.alipay_balance = alipay_balance self.is_alipay = is_alipay self.wxpay_balance = wxpay_balance self.is_wxpay = is_wxpay self.rebate_fee_balance = rebate_fee_balance self.acct_balance = acct_balance self.total_balance = total_balance def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_bank_card_balance(self): """ Get 银行卡余额 :return: string, bank_card_balance """ return self.bank_card_balance def set_bank_card_balance(self, bank_card_balance): """ Set 银行卡余额 :type bank_card_balance: string :param bank_card_balance: 银行卡余额 """ self.bank_card_balance = bank_card_balance def get_is_bank_card(self): """ Get 是否开通银行卡支付路径 :return: bool, is_bank_card """ return self.is_bank_card def set_is_bank_card(self, is_bank_card): """ Set 是否开通银行卡支付路径 :type is_bank_card: bool :param is_bank_card: 是否开通银行卡支付路径 """ self.is_bank_card = is_bank_card def get_alipay_balance(self): """ Get 支付宝余额 :return: string, alipay_balance """ return self.alipay_balance def set_alipay_balance(self, alipay_balance): """ Set 支付宝余额 :type alipay_balance: string :param alipay_balance: 支付宝余额 """ self.alipay_balance = alipay_balance def get_is_alipay(self): """ Get 是否开通支付宝支付路径 :return: bool, is_alipay """ return self.is_alipay def set_is_alipay(self, is_alipay): """ Set 是否开通支付宝支付路径 :type is_alipay: bool :param is_alipay: 是否开通支付宝支付路径 """ self.is_alipay = is_alipay def get_wxpay_balance(self): """ Get 微信余额 :return: string, wxpay_balance """ return self.wxpay_balance def set_wxpay_balance(self, wxpay_balance): """ Set 微信余额 :type wxpay_balance: string :param wxpay_balance: 微信余额 """ self.wxpay_balance = wxpay_balance def get_is_wxpay(self): """ Get 是否开通微信支付路径 :return: bool, is_wxpay """ return self.is_wxpay def set_is_wxpay(self, is_wxpay): """ Set 是否开通微信支付路径 :type is_wxpay: bool :param is_wxpay: 是否开通微信支付路径 """ self.is_wxpay = is_wxpay def get_rebate_fee_balance(self): """ Get 加成服务费返点余额 :return: string, rebate_fee_balance """ return self.rebate_fee_balance def set_rebate_fee_balance(self, rebate_fee_balance): """ Set 加成服务费返点余额 :type rebate_fee_balance: string :param rebate_fee_balance: 加成服务费返点余额 """ self.rebate_fee_balance = rebate_fee_balance def get_acct_balance(self): """ Get 业务服务费余额 :return: string, acct_balance """ return self.acct_balance def set_acct_balance(self, acct_balance): """ Set 业务服务费余额 :type acct_balance: string :param acct_balance: 业务服务费余额 """ self.acct_balance = acct_balance def get_total_balance(self): """ Get 总余额 :return: string, total_balance """ return self.total_balance def set_total_balance(self, total_balance): """ Set 总余额 :type total_balance: string :param total_balance: 总余额 """ self.total_balance = total_balance class GetEleReceiptFileRequest(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 综合服务平台流水号 """ def __init__(self, order_id=None, ref=None): super().__init__() self.order_id = order_id self.ref = ref def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref class GetEleReceiptFileResponse(BaseRequest): """ :type expire_time: string :param expire_time: 链接失效时间 :type file_name: string :param file_name: 回单名 :type url: string :param url: 下载链接 """ def __init__(self, expire_time=None, file_name=None, url=None): super().__init__() self.expire_time = expire_time self.file_name = file_name self.url = url def get_expire_time(self): """ Get 链接失效时间 :return: string, expire_time """ return self.expire_time def set_expire_time(self, expire_time): """ Set 链接失效时间 :type expire_time: string :param expire_time: 链接失效时间 """ self.expire_time = expire_time def get_file_name(self): """ Get 回单名 :return: string, file_name """ return self.file_name def set_file_name(self, file_name): """ Set 回单名 :type file_name: string :param file_name: 回单名 """ self.file_name = file_name def get_url(self): """ Get 下载链接 :return: string, url """ return self.url def set_url(self, url): """ Set 下载链接 :type url: string :param url: 下载链接 """ self.url = url class NotifyOrderRequest(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type pay: string :param pay: 订单金额 :type broker_id: string :param broker_id: 综合服务主体 ID :type dealer_id: string :param dealer_id: 平台企业 ID :type real_name: string :param real_name: 姓名 :type card_no: string :param card_no: 收款人账号 :type id_card: string :param id_card: 身份证号码 :type phone_no: string :param phone_no: 手机号 :type status: string :param status: 订单状态码 :type status_detail: string :param status_detail: 订单详细状态码 :type status_message: string :param status_message: 订单状态码描述 :type status_detail_message: string :param status_detail_message: 订单详细状态码描述 :type broker_amount: string :param broker_amount: 综合服务主体支付金额 :type ref: string :param ref: 综合服务平台流水号 :type broker_bank_bill: string :param broker_bank_bill: 支付交易流水号 :type withdraw_platform: string :param withdraw_platform: 支付路径 :type created_at: string :param created_at: 订单接收时间,精确到秒 :type finished_time: string :param finished_time: 订单完成时间,精确到秒 :type broker_fee: string :param broker_fee: 综合服务主体加成服务费 :type broker_real_fee: string :param broker_real_fee: 余额账户支出加成服务费 :type broker_deduct_fee: string :param broker_deduct_fee: 抵扣账户支出加成服务费 :type pay_remark: string :param pay_remark: 订单备注 :type user_fee: string :param user_fee: 用户加成服务费 :type bank_name: string :param bank_name: 银行名称 :type project_id: string :param project_id: 项目标识 :type anchor_id: string :param anchor_id: 新就业形态劳动者 ID,该字段已废弃 :type notes: string :param notes: 描述信息,该字段已废弃 :type sys_amount: string :param sys_amount: 系统支付金额,该字段已废弃 :type tax: string :param tax: 税费,该字段已废弃 :type sys_fee: string :param sys_fee: 系统支付费用,该字段已废弃 """ def __init__(self, order_id=None, pay=None, broker_id=None, dealer_id=None, real_name=None, card_no=None, id_card=None, phone_no=None, status=None, status_detail=None, status_message=None, status_detail_message=None, broker_amount=None, ref=None, broker_bank_bill=None, withdraw_platform=None, created_at=None, finished_time=None, broker_fee=None, broker_real_fee=None, broker_deduct_fee=None, pay_remark=None, user_fee=None, bank_name=None, project_id=None, anchor_id=None, notes=None, sys_amount=None, tax=None, sys_fee=None): super().__init__() self.order_id = order_id self.pay = pay self.broker_id = broker_id self.dealer_id = dealer_id self.real_name = real_name self.card_no = card_no self.id_card = id_card self.phone_no = phone_no self.status = status self.status_detail = status_detail self.status_message = status_message self.status_detail_message = status_detail_message self.broker_amount = broker_amount self.ref = ref self.broker_bank_bill = broker_bank_bill self.withdraw_platform = withdraw_platform self.created_at = created_at self.finished_time = finished_time self.broker_fee = broker_fee self.broker_real_fee = broker_real_fee self.broker_deduct_fee = broker_deduct_fee self.pay_remark = pay_remark self.user_fee = user_fee self.bank_name = bank_name self.project_id = project_id self.anchor_id = anchor_id self.notes = notes self.sys_amount = sys_amount self.tax = tax self.sys_fee = sys_fee def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay def get_broker_id(self): """ Get 综合服务主体 ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体 ID :type broker_id: string :param broker_id: 综合服务主体 ID """ self.broker_id = broker_id def get_dealer_id(self): """ Get 平台企业 ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业 ID :type dealer_id: string :param dealer_id: 平台企业 ID """ self.dealer_id = dealer_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_card_no(self): """ Get 收款人账号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 收款人账号 :type card_no: string :param card_no: 收款人账号 """ self.card_no = card_no def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_phone_no(self): """ Get 手机号 :return: string, phone_no """ return self.phone_no def set_phone_no(self, phone_no): """ Set 手机号 :type phone_no: string :param phone_no: 手机号 """ self.phone_no = phone_no def get_status(self): """ Get 订单状态码 :return: string, status """ return self.status def set_status(self, status): """ Set 订单状态码 :type status: string :param status: 订单状态码 """ self.status = status def get_status_detail(self): """ Get 订单详细状态码 :return: string, status_detail """ return self.status_detail def set_status_detail(self, status_detail): """ Set 订单详细状态码 :type status_detail: string :param status_detail: 订单详细状态码 """ self.status_detail = status_detail def get_status_message(self): """ Get 订单状态码描述 :return: string, status_message """ return self.status_message def set_status_message(self, status_message): """ Set 订单状态码描述 :type status_message: string :param status_message: 订单状态码描述 """ self.status_message = status_message def get_status_detail_message(self): """ Get 订单详细状态码描述 :return: string, status_detail_message """ return self.status_detail_message def set_status_detail_message(self, status_detail_message): """ Set 订单详细状态码描述 :type status_detail_message: string :param status_detail_message: 订单详细状态码描述 """ self.status_detail_message = status_detail_message def get_broker_amount(self): """ Get 综合服务主体支付金额 :return: string, broker_amount """ return self.broker_amount def set_broker_amount(self, broker_amount): """ Set 综合服务主体支付金额 :type broker_amount: string :param broker_amount: 综合服务主体支付金额 """ self.broker_amount = broker_amount def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref def get_broker_bank_bill(self): """ Get 支付交易流水号 :return: string, broker_bank_bill """ return self.broker_bank_bill def set_broker_bank_bill(self, broker_bank_bill): """ Set 支付交易流水号 :type broker_bank_bill: string :param broker_bank_bill: 支付交易流水号 """ self.broker_bank_bill = broker_bank_bill def get_withdraw_platform(self): """ Get 支付路径 :return: string, withdraw_platform """ return self.withdraw_platform def set_withdraw_platform(self, withdraw_platform): """ Set 支付路径 :type withdraw_platform: string :param withdraw_platform: 支付路径 """ self.withdraw_platform = withdraw_platform def get_created_at(self): """ Get 订单接收时间,精确到秒 :return: string, created_at """ return self.created_at def set_created_at(self, created_at): """ Set 订单接收时间,精确到秒 :type created_at: string :param created_at: 订单接收时间,精确到秒 """ self.created_at = created_at def get_finished_time(self): """ Get 订单完成时间,精确到秒 :return: string, finished_time """ return self.finished_time def set_finished_time(self, finished_time): """ Set 订单完成时间,精确到秒 :type finished_time: string :param finished_time: 订单完成时间,精确到秒 """ self.finished_time = finished_time def get_broker_fee(self): """ Get 综合服务主体加成服务费 :return: string, broker_fee """ return self.broker_fee def set_broker_fee(self, broker_fee): """ Set 综合服务主体加成服务费 :type broker_fee: string :param broker_fee: 综合服务主体加成服务费 """ self.broker_fee = broker_fee def get_broker_real_fee(self): """ Get 余额账户支出加成服务费 :return: string, broker_real_fee """ return self.broker_real_fee def set_broker_real_fee(self, broker_real_fee): """ Set 余额账户支出加成服务费 :type broker_real_fee: string :param broker_real_fee: 余额账户支出加成服务费 """ self.broker_real_fee = broker_real_fee def get_broker_deduct_fee(self): """ Get 抵扣账户支出加成服务费 :return: string, broker_deduct_fee """ return self.broker_deduct_fee def set_broker_deduct_fee(self, broker_deduct_fee): """ Set 抵扣账户支出加成服务费 :type broker_deduct_fee: string :param broker_deduct_fee: 抵扣账户支出加成服务费 """ self.broker_deduct_fee = broker_deduct_fee def get_pay_remark(self): """ Get 订单备注 :return: string, pay_remark """ return self.pay_remark def set_pay_remark(self, pay_remark): """ Set 订单备注 :type pay_remark: string :param pay_remark: 订单备注 """ self.pay_remark = pay_remark def get_user_fee(self): """ Get 用户加成服务费 :return: string, user_fee """ return self.user_fee def set_user_fee(self, user_fee): """ Set 用户加成服务费 :type user_fee: string :param user_fee: 用户加成服务费 """ self.user_fee = user_fee def get_bank_name(self): """ Get 银行名称 :return: string, bank_name """ return self.bank_name def set_bank_name(self, bank_name): """ Set 银行名称 :type bank_name: string :param bank_name: 银行名称 """ self.bank_name = bank_name def get_project_id(self): """ Get 项目标识 :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目标识 :type project_id: string :param project_id: 项目标识 """ self.project_id = project_id def get_anchor_id(self): """ Get 新就业形态劳动者 ID,该字段已废弃 :return: string, anchor_id """ return self.anchor_id def set_anchor_id(self, anchor_id): """ Set 新就业形态劳动者 ID,该字段已废弃 :type anchor_id: string :param anchor_id: 新就业形态劳动者 ID,该字段已废弃 """ self.anchor_id = anchor_id def get_notes(self): """ Get 描述信息,该字段已废弃 :return: string, notes """ return self.notes def set_notes(self, notes): """ Set 描述信息,该字段已废弃 :type notes: string :param notes: 描述信息,该字段已废弃 """ self.notes = notes def get_sys_amount(self): """ Get 系统支付金额,该字段已废弃 :return: string, sys_amount """ return self.sys_amount def set_sys_amount(self, sys_amount): """ Set 系统支付金额,该字段已废弃 :type sys_amount: string :param sys_amount: 系统支付金额,该字段已废弃 """ self.sys_amount = sys_amount def get_tax(self): """ Get 税费,该字段已废弃 :return: string, tax """ return self.tax def set_tax(self, tax): """ Set 税费,该字段已废弃 :type tax: string :param tax: 税费,该字段已废弃 """ self.tax = tax def get_sys_fee(self): """ Get 系统支付费用,该字段已废弃 :return: string, sys_fee """ return self.sys_fee def set_sys_fee(self, sys_fee): """ Set 系统支付费用,该字段已废弃 :type sys_fee: string :param sys_fee: 系统支付费用,该字段已废弃 """ self.sys_fee = sys_fee class CreateBatchOrderRequest(BaseRequest): """ :type batch_id: string :param batch_id: 平台企业批次号 :type dealer_id: string :param dealer_id: 平台企业ID :type broker_id: string :param broker_id: 综合服务主体ID :type channel: string :param channel: 支付路径 :type wx_app_id: string :param wx_app_id: 平台企业的微信AppID :type total_pay: string :param total_pay: 订单总金额 :type total_count: string :param total_count: 总笔数 :type order_list: list :param order_list: 订单列表 """ def __init__(self, batch_id=None, dealer_id=None, broker_id=None, channel=None, wx_app_id=None, total_pay=None, total_count=None, order_list=None): super().__init__() self.batch_id = batch_id self.dealer_id = dealer_id self.broker_id = broker_id self.channel = channel self.wx_app_id = wx_app_id self.total_pay = total_pay self.total_count = total_count self.order_list = order_list def get_batch_id(self): """ Get 平台企业批次号 :return: string, batch_id """ return self.batch_id def set_batch_id(self, batch_id): """ Set 平台企业批次号 :type batch_id: string :param batch_id: 平台企业批次号 """ self.batch_id = batch_id def get_dealer_id(self): """ Get 平台企业ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业ID :type dealer_id: string :param dealer_id: 平台企业ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体ID :type broker_id: string :param broker_id: 综合服务主体ID """ self.broker_id = broker_id def get_channel(self): """ Get 支付路径 :return: string, channel """ return self.channel def set_channel(self, channel): """ Set 支付路径 :type channel: string :param channel: 支付路径 """ self.channel = channel def get_wx_app_id(self): """ Get 平台企业的微信AppID :return: string, wx_app_id """ return self.wx_app_id def set_wx_app_id(self, wx_app_id): """ Set 平台企业的微信AppID :type wx_app_id: string :param wx_app_id: 平台企业的微信AppID """ self.wx_app_id = wx_app_id def get_total_pay(self): """ Get 订单总金额 :return: string, total_pay """ return self.total_pay def set_total_pay(self, total_pay): """ Set 订单总金额 :type total_pay: string :param total_pay: 订单总金额 """ self.total_pay = total_pay def get_total_count(self): """ Get 总笔数 :return: string, total_count """ return self.total_count def set_total_count(self, total_count): """ Set 总笔数 :type total_count: string :param total_count: 总笔数 """ self.total_count = total_count def get_order_list(self): """ Get 订单列表 :return: list, order_list """ return self.order_list def set_order_list(self, order_list): """ Set 订单列表 :type order_list: list :param order_list: 订单列表 """ self.order_list = order_list class BatchOrderInfo(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type real_name: string :param real_name: 姓名 :type id_card: string :param id_card: 身份证号码 :type card_no: string :param card_no: 收款账号 :type openid: string :param openid: 微信用户openid :type phone_no: string :param phone_no: 手机号 :type project_id: string :param project_id: 项目标识 :type pay: string :param pay: 订单金额 :type pay_remark: string :param pay_remark: 订单备注 :type notify_url: string :param notify_url: 回调地址 """ def __init__(self, order_id=None, real_name=None, id_card=None, card_no=None, openid=None, phone_no=None, project_id=None, pay=None, pay_remark=None, notify_url=None): super().__init__() self.order_id = order_id self.real_name = real_name self.id_card = id_card self.card_no = card_no self.openid = openid self.phone_no = phone_no self.project_id = project_id self.pay = pay self.pay_remark = pay_remark self.notify_url = notify_url def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_real_name(self): """ Get 姓名 :return: string, real_name """ return self.real_name def set_real_name(self, real_name): """ Set 姓名 :type real_name: string :param real_name: 姓名 """ self.real_name = real_name def get_id_card(self): """ Get 身份证号码 :return: string, id_card """ return self.id_card def set_id_card(self, id_card): """ Set 身份证号码 :type id_card: string :param id_card: 身份证号码 """ self.id_card = id_card def get_card_no(self): """ Get 收款账号 :return: string, card_no """ return self.card_no def set_card_no(self, card_no): """ Set 收款账号 :type card_no: string :param card_no: 收款账号 """ self.card_no = card_no def get_openid(self): """ Get 微信用户openid :return: string, openid """ return self.openid def set_openid(self, openid): """ Set 微信用户openid :type openid: string :param openid: 微信用户openid """ self.openid = openid def get_phone_no(self): """ Get 手机号 :return: string, phone_no """ return self.phone_no def set_phone_no(self, phone_no): """ Set 手机号 :type phone_no: string :param phone_no: 手机号 """ self.phone_no = phone_no def get_project_id(self): """ Get 项目标识 :return: string, project_id """ return self.project_id def set_project_id(self, project_id): """ Set 项目标识 :type project_id: string :param project_id: 项目标识 """ self.project_id = project_id def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay def get_pay_remark(self): """ Get 订单备注 :return: string, pay_remark """ return self.pay_remark def set_pay_remark(self, pay_remark): """ Set 订单备注 :type pay_remark: string :param pay_remark: 订单备注 """ self.pay_remark = pay_remark def get_notify_url(self): """ Get 回调地址 :return: string, notify_url """ return self.notify_url def set_notify_url(self, notify_url): """ Set 回调地址 :type notify_url: string :param notify_url: 回调地址 """ self.notify_url = notify_url class CreateBatchOrderResponse(BaseRequest): """ :type batch_id: string :param batch_id: 平台企业批次号 :type result_list: list :param result_list: 订单结果列表 """ def __init__(self, batch_id=None, result_list=None): super().__init__() self.batch_id = batch_id self.result_list = result_list def get_batch_id(self): """ Get 平台企业批次号 :return: string, batch_id """ return self.batch_id def set_batch_id(self, batch_id): """ Set 平台企业批次号 :type batch_id: string :param batch_id: 平台企业批次号 """ self.batch_id = batch_id def get_result_list(self): """ Get 订单结果列表 :return: list, result_list """ return self.result_list def set_result_list(self, result_list): """ Set 订单结果列表 :type result_list: list :param result_list: 订单结果列表 """ self.result_list = result_list class BatchOrderResult(BaseRequest): """ :type order_id: string :param order_id: 平台企业订单号 :type ref: string :param ref: 综合服务平台流水号 :type pay: string :param pay: 订单金额 """ def __init__(self, order_id=None, ref=None, pay=None): super().__init__() self.order_id = order_id self.ref = ref self.pay = pay def get_order_id(self): """ Get 平台企业订单号 :return: string, order_id """ return self.order_id def set_order_id(self, order_id): """ Set 平台企业订单号 :type order_id: string :param order_id: 平台企业订单号 """ self.order_id = order_id def get_ref(self): """ Get 综合服务平台流水号 :return: string, ref """ return self.ref def set_ref(self, ref): """ Set 综合服务平台流水号 :type ref: string :param ref: 综合服务平台流水号 """ self.ref = ref def get_pay(self): """ Get 订单金额 :return: string, pay """ return self.pay def set_pay(self, pay): """ Set 订单金额 :type pay: string :param pay: 订单金额 """ self.pay = pay class ConfirmBatchOrderRequest(BaseRequest): """ :type batch_id: string :param batch_id: 平台企业批次号 :type dealer_id: string :param dealer_id: 平台企业ID :type broker_id: string :param broker_id: 综合服务主体ID :type channel: string :param channel: 支付路径 """ def __init__(self, batch_id=None, dealer_id=None, broker_id=None, channel=None): super().__init__() self.batch_id = batch_id self.dealer_id = dealer_id self.broker_id = broker_id self.channel = channel def get_batch_id(self): """ Get 平台企业批次号 :return: string, batch_id """ return self.batch_id def set_batch_id(self, batch_id): """ Set 平台企业批次号 :type batch_id: string :param batch_id: 平台企业批次号 """ self.batch_id = batch_id def get_dealer_id(self): """ Get 平台企业ID :return: string, dealer_id """ return self.dealer_id def set_dealer_id(self, dealer_id): """ Set 平台企业ID :type dealer_id: string :param dealer_id: 平台企业ID """ self.dealer_id = dealer_id def get_broker_id(self): """ Get 综合服务主体ID :return: string, broker_id """ return self.broker_id def set_broker_id(self, broker_id): """ Set 综合服务主体ID :type broker_id: string :param broker_id: 综合服务主体ID """ self.broker_id = broker_id def get_channel(self): """ Get 支付路径 :return: string, channel """ return self.channel def set_channel(self, channel): """ Set 支付路径 :type channel: string :param channel: 支付路径 """ self.channel = channel class ConfirmBatchOrderResponse(BaseRequest): """ """ def __init__(self): super().__init__()
yzh-py
/yzh_py-1.0.0.tar.gz/yzh_py-1.0.0/yzh_py/client/api/model/payment.py
payment.py
# yzhanURLParser A python library which could parse URL to ip and country. ## Usage ### Install ```shell pip install yzhanurlparser ``` ### API #### Is IP ```python from yzhanurlparser import is_ip is_ip('123') # False is_ip('8.8.8.8') # True ``` #### Get Info By IP ```python from yzhanurlparser import get_info_by_ip get_info_by_ip('8.8.8.8') # {'ip': '8.8.8.8', 'country_short': 'US', 'country_long': 'United States of America'} ``` #### Get Country By IP ```python from yzhanurlparser import get_country_by_ip get_country_by_ip('8.8.8.8') # US get_country_by_ip('114.114.114.114') # CN ``` #### Get Info By URL ```python from yzhanurlparser import get_info_by_url get_info_by_url('https://www.163.com') # {'ip': '183.3.203.247', 'country_short': 'CN', 'country_long': 'China'} ``` #### Get Country By URL ```python from yzhanurlparser import get_country_by_url get_country_by_url('https://www.163.com') # CN ``` ## Development ### Install ```shell pip install -r requirements.txt ``` ### Unit Test ```shell cd yzhanurlparser python -m unittest discover -s test -p '*_test.py' ``` ### Build ```shell pip install --user --upgrade setuptools wheel twine # First Run python setup.py sdist bdist_wheel ``` ## Thanks [ip2location](https://lite.ip2location.com)
yzhanurlparser
/yzhanurlparser-0.1.0.tar.gz/yzhanurlparser-0.1.0/README.md
README.md
r""" The ``codes`` object defines a mapping from common names for HTTP statuses to their numerical codes, accessible either as attributes or as dictionary items. >>> requests.codes['temporary_redirect'] 307 >>> requests.codes.teapot 418 >>> requests.codes['\o/'] 200 Some codes have multiple names, and both upper- and lower-case versions of the names are allowed. For example, ``codes.ok``, ``codes.OK``, and ``codes.okay`` all correspond to the HTTP status code 200. """ from .structures import LookupDict _codes = { # Informational. 100: ('continue',), 101: ('switching_protocols',), 102: ('processing',), 103: ('checkpoint',), 122: ('uri_too_long', 'request_uri_too_long'), 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 201: ('created',), 202: ('accepted',), 203: ('non_authoritative_info', 'non_authoritative_information'), 204: ('no_content',), 205: ('reset_content', 'reset'), 206: ('partial_content', 'partial'), 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 208: ('already_reported',), 226: ('im_used',), # Redirection. 300: ('multiple_choices',), 301: ('moved_permanently', 'moved', '\\o-'), 302: ('found',), 303: ('see_other', 'other'), 304: ('not_modified',), 305: ('use_proxy',), 306: ('switch_proxy',), 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 308: ('permanent_redirect', 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 # Client Error. 400: ('bad_request', 'bad'), 401: ('unauthorized',), 402: ('payment_required', 'payment'), 403: ('forbidden',), 404: ('not_found', '-o-'), 405: ('method_not_allowed', 'not_allowed'), 406: ('not_acceptable',), 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 408: ('request_timeout', 'timeout'), 409: ('conflict',), 410: ('gone',), 411: ('length_required',), 412: ('precondition_failed', 'precondition'), 413: ('request_entity_too_large',), 414: ('request_uri_too_large',), 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 417: ('expectation_failed',), 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 421: ('misdirected_request',), 422: ('unprocessable_entity', 'unprocessable'), 423: ('locked',), 424: ('failed_dependency', 'dependency'), 425: ('unordered_collection', 'unordered'), 426: ('upgrade_required', 'upgrade'), 428: ('precondition_required', 'precondition'), 429: ('too_many_requests', 'too_many'), 431: ('header_fields_too_large', 'fields_too_large'), 444: ('no_response', 'none'), 449: ('retry_with', 'retry'), 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 499: ('client_closed_request',), # Server Error. 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 501: ('not_implemented',), 502: ('bad_gateway',), 503: ('service_unavailable', 'unavailable'), 504: ('gateway_timeout',), 505: ('http_version_not_supported', 'http_version'), 506: ('variant_also_negotiates',), 507: ('insufficient_storage',), 509: ('bandwidth_limit_exceeded', 'bandwidth'), 510: ('not_extended',), 511: ('network_authentication_required', 'network_auth', 'network_authentication'), } codes = LookupDict(name='status_codes') def _init(): for code, titles in _codes.items(): for title in titles: setattr(codes, title, code) if not title.startswith(('\\', '/')): setattr(codes, title.upper(), code) def doc(code): names = ', '.join('``%s``' % n for n in _codes[code]) return '* %d: %s' % (code, names) global __doc__ __doc__ = (__doc__ + '\n' + '\n'.join(doc(code) for code in sorted(_codes)) if __doc__ is not None else None) _init()
yzm
/yzm-1.0-py3-none-any.whl/request/status_codes.py
status_codes.py
import os.path import socket from urllib3.poolmanager import PoolManager, proxy_from_url from urllib3.response import HTTPResponse from urllib3.util import parse_url from urllib3.util import Timeout as TimeoutSauce from urllib3.util.retry import Retry from urllib3.exceptions import ClosedPoolError from urllib3.exceptions import ConnectTimeoutError from urllib3.exceptions import HTTPError as _HTTPError from urllib3.exceptions import MaxRetryError from urllib3.exceptions import NewConnectionError from urllib3.exceptions import ProxyError as _ProxyError from urllib3.exceptions import ProtocolError from urllib3.exceptions import ReadTimeoutError from urllib3.exceptions import SSLError as _SSLError from urllib3.exceptions import ResponseError from urllib3.exceptions import LocationValueError from .models import Response from .compat import urlparse, basestring from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths, get_encoding_from_headers, prepend_scheme_if_needed, get_auth_from_url, urldefragauth, select_proxy) from .structures import CaseInsensitiveDict from .cookies import extract_cookies_to_jar from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError, ProxyError, RetryError, InvalidSchema, InvalidProxyURL, InvalidURL) from .auth import _basic_auth_str try: from urllib3.contrib.socks import SOCKSProxyManager except ImportError: def SOCKSProxyManager(*args, **kwargs): raise InvalidSchema("Missing dependencies for SOCKS support.") DEFAULT_POOLBLOCK = False DEFAULT_POOLSIZE = 10 DEFAULT_RETRIES = 0 DEFAULT_POOL_TIMEOUT = None class BaseAdapter(object): """The Base Transport Adapter""" def __init__(self): super(BaseAdapter, self).__init__() def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ raise NotImplementedError def close(self): """Cleans up adapter specific items.""" raise NotImplementedError class HTTPAdapter(BaseAdapter): """The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the :class:`Session <Session>` class under the covers. :param pool_connections: The number of urllib3 connection pools to cache. :param pool_maxsize: The maximum number of connections to save in the pool. :param max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3's ``Retry`` class and pass that instead. :param pool_block: Whether the connection pool should block for connections. Usage:: >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) """ __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize', '_pool_block'] def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK): if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super(HTTPAdapter, self).__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager(self._pool_connections, self._pool_maxsize, block=self._pool_block) def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): """Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. """ # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs) def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs) return manager def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify. """ if url.lower().startswith('https') and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise IOError("Could not find a suitable TLS CA certificate bundle, " "invalid path: {}".format(cert_loc)) conn.cert_reqs = 'CERT_REQUIRED' if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise IOError("Could not find the TLS certificate file, " "invalid path: {}".format(conn.cert_file)) if conn.key_file and not os.path.exists(conn.key_file): raise IOError("Could not find the TLS key file, " "invalid path: {}".format(conn.key_file)) def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, 'status', None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL("Please check proxy URL. It is malformed" " and could be missing the host.") proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear() def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) chunked = not (request.body is None or 'Content-Length' in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError as e: # this may raise a string formatting error. err = ("Invalid timeout {}. Pass a (connect, read) " "timeout tuple, or a single float to set " "both timeouts to the same value".format(timeout)) raise ValueError(err) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout ) # Send the request. else: if hasattr(conn, 'proxy_pool'): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: low_conn.putrequest(request.method, url, skip_accept_encoding=True) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode('utf-8')) low_conn.send(b'\r\n') low_conn.send(i) low_conn.send(b'\r\n') low_conn.send(b'0\r\n\r\n') # Receive the response from the server try: # For Python 2.7, use buffering of HTTP responses r = low_conn.getresponse(buffering=True) except TypeError: # For compatibility with Python 3.3+ r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False ) except: # If we hit any problems here, clean up the connection. # Then, reraise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, socket.error) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) else: raise return self.build_response(request, resp)
yzm
/yzm-1.0-py3-none-any.whl/request/adapters.py
adapters.py
import os import sys import time from datetime import timedelta from .auth import _basic_auth_str from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse, Mapping from .cookies import ( cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies) from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT from .hooks import default_hooks, dispatch_hook from ._internal_utils import to_native_string from .utils import to_key_val_list, default_headers, DEFAULT_PORTS from .exceptions import ( TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError) from .structures import CaseInsensitiveDict from .adapters import HTTPAdapter from .utils import ( requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies, get_auth_from_url, rewind_body ) from .status_codes import codes # formerly defined here, reexposed here for backward compatibility from .models import REDIRECT_STATI # Preferred clock, based on which one is more accurate on a given system. if sys.platform == 'win32': try: # Python 3.4+ preferred_clock = time.perf_counter except AttributeError: # Earlier than Python 3. preferred_clock = time.clock else: preferred_clock = time.time def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class) class SessionRedirectMixin(object): def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs): """Receives a Response. Returns a generator of Responses or Requests.""" hist = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp) # Release the connection back into the pool. resp.close() # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url) # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) parsed = urlparse(url) if parsed.fragment == '' and previous_fragment: parsed = parsed._replace(fragment=previous_fragment) elif parsed.fragment: previous_fragment = parsed.fragment url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # https://github.com/requests/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): # https://github.com/requests/requests/issues/3490 purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding') for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers try: del headers['Cookie'] except KeyError: pass # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # A failed tell() sets `_body_position` to `object()`. This non-None # value ensures `rewindable` will be True, allowing us to raise an # UnrewindableBodyError, instead of hanging the connection. rewindable = ( prepared_request._body_position is not None and ('Content-Length' in headers or 'Transfer-Encoding' in headers) ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) # extract redirect url, if any, for the next loop url = self.get_redirect_target(resp) yield resp def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) return def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method class Session(SessionRedirectMixin): """A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:: >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') <Response [200]> Or as a context manager:: >>> with requests.Session() as s: >>> s.get('https://httpbin.org/get') <Response [200]> """ __attrs__ = [ 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify', 'cert', 'prefetch', 'adapters', 'stream', 'trust_env', 'max_redirects', ] def __init__(self): #: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. self.stream = False #: SSL Verification default. self.verify = True #: SSL client certificate default, if String, path to ssl client #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount('https://', HTTPAdapter()) self.mount('http://', HTTPAdapter()) def __enter__(self): return self def __exit__(self, *args): self.close() def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs) def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs) def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs) def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs) def put(self, url, data=None, **kwargs): r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PUT', url, data=data, **kwargs) def patch(self, url, data=None, **kwargs): r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PATCH', url, data=data, **kwargs) def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('DELETE', url, **kwargs) def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert} def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url) def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close() def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key) def __getstate__(self): state = {attr: getattr(self, attr, None) for attr in self.__attrs__} return state def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def session(): """ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session """ return Session()
yzm
/yzm-1.0-py3-none-any.whl/request/sessions.py
sessions.py
import os import re import time import hashlib import threading import warnings from base64 import b64encode from .compat import urlparse, str, basestring from .cookies import extract_cookies_to_jar from ._internal_utils import to_native_string from .utils import parse_dict_header CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded' CONTENT_TYPE_MULTI_PART = 'multipart/form-data' def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backwards compatibility # for things like ints. This will be removed in 3.0.0. if not isinstance(username, basestring): warnings.warn( "Non-string usernames will no longer be supported in Requests " "3.0.0. Please convert the object you've passed in ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(username), category=DeprecationWarning, ) username = str(username) if not isinstance(password, basestring): warnings.warn( "Non-string passwords will no longer be supported in Requests " "3.0.0. Please convert the object you've passed in ({!r}) to " "a string or bytes object in the near future to avoid " "problems.".format(password), category=DeprecationWarning, ) password = str(password) # -- End Removal -- if isinstance(username, str): username = username.encode('latin1') if isinstance(password, str): password = password.encode('latin1') authstr = 'Basic ' + to_native_string( b64encode(b':'.join((username, password))).strip() ) return authstr class AuthBase(object): """Base class that all auth implementations derive from""" def __call__(self, r): raise NotImplementedError('Auth hooks must be callable.') class HTTPBasicAuth(AuthBase): """Attaches HTTP Basic Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password def __eq__(self, other): return all([ self.username == getattr(other, 'username', None), self.password == getattr(other, 'password', None) ]) def __ne__(self, other): return not self == other def __call__(self, r): r.headers['Authorization'] = _basic_auth_str(self.username, self.password) return r class HTTPProxyAuth(HTTPBasicAuth): """Attaches HTTP Proxy Authentication to a given Request object.""" def __call__(self, r): r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password) return r class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password # Keep state in per-thread local storage self._thread_local = threading.local() def init_per_thread_state(self): # Ensure state is initialized just once per-thread if not hasattr(self._thread_local, 'init'): self._thread_local.init = True self._thread_local.last_nonce = '' self._thread_local.nonce_count = 0 self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None def build_digest_header(self, method, url): """ :rtype: str """ realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] qop = self._thread_local.chal.get('qop') algorithm = self._thread_local.chal.get('algorithm') opaque = self._thread_local.chal.get('opaque') hash_utf8 = None if algorithm is None: _algorithm = 'MD5' else: _algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level if _algorithm == 'MD5' or _algorithm == 'MD5-SESS': def md5_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.md5(x).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == 'SHA': def sha_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha1(x).hexdigest() hash_utf8 = sha_utf8 elif _algorithm == 'SHA-256': def sha256_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha256(x).hexdigest() hash_utf8 = sha256_utf8 elif _algorithm == 'SHA-512': def sha512_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha512(x).hexdigest() hash_utf8 = sha512_utf8 KD = lambda s, d: hash_utf8("%s:%s" % (s, d)) if hash_utf8 is None: return None # XXX not implemented yet entdig = None p_parsed = urlparse(url) #: path is request-uri defined in RFC 2616 which should not be empty path = p_parsed.path or "/" if p_parsed.query: path += '?' + p_parsed.query A1 = '%s:%s:%s' % (self.username, realm, self.password) A2 = '%s:%s' % (method, path) HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if nonce == self._thread_local.last_nonce: self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 ncvalue = '%08x' % self._thread_local.nonce_count s = str(self._thread_local.nonce_count).encode('utf-8') s += nonce.encode('utf-8') s += time.ctime().encode('utf-8') s += os.urandom(8) cnonce = (hashlib.sha1(s).hexdigest()[:16]) if _algorithm == 'MD5-SESS': HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce)) if not qop: respdig = KD(HA1, "%s:%s" % (nonce, HA2)) elif qop == 'auth' or 'auth' in qop.split(','): noncebit = "%s:%s:%s:%s:%s" % ( nonce, ncvalue, cnonce, 'auth', HA2 ) respdig = KD(HA1, noncebit) else: # XXX handle auth-int. return None self._thread_local.last_nonce = nonce # XXX should the partial digests be encoded too? base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \ 'response="%s"' % (self.username, realm, nonce, path, respdig) if opaque: base += ', opaque="%s"' % opaque if algorithm: base += ', algorithm="%s"' % algorithm if entdig: base += ', digest="%s"' % entdig if qop: base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce) return 'Digest %s' % (base) def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1 def handle_401(self, r, **kwargs): """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/requests/requests/issues/3772 if not 400 <= r.status_code < 500: self._thread_local.num_401_calls = 1 return r if self._thread_local.pos is not None: # Rewind the file position indicator of the body to where # it was to resend the request. r.request.body.seek(self._thread_local.pos) s_auth = r.headers.get('www-authenticate', '') if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2: self._thread_local.num_401_calls += 1 pat = re.compile(r'digest ', flags=re.IGNORECASE) self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1)) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.close() prep = r.request.copy() extract_cookies_to_jar(prep._cookies, r.request, r.raw) prep.prepare_cookies(prep._cookies) prep.headers['Authorization'] = self.build_digest_header( prep.method, prep.url) _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r def __call__(self, r): # Initialize per-thread state, if needed self.init_per_thread_state() # If we have a saved nonce, skip the 401 if self._thread_local.last_nonce: r.headers['Authorization'] = self.build_digest_header(r.method, r.url) try: self._thread_local.pos = r.body.tell() except AttributeError: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # file position of the previous body. Ensure it's set to # None. self._thread_local.pos = None r.register_hook('response', self.handle_401) r.register_hook('response', self.handle_redirect) self._thread_local.num_401_calls = 1 return r def __eq__(self, other): return all([ self.username == getattr(other, 'username', None), self.password == getattr(other, 'password', None) ]) def __ne__(self, other): return not self == other
yzm
/yzm-1.0-py3-none-any.whl/request/auth.py
auth.py
import codecs import contextlib import io import os import re import socket import struct import sys import tempfile import warnings import zipfile from .__version__ import __version__ from . import certs # to_native_string is unused here, but imported here for backwards compatibility from ._internal_utils import to_native_string from .compat import parse_http_list as _parse_list_header from .compat import ( quote, urlparse, bytes, str, OrderedDict, unquote, getproxies, proxy_bypass, urlunparse, basestring, integer_types, is_py3, proxy_bypass_environment, getproxies_environment, Mapping) from .cookies import cookiejar_from_dict from .structures import CaseInsensitiveDict from .exceptions import ( InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError) NETRC_FILES = ('.netrc', '_netrc') DEFAULT_CA_BUNDLE_PATH = certs.where() DEFAULT_PORTS = {'http': 80, 'https': 443} if sys.platform == 'win32': # provide a proxy_bypass version on Windows without DNS lookups def proxy_bypass_registry(host): try: if is_py3: import winreg else: import _winreg as winreg except ImportError: return False try: internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it proxyEnable = int(winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]) # ProxyOverride is almost always a string proxyOverride = winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0] except OSError: return False if not proxyEnable or not proxyOverride: return False # make a check value list from the registry entry: replace the # '<local>' string by the localhost entry and the corresponding # canonical entry. proxyOverride = proxyOverride.split(';') # now check if we match one of the registry values. for test in proxyOverride: if test == '<local>': if '.' not in host: return True test = test.replace(".", r"\.") # mask dots test = test.replace("*", r".*") # change glob sequence test = test.replace("?", r".") # change glob char if re.match(test, host, re.I): return True return False def proxy_bypass(host): # noqa """Return True, if the host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. """ if getproxies_environment(): return proxy_bypass_environment(host) else: return proxy_bypass_registry(host) def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, 'items'): d = d.items() return d def super_len(o): total_length = None current_position = 0 if hasattr(o, '__len__'): total_length = len(o) elif hasattr(o, 'len'): total_length = o.len elif hasattr(o, 'fileno'): try: fileno = o.fileno() except io.UnsupportedOperation: pass else: total_length = os.fstat(fileno).st_size # Having used fstat to determine the file length, we need to # confirm that this file was opened up in binary mode. if 'b' not in o.mode: warnings.warn(( "Requests has determined the content-length for this " "request using the binary size of the file: however, the " "file has been opened in text mode (i.e. without the 'b' " "flag in the mode). This may lead to an incorrect " "content-length. In Requests 3.0, support will be removed " "for files in text mode."), FileModeWarning ) if hasattr(o, 'tell'): try: current_position = o.tell() except (OSError, IOError): # This can happen in some weird situations, such as when the file # is actually a special file descriptor like stdin. In this # instance, we don't know what the length is, so set it to zero and # let requests chunk it instead. if total_length is not None: current_position = total_length else: if hasattr(o, 'seek') and total_length is None: # StringIO and BytesIO have seek but no useable fileno try: # seek to end of file o.seek(0, 2) total_length = o.tell() # seek back to current position to support # partially read file-like objects o.seek(current_position or 0) except (OSError, IOError): total_length = 0 if total_length is None: total_length = 0 return max(0, total_length - current_position) def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/requests/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # AppEngine hackiness. except (ImportError, AttributeError): pass def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name) def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) member = '/'.join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, *member.split('/')) if not os.path.exists(extracted_path): extracted_path = zip_file.extract(member, path=tmp) return extracted_path def from_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. Unless it can not be represented as such, return an OrderedDict, e.g., :: >>> from_key_val_list([('key', 'val')]) OrderedDict([('key', 'val')]) >>> from_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) :rtype: OrderedDict """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') return OrderedDict(value) def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples. :rtype: list """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value, Mapping): value = value.items() return list(value) # From mitsuhiko/werkzeug (used with permission). def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like :func:`parse_set_header` just that items may appear multiple times and case sensitivity is preserved. The return value is a standard :class:`list`: >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] To create a header from the :class:`list` again, use the :func:`dump_header` function. :param value: a string with a list header. :return: :class:`list` :rtype: list """ result = [] for item in _parse_list_header(value): if item[:1] == item[-1:] == '"': item = unquote_header_value(item[1:-1]) result.append(item) return result # From mitsuhiko/werkzeug (used with permission). def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result # From mitsuhiko/werkzeug (used with permission). def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. :rtype: str """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] # if this is a filename and the starting characters look like # a UNC path, then just return the value without quotes. Using the # replace sequence below on a UNC path has the effect of turning # the leading double slash into a single slash and then # _fix_ie_filename() doesn't work correctly. See #458. if not is_filename or value[:2] != '\\\\': return value.replace('\\\\', '\\').replace('\\"', '"') return value def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. :rtype: dict """ cookie_dict = {} for cookie in cj: cookie_dict[cookie.name] = cookie.value return cookie_dict def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. :rtype: CookieJar """ return cookiejar_from_dict(cookie_dict, cj) def get_encodings_from_content(content): """Returns encodings from given content string. :param content: bytestring to extract encodings from. """ warnings.warn(( 'In requests 3.0, get_encodings_from_content will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I) xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') return (charset_re.findall(content) + pragma_re.findall(content) + xml_re.findall(content)) def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1:].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. :rtype: str """ content_type = headers.get('content-type') if not content_type: return None content_type, params = _parse_content_type_header(content_type) if 'charset' in params: return params['charset'].strip("'\"") if 'text' in content_type: return 'ISO-8859-1' def stream_decode_response_unicode(iterator, r): """Stream decodes a iterator.""" if r.encoding is None: for item in iterator: yield item return decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') for chunk in iterator: rv = decoder.decode(chunk) if rv: yield rv rv = decoder.decode(b'', final=True) if rv: yield rv def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content # The unreserved URI characters (RFC 3986) UNRESERVED_SET = frozenset( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~") def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str """ parts = uri.split('%') for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise InvalidURL("Invalid percent-escape sequence: '%s'" % h) if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = '%' + parts[i] else: parts[i] = '%' + parts[i] return ''.join(parts) def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent) def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask) def dotted_netmask(mask): """Converts mask from /xx format to xxx.xxx.xxx.xxx Example: if mask is 24 function returns 255.255.255.0 :rtype: str """ bits = 0xffffffff ^ (1 << 32 - mask) - 1 return socket.inet_ntoa(struct.pack('>I', bits)) def is_ipv4_address(string_ip): """ :rtype: bool """ try: socket.inet_aton(string_ip) except socket.error: return False return True def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split('/')[0]) except socket.error: return False else: return False return True @contextlib.contextmanager def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting isn't in the no_proxy list. no_proxy_arg = no_proxy if no_proxy is None: no_proxy = get_proxy('no_proxy') parsed = urlparse(url) if parsed.hostname is None: # URLs don't always have hostnames, e.g. file:/// urls. return True if no_proxy: # We need to check whether we match here. We need to see if we match # the end of the hostname, both with and without the port. no_proxy = ( host for host in no_proxy.replace(' ', '').split(',') if host ) if is_ipv4_address(parsed.hostname): for proxy_ip in no_proxy: if is_valid_cidr(proxy_ip): if address_in_network(parsed.hostname, proxy_ip): return True elif parsed.hostname == proxy_ip: # If no_proxy ip was defined in plain IP notation instead of cidr notation & # matches the IP of the index return True else: host_with_port = parsed.hostname if parsed.port: host_with_port += ':{}'.format(parsed.port) for host in no_proxy: if parsed.hostname.endswith(host) or host_with_port.endswith(host): # The URL does match something in no_proxy, so we don't want # to apply the proxies on this URL. return True with set_environ('no_proxy', no_proxy_arg): # parsed.hostname can be `None` in cases such as a file URI. try: bypass = proxy_bypass(parsed.hostname) except (TypeError, socket.gaierror): bypass = False if bypass: return True return False def get_environ_proxies(url, no_proxy=None): """ Return a dict of environment proxies. :rtype: dict """ if should_bypass_proxies(url, no_proxy=no_proxy): return {} else: return getproxies() def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, urlparts.scheme, 'all://' + urlparts.hostname, 'all', ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy def default_user_agent(name="python-requests"): """ Return a string representing the default user agent. :rtype: str """ return '%s/%s' % (name, __version__) def default_headers(): """ :rtype: requests.structures.CaseInsensitiveDict """ return CaseInsensitiveDict({ 'User-Agent': default_user_agent(), 'Accept-Encoding': ', '.join(('gzip', 'deflate')), 'Accept': '*/*', 'Connection': 'keep-alive', }) def parse_header_links(value): """Return a list of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' value = value.strip(replace_chars) if not value: return links for val in re.split(', *<', value): try: url, params = val.split(';', 1) except ValueError: url, params = val, '' link = {'url': url.strip('<> \'"')} for param in params.split(';'): try: key, value = param.split('=') except ValueError: break link[key.strip(replace_chars)] = value.strip(replace_chars) links.append(link) return links # Null bytes; no need to recreate these on each call to guess_json_utf _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3 _null2 = _null * 2 _null3 = _null * 3 def guess_json_utf(data): """ :rtype: str """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): return 'utf-32' # BOM included if sample[:3] == codecs.BOM_UTF8: return 'utf-8-sig' # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return 'utf-16' # BOM included nullcount = sample.count(_null) if nullcount == 0: return 'utf-8' if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return 'utf-16-be' if sample[1::2] == _null2: # 2nd and 4th are null return 'utf-16-le' # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return 'utf-32-be' if sample[1:] == _null3: return 'utf-32-le' # Did not detect a valid UTF-32 ascii-range character return None def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and switch netloc # and path if urlparse decided there was no netloc. if not netloc: netloc, path = path, netloc return urlunparse((scheme, netloc, path, params, query, fragment)) def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth # Moved outside of function to avoid recompile every call _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$') _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$') def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value))) def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, '')) def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect.") else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
yzm
/yzm-1.0-py3-none-any.whl/request/utils.py
utils.py
import copy import time import calendar from ._internal_utils import to_native_string from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping try: import threading except ImportError: import dummy_threading as threading class MockRequest(object): """Wraps a `requests.Request` to mimic a `urllib2.Request`. The code in `cookielib.CookieJar` expects this interface in order to correctly manage cookie policies, i.e., determine whether a cookie can be set, given the domains of the request and the cookie. The original request object is read-only. The client is responsible for collecting the new headers via `get_new_headers()` and interpreting them appropriately. You probably want `get_cookie_header`, defined below. """ def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme def get_type(self): return self.type def get_host(self): return urlparse(self._r.url).netloc def get_origin_req_host(self): return self.get_host() def get_full_url(self): # Only return the response's URL if the user hadn't set the Host # header if not self._r.headers.get('Host'): return self._r.url # If they did set it, retrieve it and reconstruct the expected domain host = to_native_string(self._r.headers['Host'], encoding='utf-8') parsed = urlparse(self._r.url) # Reconstruct the URL as we expect it return urlunparse([ parsed.scheme, host, parsed.path, parsed.params, parsed.query, parsed.fragment ]) def is_unverifiable(self): return True def has_header(self, name): return name in self._r.headers or name in self._new_headers def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default)) def add_header(self, key, val): """cookielib has no legitimate use for this method; add it back if you find one.""" raise NotImplementedError("Cookie headers should be added with add_unredirected_header()") def add_unredirected_header(self, name, value): self._new_headers[name] = value def get_new_headers(self): return self._new_headers @property def unverifiable(self): return self.is_unverifiable() @property def origin_req_host(self): return self.get_origin_req_host() @property def host(self): return self.get_host() class MockResponse(object): """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. ...what? Basically, expose the parsed HTTP headers from the server response the way `cookielib` expects to see them. """ def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers def info(self): return self._headers def getheaders(self, name): self._headers.getheaders(name) def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req) def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie') def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name) class CookieConflictError(RuntimeError): """There are two cookies that meet the criteria specified in the cookie jar. Use .get and .set and include domain and path args in order to be more specific. """ class RequestsCookieJar(cookielib.CookieJar, MutableMapping): """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Requests does not use the dict interface internally; it's just for compatibility with external client code. All requests code should work out of the box with externally provided instances of ``CookieJar``, e.g. ``LWPCookieJar`` and ``FileCookieJar``. Unlike a regular CookieJar, this class is pickleable. .. warning:: dictionary operations that are normally O(1) may be O(n). """ def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ try: return self._find_no_duplicates(name, domain, path) except KeyError: return default def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. """ # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c def iterkeys(self): """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). """ for cookie in iter(self): yield cookie.name def keys(self): """Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). """ return list(self.iterkeys()) def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). """ for cookie in iter(self): yield cookie.value def values(self): """Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items(). """ return list(self.itervalues()) def iteritems(self): """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues(). """ for cookie in iter(self): yield cookie.name, cookie.value def items(self): """Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values(). """ return list(self.iteritems()) def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False # there is only one domain in jar def get_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. :rtype: dict """ dictionary = {} for cookie in iter(self): if ( (domain is None or cookie.domain == domain) and (path is None or cookie.path == path) ): dictionary[cookie.name] = cookie.value return dictionary def __contains__(self, name): try: return super(RequestsCookieJar, self).__contains__(name) except CookieConflictError: return True def __getitem__(self, name): """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1). """ return self._find_no_duplicates(name) def __setitem__(self, name, value): """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead. """ self.set(name, value) def __delitem__(self, name): """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``. """ remove_cookie_by_name(self, name) def set_cookie(self, cookie, *args, **kwargs): if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'): cookie.value = cookie.value.replace('\\"', '') return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs) def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super(RequestsCookieJar, self).update(other) def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def __getstate__(self): """Unlike a normal CookieJar, this class is pickleable.""" state = self.__dict__.copy() # remove the unpickleable RLock object state.pop('_cookies_lock') return state def __setstate__(self, state): """Unlike a normal CookieJar, this class is pickleable.""" self.__dict__.update(state) if '_cookies_lock' not in self.__dict__: self._cookies_lock = threading.RLock() def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj def get_policy(self): """Return the CookiePolicy instance used.""" return self._policy def _copy_cookie_jar(jar): if jar is None: return None if hasattr(jar, 'copy'): # We're dealing with an instance of RequestsCookieJar return jar.copy() # We're dealing with a generic CookieJar instance new_jar = copy.copy(jar) new_jar.clear() for cookie in jar: new_jar.set_cookie(copy.copy(cookie)) return new_jar def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result) def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueError: raise TypeError('max-age: %s must be integer' % morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm( time.strptime(morsel['expires'], time_template) ) return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, ) def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
yzm
/yzm-1.0-py3-none-any.whl/request/cookies.py
cookies.py
from . import sessions def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs) def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return request('get', url, params=params, **kwargs) def options(url, **kwargs): r"""Sends an OPTIONS request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return request('options', url, **kwargs) def head(url, **kwargs): r"""Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs) def post(url, data=None, json=None, **kwargs): r"""Sends a POST request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('post', url, data=data, json=json, **kwargs) def put(url, data=None, **kwargs): r"""Sends a PUT request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('put', url, data=data, **kwargs) def patch(url, data=None, **kwargs): r"""Sends a PATCH request. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('patch', url, data=data, **kwargs) def delete(url, **kwargs): r"""Sends a DELETE request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ return request('delete', url, **kwargs)
yzm
/yzm-1.0-py3-none-any.whl/request/api.py
api.py
from .compat import OrderedDict, Mapping, MutableMapping class CaseInsensitiveDict(MutableMapping): """A case-insensitive ``dict``-like object. Implements all methods and operations of ``MutableMapping`` as well as dict's ``copy``. Also provides ``lower_items``. All keys are expected to be strings. The structure remembers the case of the last key to be set, and ``iter(instance)``, ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` will contain case-sensitive keys. However, querying and contains testing is case insensitive:: cid = CaseInsensitiveDict() cid['Accept'] = 'application/json' cid['aCCEPT'] == 'application/json' # True list(cid) == ['Accept'] # True For example, ``headers['content-encoding']`` will return the value of a ``'Content-Encoding'`` response header, regardless of how the header name was originally stored. If the constructor, ``.update``, or equality comparison operations are given keys that have equal ``.lower()``s, the behavior is undefined. """ def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: data = {} self.update(data, **kwargs) def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value) def __getitem__(self, key): return self._store[key.lower()][1] def __delitem__(self, key): del self._store[key.lower()] def __iter__(self): return (casedkey for casedkey, mappedvalue in self._store.values()) def __len__(self): return len(self._store) def lower_items(self): """Like iteritems(), but with all lowercase keys.""" return ( (lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items() ) def __eq__(self, other): if isinstance(other, Mapping): other = CaseInsensitiveDict(other) else: return NotImplemented # Compare insensitively return dict(self.lower_items()) == dict(other.lower_items()) # Copy is required def copy(self): return CaseInsensitiveDict(self._store.values()) def __repr__(self): return str(dict(self.items())) class LookupDict(dict): """Dictionary lookup object.""" def __init__(self, name=None): self.name = name super(LookupDict, self).__init__() def __repr__(self): return '<lookup \'%s\'>' % (self.name) def __getitem__(self, key): # We allow fall-through here, so values default to None return self.__dict__.get(key, None) def get(self, key, default=None): return self.__dict__.get(key, default)
yzm
/yzm-1.0-py3-none-any.whl/request/structures.py
structures.py
# __ # /__) _ _ _ _ _/ _ # / ( (- (/ (/ (- _) / _) # / """ Requests HTTP Library ~~~~~~~~~~~~~~~~~~~~~ Requests is an HTTP library, written in Python, for human beings. Basic GET usage: >>> import requests >>> r = requests.get('https://www.python.org') >>> r.status_code 200 >>> 'Python is a programming language' in r.content True ... or POST: >>> payload = dict(key1='value1', key2='value2') >>> r = requests.post('https://httpbin.org/post', data=payload) >>> print(r.text) { ... "form": { "key2": "value2", "key1": "value1" }, ... } The other HTTP methods are supported - see `requests.api`. Full documentation is at <http://python-requests.org>. :copyright: (c) 2017 by Kenneth Reitz. :license: Apache 2.0, see LICENSE for more details. """ import urllib3 import chardet import warnings from .exceptions import RequestsDependencyWarning def check_compatibility(urllib3_version, chardet_version): urllib3_version = urllib3_version.split('.') assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git. # Sometimes, urllib3 only reports its version as 16.1. if len(urllib3_version) == 2: urllib3_version.append('0') # Check urllib3 for compatibility. major, minor, patch = urllib3_version # noqa: F811 major, minor, patch = int(major), int(minor), int(patch) # urllib3 >= 1.21.1, <= 1.25 assert major == 1 assert minor >= 21 assert minor <= 25 # Check chardet for compatibility. major, minor, patch = chardet_version.split('.')[:3] major, minor, patch = int(major), int(minor), int(patch) # chardet >= 3.0.2, < 3.1.0 assert major == 3 assert minor < 1 assert patch >= 2 def _check_cryptography(cryptography_version): # cryptography < 1.3.4 try: cryptography_version = list(map(int, cryptography_version.split('.'))) except ValueError: return if cryptography_version < [1, 3, 4]: warning = 'Old version of cryptography ({}) may cause slowdown.'.format(cryptography_version) warnings.warn(warning, RequestsDependencyWarning) # Check imported dependencies for compatibility. try: check_compatibility(urllib3.__version__, chardet.__version__) except (AssertionError, ValueError): warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported " "version!".format(urllib3.__version__, chardet.__version__), RequestsDependencyWarning) # Attempt to enable urllib3's SNI support, if possible try: from urllib3.contrib import pyopenssl pyopenssl.inject_into_urllib3() # Check cryptography version from cryptography import __version__ as cryptography_version _check_cryptography(cryptography_version) except ImportError: pass # urllib3's DependencyWarnings should be silenced. from urllib3.exceptions import DependencyWarning warnings.simplefilter('ignore', DependencyWarning) from .__version__ import __title__, __description__, __url__, __version__ from .__version__ import __build__, __author__, __author_email__, __license__ from .__version__ import __copyright__, __cake__ from . import utils from . import packages from .models import Request, Response, PreparedRequest from .api import request, get, head, post, patch, put, delete, options from .sessions import session, Session from .status_codes import codes from .exceptions import ( RequestException, Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError, FileModeWarning, ConnectTimeout, ReadTimeout ) # Set default logging handler to avoid "No handler found" warnings. import logging from logging import NullHandler logging.getLogger(__name__).addHandler(NullHandler()) # FileModeWarnings go off per the default. warnings.simplefilter('default', FileModeWarning, append=True)
yzm
/yzm-1.0-py3-none-any.whl/request/__init__.py
__init__.py
from __future__ import print_function import json import platform import sys import ssl import idna import urllib3 import chardet from . import __version__ as requests_version try: from urllib3.contrib import pyopenssl except ImportError: pyopenssl = None OpenSSL = None cryptography = None else: import OpenSSL import cryptography def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == 'CPython': implementation_version = platform.python_version() elif implementation == 'PyPy': implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': implementation_version = ''.join([ implementation_version, sys.pypy_version_info.releaselevel ]) elif implementation == 'Jython': implementation_version = platform.python_version() # Complete Guess elif implementation == 'IronPython': implementation_version = platform.python_version() # Complete Guess else: implementation_version = 'Unknown' return {'name': implementation, 'version': implementation_version} def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_info = {'version': urllib3.__version__} chardet_info = {'version': chardet.__version__} pyopenssl_info = { 'version': None, 'openssl_version': '', } if OpenSSL: pyopenssl_info = { 'version': OpenSSL.__version__, 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER, } cryptography_info = { 'version': getattr(cryptography, '__version__', ''), } idna_info = { 'version': getattr(idna, '__version__', ''), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = { 'version': '%x' % system_ssl if system_ssl is not None else '' } return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, } def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2)) if __name__ == '__main__': main()
yzm
/yzm-1.0-py3-none-any.whl/request/help.py
help.py
import datetime import sys # Import encoding now, to avoid implicit import later. # Implicit import within threads may cause LookupError when standard library is in a ZIP, # such as in Embedded Python. See https://github.com/requests/requests/issues/3578. import encodings.idna from urllib3.fields import RequestField from urllib3.filepost import encode_multipart_formdata from urllib3.util import parse_url from urllib3.exceptions import ( DecodeError, ReadTimeoutError, ProtocolError, LocationParseError) from io import UnsupportedOperation from .hooks import default_hooks from .structures import CaseInsensitiveDict from .auth import HTTPBasicAuth from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar from .exceptions import ( HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError, ConnectionError, StreamConsumedError) from ._internal_utils import to_native_string, unicode_is_ascii from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, check_header_validity) from .compat import ( Callable, Mapping, cookielib, urlunparse, urlsplit, urlencode, str, bytes, is_py2, chardet, builtin_str, basestring) from .compat import json as complexjson from .status_codes import codes #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( codes.moved, # 301 codes.found, # 302 codes.other, # 303 codes.temporary_redirect, # 307 codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 CONTENT_CHUNK_SIZE = 10 * 1024 ITER_CHUNK_SIZE = 512 class RequestEncodingMixin(object): @property def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url) @staticmethod def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, '__iter__'): vs = [vs] for v in vs: if v is not None: result.append( (k.encode('utf-8') if isinstance(k, str) else k, v.encode('utf-8') if isinstance(v, str) else v)) return urlencode(result, doseq=True) else: return data @staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v)) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif hasattr(fp, 'read'): fdata = fp.read() elif fp is None: continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type class RequestHooksMixin(object): def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False class Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self): return '<Request [%s]>' % (self.method) def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Generated from either a :class:`Request <Request>` object or manually. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> """ def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def __repr__(self): return '<PreparedRequest [%s]>' % (self.method) def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper()) @staticmethod def _get_idna_encoded_host(host): import idna try: host = idna.encode(host, uts46=True).decode('utf-8') except idna.IDNAError: raise UnicodeError return host def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/requests/requests/pull/2238 if isinstance(url, bytes): url = url.decode('utf8') else: url = unicode(url) if is_py2 else str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?") error = error.format(to_native_string(url, 'utf8')) raise MissingSchema(error) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL('URL has an invalid label.') elif host.startswith(u'*'): raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url def prepare_headers(self, headers): """Prepares the given HTTP headers.""" self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = 'application/json' body = complexjson.dumps(json) if not isinstance(body, bytes): body = body.encode('utf-8') is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, (basestring, list, tuple, Mapping)) ]) try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None if is_stream: body = data if getattr(body, 'tell', None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.') if length: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ('content-type' not in self.headers): self.headers['Content-Type'] = content_type self.body = body def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self.headers['Content-Length'] = builtin_str(length) elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None: # Set Content-Length to 0 for methods that can have a body # but don't provide one. (i.e. not GET or HEAD) self.headers['Content-Length'] = '0' def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body) def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event]) class Response(object): """The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """ __attrs__ = [ '_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request' ] def __init__(self): self._content = False self._content_consumed = False self._next = None #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. # This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None def __enter__(self): return self def __exit__(self, *args): self.close() def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, '_content_consumed', True) setattr(self, 'raw', None) def __repr__(self): return '<Response [%s]>' % (self.status_code) def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __nonzero__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128) @property def ok(self): """Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ try: self.raise_for_status() except HTTPError: return False return True @property def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return ('location' in self.headers and self.status_code in REDIRECT_STATI) @property def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) @property def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next @property def apparent_encoding(self): """The apparent encoding, provided by the chardet library.""" return chardet.detect(self.content)['encoding'] def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): # Special case for urllib3. if hasattr(self.raw, 'stream'): try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size)) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending @property def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed') if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b'' self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content @property def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace') return content def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs) @property def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') l[key] = link return l def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode('utf-8') except UnicodeDecodeError: reason = self.reason.decode('iso-8859-1') else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url) elif 500 <= self.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, 'release_conn', None) if release_conn is not None: release_conn()
yzm
/yzm-1.0-py3-none-any.whl/request/models.py
models.py
from urllib3.exceptions import HTTPError as BaseHTTPError class RequestException(IOError): """There was an ambiguous exception that occurred while handling your request. """ def __init__(self, *args, **kwargs): """Initialize RequestException with `request` and `response` objects.""" response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) if (response is not None and not self.request and hasattr(response, 'request')): self.request = self.response.request super(RequestException, self).__init__(*args, **kwargs) class HTTPError(RequestException): """An HTTP error occurred.""" class ConnectionError(RequestException): """A Connection error occurred.""" class ProxyError(ConnectionError): """A proxy error occurred.""" class SSLError(ConnectionError): """An SSL error occurred.""" class Timeout(RequestException): """The request timed out. Catching this error will catch both :exc:`~requests.exceptions.ConnectTimeout` and :exc:`~requests.exceptions.ReadTimeout` errors. """ class ConnectTimeout(ConnectionError, Timeout): """The request timed out while trying to connect to the remote server. Requests that produced this error are safe to retry. """ class ReadTimeout(Timeout): """The server did not send any data in the allotted amount of time.""" class URLRequired(RequestException): """A valid URL is required to make a request.""" class TooManyRedirects(RequestException): """Too many redirects.""" class MissingSchema(RequestException, ValueError): """The URL schema (e.g. http or https) is missing.""" class InvalidSchema(RequestException, ValueError): """See defaults.py for valid schemas.""" class InvalidURL(RequestException, ValueError): """The URL provided was somehow invalid.""" class InvalidHeader(RequestException, ValueError): """The header value provided was somehow invalid.""" class InvalidProxyURL(InvalidURL): """The proxy URL provided is invalid.""" class ChunkedEncodingError(RequestException): """The server declared chunked encoding but sent an invalid chunk.""" class ContentDecodingError(RequestException, BaseHTTPError): """Failed to decode response content""" class StreamConsumedError(RequestException, TypeError): """The content for this response was already consumed""" class RetryError(RequestException): """Custom retries logic failed""" class UnrewindableBodyError(RequestException): """Requests encountered an error when trying to rewind a body""" # Warnings class RequestsWarning(Warning): """Base warning for Requests.""" pass class FileModeWarning(RequestsWarning, DeprecationWarning): """A file was opened in text mode, but Requests determined its binary length.""" pass class RequestsDependencyWarning(RequestsWarning): """An imported dependency doesn't match the expected version range.""" pass
yzm
/yzm-1.0-py3-none-any.whl/request/exceptions.py
exceptions.py
import os from typing import Optional, Tuple, List, Union try: import yaml except: yaml = None from pydantic import BaseSettings, AnyUrl, DirectoryPath __all__ = [ "DefaultSetting", "settings", "get_configer", "get_ini_section_to_dict" ] def get_src_path() -> str: _path = os.getcwd() if 'src' in os.listdir(_path): _path = os.path.join(_path, 'src') return _path class DefaultSetting(BaseSettings): is_configured: bool = False command_path: DirectoryPath = None src_path: str = get_src_path() # src_path: str = "/Users/cml/cmlpy/xyz/yz-rpc" def __init_subclass__(cls, **kwargs): """""" super().__init_subclass__() reload_reload_settings(cls()) class Config: case_sensitive = False # 是否区分大小写 DEBUG: bool = False # SECRET_KEY: str = get_random_secret_key() # ============================================ PROTO_TEMPLATE_ROOT = "" PROTO_TEMPLATE_PATH = "protos" # >>>>>>>>>>>>>>>>>>>>>>>>>> GRPC >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # >>>>>>>>>>>>>>>>>>>>>>>>>> GRPC >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # 地址 GRPC_SERVER_HOST: str = "[::]" # 端口 GRPC_SERVER_PORT: int = 50051 # 最大线程数 GRPC_SERVER_MAX_WORKERS: int = None # 多进程支持,可以使用`multiprocessing.cpu_count()` GRPC_SERVER_PROCESS_COUNT: int = 1 # RPC Server的中间件导入列表:['dotted.path.to.callable_interceptor', ...] GRPC_SERVER_MIDDLEWARES: List = [] # 键值对的可选列表用于配置通道:[("grpc.max_receive_message_length", 1024*1024*100)] GRPC_SERVER_OPTIONS: List[Tuple[str, Union[str, int, bool]]] = [] # 服务器的最大并发rpcs数 GRPC_SERVER_MAXIMUM_CONCURRENT_RPCS: Optional[int] = None # 启动后是否阻塞 GRPC_SERVER_RUN_WITH_BLOCK: bool = True # 健康检测 GRPC_HEALTH_CHECKING_ENABLE = True GRPC_HEALTH_CHECKING_THREAD_POOL_NUM = 1 # Server Reflection GRPC_SEVER_REFLECTION_ENABLE = False # gRPC Service Third-Part Package Support GRPC_THIRD_PART_PACKAGES: List[str] = [] # <<<<<<<<<<<<<<<<<<<<<<<<<<< GRPC <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # <<<<<<<<<<<<<<<<<<<<<<<<<<< GRPC <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # logger # LOGGER_LEVEL = logging.INFO # LOGGER_FORMATTER: str = "[PID %(process)d] %(message)s" settings = DefaultSetting() def reload_reload_settings(instance): # settings = default_setting for k, v in settings.__fields__.items(): val = getattr(instance, k) setattr(settings, k, val) # 配置已经被加载过的标志 settings.is_configured = True def get_configer(ext: str = "ini", import_path=os.curdir): profile = os.environ.get('ENV_PROFILE', 'dev') if profile == 'production': configname = 'config_production' elif profile == 'testing': configname = 'config_testing' else: configname = 'config_dev' print(f"===>当前环境为:{profile}!导入的配置文件为:{configname}.{ext}") base_path = os.path.abspath(import_path) _path = os.path.join(base_path, "conf", f"{configname}.{ext}") if ext in ["ini", "cfg"]: import configparser conf = configparser.ConfigParser() conf.read(_path) elif ext in ["yaml", "yml"]: if yaml is not None: raise ImportError("Need to install PyYaml") conf = yaml.safe_load(open(_path)) else: raise AttributeError(f"暂不支持该文件格式: {ext}") return conf def get_ini_section_to_dict( section: str, exclude: set = None, conf_parser=None ) -> dict: """ 获取ini配置文件某个节选的全部数据,转换成字典 :param section: 节选名称 :param exclude: 排除的字段 :param conf_parser: 配置解析器 :return: """ conf_dict = dict() for k in conf_parser.options(section): if exclude and k in exclude: break conf_dict[k] = conf.get(section, k) return conf_dict if __name__ == '__main__': conf = get_configer("ini")
yzrpc
/config/default_settings.py
default_settings.py
from django.conf.urls import url from django.db.models.fields.files import ImageFieldFile, ImageField, FileField, FieldFile from django.http import JsonResponse, HttpResponse from tastypie.bundle import Bundle from tastypie.exceptions import ImmediateHttpResponse from tastypie.resources import ModelResource from tastypie.utils import trailing_slash import functools from django.utils import timezone import time from yzs.django_extend.image_upload import get_absolute_url from yzs.tastypie_extend.response_code import resource_code_manage from datetime import datetime, date from django.conf import settings def querydict_to_dict(querydict): data_dict = {} for key in querydict: value = querydict.getlist(key) data_dict[key] = value[0] if len(value) == 1 else value return data_dict class CodeException(Exception): def __init__(self, code=0, data=None, *args, **kwargs): self.code = code self.data = data def api_view(url_path: str = None, url_name: str = None, auth: bool = False, allowed_methods: list = None, single_api: bool = False): """ 自动包装一个url映射 url_path: api视图的backend的最后一个路径的名称, 默认为视图方法名称(替换下划线为横线) url_name: api视图对应的url定义中的name, 默认为资源类名称+视图方法名称 auth: 指定是否需要用户验证 allowed_methods: 用来制定自定义视图允许的请求方法列表 single_api: 该方法是否对单个对象使用 """ def view_decorator(view_func): view_func._is_api = True view_func._url_path = url_path view_func._url_name = url_name view_func._single_api = single_api default_allowed_methods = ['get', 'options', 'head'] final_methods = allowed_methods or default_allowed_methods @functools.wraps(view_func) def view_wrapper(self, request, *args, **kwargs): try: request._load_post_and_files() if auth: self.is_authenticated(request) self.method_check(request, final_methods) return view_func(self, request, *args, **kwargs) except CodeException as e: return self.create_response(request, data=e.data, code=e.code) except Exception as e: if settings.DEBUG: try: print(e) print('post_data:', self._deserialize(request)) print('GET:', request.GET) except: pass raise e return view_wrapper return view_decorator def dt_to_ts(v): if v: if hasattr(v, "tzinfo") and v.tzinfo is not None and v.tzinfo.utcoffset(v) is not None: v = timezone.localtime(v) return int(time.mktime(v.timetuple())) else: # 如果没有时间返回20180101 00:00 return 1514736000 class BaseModelResource(ModelResource): CONTENT_TYPE_FIELD = 'CONTENT_TYPE' FORM_URLENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded' MULTIPART_CONTENT_TYPE = 'multipart/form-data' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._handel_api_view() def dehydrate(self, bundle): for k, v in bundle.data.items(): if type(v) == datetime or type(v) == date: if not v: bundle.data[k] = dt_to_ts(datetime(2017, 1, 1)) else: bundle.data[k] = dt_to_ts(v) if hasattr(bundle.obj, k) and type(getattr(bundle.obj, k)) in [ImageFieldFile, ImageField, FileField, FieldFile]: if not v: bundle.data[k] = "" else: bundle.data[k] = get_absolute_url(v) return bundle def _handel_api_view(self): """ 处理api_view装饰器 """ self.prepend_url_list = [] for attr_name in (attr_name for attr_name in dir(self) if attr_name not in dir(BaseModelResource)): attr_value = getattr(self, attr_name) if not callable(attr_value) or not hasattr(attr_value, '_is_api'): continue api_url_path = getattr(attr_value, '_url_path', None) or attr_name api_url_name = getattr(attr_value, '_url_name', None) or self._meta.resource_name + '_' + attr_name if hasattr(attr_value, '_single_api') and getattr(attr_value, '_single_api') is True: self.prepend_url_list.append( url(r'^(?P<resource_name>{})/(?P<pk>\w[\w/-]*)/{}{}'.format(self._meta.resource_name, api_url_path, trailing_slash()), self.wrap_view(attr_name), name=api_url_name) ) else: self.prepend_url_list.append( url(r'^(?P<resource_name>{})/{}{}'.format(self._meta.resource_name, api_url_path, trailing_slash()), self.wrap_view(attr_name), name=api_url_name) ) def prepend_urls(self): """ 自动生成prepend_urls :return: """ return self.prepend_url_list or super().prepend_urls() def create_response(self, request, data=None, response_class=HttpResponse, **response_kwargs): if data is None: data = {} if isinstance(data, dict): self.handel_code(data, response_kwargs) if isinstance(data, Bundle): self.handel_code(data.data, response_kwargs) return super().create_response(request, data, **response_kwargs) def handel_code(self, data, response_kwargs): code = 0 if 'code' in response_kwargs: code = response_kwargs['code'] del response_kwargs['code'] if '_code' not in data: data['_code'] = code if '_message' not in data: data['_message'] = resource_code_manage.get_message(code) def _deserialize(self, request, data=None, content_type=None): content_type = content_type or request.META.get(self.CONTENT_TYPE_FIELD, 'application/json') if self.FORM_URLENCODED_CONTENT_TYPE in content_type: return querydict_to_dict(request.POST) if self.MULTIPART_CONTENT_TYPE in content_type: data = querydict_to_dict(request.POST) data.update(request.FILES) return data return super().deserialize(request, data or request.body.decode(), content_type)
yzs-work
/yzs-work-0.1.34.tar.gz/yzs-work-0.1.34/yzs/tastypie_extend/base_resource.py
base_resource.py
import uuid import os, time from django.conf import settings import logging from django.core.files.storage import FileSystemStorage logger = logging.getLogger('system') def upload_aliyun_oss(folder): import oss2 AccessKeyId = settings.ALIYUN_OSS["AccessKeyId"] AccessKeySecret = settings.ALIYUN_OSS["AccessKeySecret"] Endpoint = settings.ALIYUN_OSS["Endpoint"] BucketName = settings.ALIYUN_OSS["BucketName"] if settings.UPLOAD_ALIYUN_OSS: auth = oss2.Auth(AccessKeyId, AccessKeySecret) bucket = oss2.Bucket(auth, Endpoint, BucketName) p = os.path.join(settings.MEDIA_ROOT, folder) aliyun_path = "{}/{}".format(settings.MEDIA_URL.replace("/", ""), folder).replace("\\", "/") try: with open(p, 'rb') as fileobj: result = bucket.put_object(aliyun_path, fileobj) if result.status == 200: return 'success', p else: return 'fail', '' except Exception as e: logger.error(e) return 'fail', '' class ImageStorage(FileSystemStorage): from django.conf import settings def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL): # 初始化 super(ImageStorage, self).__init__(location, base_url) # 重写 _save方法 def _save(self, name, content): import os, time, random # 文件扩展名 ext = os.path.splitext(name)[1] # 文件目录 d = os.path.dirname(name) # 定义文件名 fn = str(uuid.uuid4()) # 重写合成文件名 name = os.path.join(d, fn + ext) # 调用父类方法 fn = super(ImageStorage, self)._save(name, content) if hasattr(settings, 'ALIYUN_OSS'): upload_aliyun_oss(fn) return fn def get_absolute_url(url): if not url: return url if url.startswith("http://") or url.startswith("https://"): return url if hasattr(settings,'UPLOAD_ALIYUN_OSS') and settings.UPLOAD_ALIYUN_OSS: return "{}{}".format(settings.IMGHOST, url) else: return "{}{}".format(settings.HOST, url)
yzs-work
/yzs-work-0.1.34.tar.gz/yzs-work-0.1.34/yzs/django_extend/image_upload.py
image_upload.py
# yzw scrapy爬取研招网研究生考试专业信息 含有考试范围、专业等,可输出到Excel或MySQL。 **[发布页](https://github.com/Hthing/yzw/releases)有爬取好的数据,可用excel或mysql直接查看** 数据大概这个样子,获得数据之后我们就能方便地进行筛选了。 ![图1](https://github.com/Hthing/yzw/blob/master/img/excel.png) ## 安装: 可直接使用pip自主安装 ``` pip install --upgrade yzwspider python -m yzwspider ``` 或者clone到本地使用 ``` git clone https://github.com/Hthing/yzw.git cd yzw pip install -r requirements.txt python -m yzwspider ``` ## 运行环境: python3.7以上 ## 使用方法 **需提前建立数据库** 省市代码,学科门类,一级学科代码(学科类别) 可在研招网查得。 例,计算机科学与技术:0812 https://yz.chsi.com.cn/zsml/queryAction.do ``` python -m yzwspider [-h] [-ssdm] [-mldm] [-yjxk] [--all] [--log] 输出目标 [其他参数] ``` yzwspider参数: (括号内为默认值) > **-ssdm**: 省市代码(11) 支持中文名 即北京、上海等, 0表示全国 > > **-mldm:** 门类代码(01) 支持中文名: 理学、工学等 > > **-yjxk:** 一级学科代码(0101) > > **--all:**爬取全部专业信息并只可输出到mysql > > **--log:** 保存日志文件至当前目录 > > 命令 "excel" 参数: > > > **-o:** .xls文件输出路径, 默认为当前目录 > > 命令 "mysql" 参数: > > > **-host:**主机地址(localhost) > > > > **-port:**端口号(3306) > > > > **-u:** 用户名(root) > > > > **-p:** 密码('') > > > > **-db:** 数据库名(yanzhao) > > > > **-table:**数据表名(major) 例如,我们想获取北京市(11)的计算机科学与技术专业(0812)并输出为excel文件 ``` python -m yzwspider -ssdm 11 -yjxk 0812 excel ``` 上条语句可将"-ssdm 11"替换为"-ssdm 北京"同样生效。 最终将会得到如下的信息 ``` 2019-12-04 15:13:57 [scrapy.core.engine] INFO: Closing spider (finished) 2019-12-04 15:13:57 [YzwPipeline] INFO: excel文件已存储于 /home/研招网专业信息.xls 2019-12-04 15:13:57 [yzwspider.yzw.collector] INFO: 数据抓取完成, 共计 691 条数据, 程序开始时间 2019-12-04 15:13:44 , 结束时间 2019-12-04 15:13:57, 耗时 0 分钟 2019-12-04 15:13:57 [scrapy.core.engine] INFO: Spider closed (finished) ``` 若输出至mysql(默认参数可以不填) ``` python -m yzwspider -ssdm 11 -yjxk 0812 mysql -u root -p **** -host ******* -table test ``` 爬取全国某专业 ``` python -m yzwspider -ssdm 0 -yjxk 0812 mysql -u *** -p *** ``` 输出信息类似于excel. 如果想保存日志则加上--log即可 ## 爬取页面 ​ 爬取的页面如下,另外每行数据的id由页面的id以及考试范围顺序组成 ​ ![图2](https://github.com/Hthing/yzw/blob/master/img/page.png)
yzwspider
/yzwspider-0.1.5.2.tar.gz/yzwspider-0.1.5.2/README.md
README.md
import os, sys DEFAULT_VERSION = "0.6c7" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', } def _validate_md5(egg_name, data): if egg_name in md5_data: from md5 import md5 digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data # The following code to parse versions is copied from pkg_resources.py so that # we can parse versions without importing that module. import re component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE) replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get def _parse_version_parts(s): for part in component_re.split(s): part = replace(part,part) if not part or part=='.': continue if part[:1] in '0123456789': yield part.zfill(8) # pad for numeric comparison else: yield '*'+part yield '*final' # ensure that alpha/beta/candidate are before final def parse_version(s): parts = [] for part in _parse_version_parts(s.lower()): if part.startswith('*'): if part<'*final': # remove '-' before a prerelease tag while parts and parts[-1]=='*final-': parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1]=='00000000': parts.pop() parts.append(part) return tuple(parts) def setuptools_is_new_enough(required_version): """Return True if setuptools is already installed and has a version number >= required_version.""" if 'pkg_resources' in sys.modules: import pkg_resources try: pkg_resources.require('setuptools >= %s' % (required_version,)) except pkg_resources.VersionConflict: # An insufficiently new version is installed. return False else: return True else: try: import pkg_resources except ImportError: # Okay it is not installed. return False else: try: pkg_resources.require('setuptools >= %s' % (required_version,)) except pkg_resources.VersionConflict: # An insufficiently new version is installed. pkg_resources.__dict__.clear() # "If you want to be absolutely sure... before deleting it." --said PJE on IRC del sys.modules['pkg_resources'] return False else: pkg_resources.__dict__.clear() # "If you want to be absolutely sure... before deleting it." --said PJE on IRC del sys.modules['pkg_resources'] return True def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, min_version=None, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ if min_version is None: min_version = version if not setuptools_is_new_enough(min_version): egg = download_setuptools(version, min_version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg def download_setuptools( version=DEFAULT_VERSION, min_version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version >= %s to run (even to display help). I will attempt to download setuptools for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", min_version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" if setuptools_is_new_enough(version): if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' else: egg = None try: egg = download_setuptools(version, min_version=version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) def update_md5(filenames): """Update our built-in md5 registry""" import re from md5 import md5 for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if '--md5update' in sys.argv: sys.argv.remove('--md5update') update_md5(sys.argv[1:]) else: main(sys.argv[1:])
z-base-36
/z-base-36-1.0.1.tar.gz/z-base-36-1.0.1/ez_setup.py
ez_setup.py
# Copyright (c) 2002-2008 Zooko "Zooko" Wilcox-O'Hearn # mailto:[email protected] # Permission is hereby granted to any person obtaining a copy of this work to # deal in this work without restriction (including the rights to use, modify, # distribute, sublicense, and/or sell copies). # from the Python Standard Library import string from pyutil.assertutil import _assert, precondition, postcondition from pyutil.mathutil import div_ceil, log_ceil, log_floor chars = "0123456789abcdefghijklmnopqrstuvwxyz" vals = ''.join([chr(i) for i in range(36)]) c2vtranstable = string.maketrans(chars, vals) v2ctranstable = string.maketrans(vals, chars) identitytranstable = string.maketrans(chars, chars) def b2a(os): """ @param os the data to be encoded (a string) @return the contents of os in base-36 encoded form """ cs = b2a_l(os, len(os)*8) assert num_octets_that_encode_to_this_many_chars(len(cs)) == len(os), "%s != %s, numchars: %s" % (num_octets_that_encode_to_this_many_chars(len(cs)), len(os), len(cs)) return cs def b2a_l(os, lengthinbits): """ @param os the data to be encoded (a string) @param lengthinbits the number of bits of data in os to be encoded b2a_l() will generate a base-36 encoded string big enough to encode lengthinbits bits. So for example if os is 3 bytes long and lengthinbits is 17, then b2a_l() will generate a 4-character- long base-36 encoded string (since 4 chars is sufficient to encode all 2^17 values). If os is 3 bytes long and lengthinbits is 21 (or None), then b2a_l() will generate a 5-character string (since 5 chars are required to hold 2^21 values or 2^24 values). Note that if os is 3 bytes long and lengthinbits is 17, the least significant 7 bits of os are ignored. Warning: if you generate a base-36 encoded string with b2a_l(), and then someone else tries to decode it by calling a2b() instead of a2b_l(), then they will (potentially) get a different string than the one you encoded! So use b2a_l() only when you are sure that the encoding and decoding sides know exactly which lengthinbits to use. If you do not have a way for the encoder and the decoder to agree upon the lengthinbits, then it is best to use b2a() and a2b(). The only drawback to using b2a() over b2a_l() is that when you have a number of bits to encode that is not a multiple of 8, b2a() can sometimes generate a base-36 encoded string that is one or two characters longer than necessary. @return the contents of os in base-36 encoded form """ os = [ord(o) for o in reversed(os)] # treat os as big-endian -- and we want to process the least-significant o first value = 0 numvalues = 1 # the number of possible values that value could be for o in os: o *= numvalues value += o numvalues *= 256 chars = [] while numvalues > 0: chars.append(value % 36) value //= 36 numvalues //= 36 return string.translate(''.join([chr(c) for c in reversed(chars)]), v2ctranstable) # make it big-endian def num_octets_that_encode_to_this_many_chars(numcs): return log_floor(36**numcs, 256) def num_chars_that_this_many_octets_encode_to(numos): return log_ceil(256**numos, 36) def a2b(cs): """ @param cs the base-36 encoded data (a string) """ return a2b_l(cs, num_octets_that_encode_to_this_many_chars(len(cs))*8) def a2b_l(cs, lengthinbits): """ @param lengthinbits the number of bits of data in encoded into cs a2b_l() will return a result just big enough to hold lengthinbits bits. So for example if cs is 2 characters long (encoding between 5 and 12 bits worth of data) and lengthinbits is 8, then a2b_l() will return a string of length 1 (since 1 byte is sufficient to store 8 bits), but if lengthinbits is 9, then a2b_l() will return a string of length 2. Please see the warning in the docstring of b2a_l() regarding the use of b2a() versus b2a_l(). @return the data encoded in cs """ cs = [ord(c) for c in reversed(string.translate(cs, c2vtranstable))] # treat cs as big-endian -- and we want to process the least-significant c first value = 0 numvalues = 1 # the number of possible values that value could be for c in cs: c *= numvalues value += c numvalues *= 36 numvalues = 2**lengthinbits bytes = [] while numvalues > 1: bytes.append(value % 256) value //= 256 numvalues //= 256 return ''.join([chr(b) for b in reversed(bytes)]) # make it big-endian
z-base-36
/z-base-36-1.0.1.tar.gz/z-base-36-1.0.1/base36/base36.py
base36.py
import os, sys DEFAULT_VERSION = "0.6c7" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', } def _validate_md5(egg_name, data): if egg_name in md5_data: from md5 import md5 digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data # The following code to parse versions is copied from pkg_resources.py so that # we can parse versions without importing that module. import re component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE) replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get def _parse_version_parts(s): for part in component_re.split(s): part = replace(part,part) if not part or part=='.': continue if part[:1] in '0123456789': yield part.zfill(8) # pad for numeric comparison else: yield '*'+part yield '*final' # ensure that alpha/beta/candidate are before final def parse_version(s): parts = [] for part in _parse_version_parts(s.lower()): if part.startswith('*'): if part<'*final': # remove '-' before a prerelease tag while parts and parts[-1]=='*final-': parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1]=='00000000': parts.pop() parts.append(part) return tuple(parts) def setuptools_is_new_enough(required_version): """Return True if setuptools is already installed and has a version number >= required_version.""" if 'pkg_resources' in sys.modules: import pkg_resources try: pkg_resources.require('setuptools >= %s' % (required_version,)) except pkg_resources.VersionConflict: # An insufficiently new version is installed. return False else: return True else: try: import pkg_resources except ImportError: # Okay it is not installed. return False else: try: pkg_resources.require('setuptools >= %s' % (required_version,)) except pkg_resources.VersionConflict: # An insufficiently new version is installed. pkg_resources.__dict__.clear() # "If you want to be absolutely sure... before deleting it." --said PJE on IRC del sys.modules['pkg_resources'] return False else: pkg_resources.__dict__.clear() # "If you want to be absolutely sure... before deleting it." --said PJE on IRC del sys.modules['pkg_resources'] return True def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, min_version=None, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ if min_version is None: min_version = version if not setuptools_is_new_enough(min_version): egg = download_setuptools(version, min_version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg def download_setuptools( version=DEFAULT_VERSION, min_version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version >= %s to run (even to display help). I will attempt to download setuptools for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", min_version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" if setuptools_is_new_enough(version): if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' else: egg = None try: egg = download_setuptools(version, min_version=version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) def update_md5(filenames): """Update our built-in md5 registry""" import re from md5 import md5 for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if '--md5update' in sys.argv: sys.argv.remove('--md5update') update_md5(sys.argv[1:]) else: main(sys.argv[1:])
z-base-62
/z-base-62-1.0.1.tar.gz/z-base-62-1.0.1/ez_setup.py
ez_setup.py
# Copyright (c) 2002-2008 Bryce "Zooko" Wilcox-O'Hearn # mailto:[email protected] # Permission is hereby granted to any person obtaining a copy of this work to # deal in this work without restriction (including the rights to use, modify, # distribute, sublicense, and/or sell copies). # from the Python Standard Library import string from pyutil.assertutil import _assert, precondition, postcondition from pyutil.mathutil import div_ceil, log_ceil, log_floor chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" vals = ''.join([chr(i) for i in range(62)]) c2vtranstable = string.maketrans(chars, vals) v2ctranstable = string.maketrans(vals, chars) identitytranstable = string.maketrans(chars, chars) def b2a(os): """ @param os the data to be encoded (a string) @return the contents of os in base-62 encoded form """ cs = b2a_l(os, len(os)*8) assert num_octets_that_encode_to_this_many_chars(len(cs)) == len(os), "%s != %s, numchars: %s" % (num_octets_that_encode_to_this_many_chars(len(cs)), len(os), len(cs)) return cs def b2a_l(os, lengthinbits): """ @param os the data to be encoded (a string) @param lengthinbits the number of bits of data in os to be encoded b2a_l() will generate a base-62 encoded string big enough to encode lengthinbits bits. So for example if os is 3 bytes long and lengthinbits is 17, then b2a_l() will generate a 3-character- long base-62 encoded string (since 3 chars is sufficient to encode more than 2^17 values). If os is 3 bytes long and lengthinbits is 18 (or None), then b2a_l() will generate a 4-character string (since 4 chars are required to hold 2^18 values). Note that if os is 3 bytes long and lengthinbits is 17, the least significant 7 bits of os are ignored. Warning: if you generate a base-62 encoded string with b2a_l(), and then someone else tries to decode it by calling a2b() instead of a2b_l(), then they will (potentially) get a different string than the one you encoded! So use b2a_l() only when you are sure that the encoding and decoding sides know exactly which lengthinbits to use. If you do not have a way for the encoder and the decoder to agree upon the lengthinbits, then it is best to use b2a() and a2b(). The only drawback to using b2a() over b2a_l() is that when you have a number of bits to encode that is not a multiple of 8, b2a() can sometimes generate a base-62 encoded string that is one or two characters longer than necessary. @return the contents of os in base-62 encoded form """ os = [ord(o) for o in reversed(os)] # treat os as big-endian -- and we want to process the least-significant o first value = 0 numvalues = 1 # the number of possible values that value could be for o in os: o *= numvalues value += o numvalues *= 256 chars = [] while numvalues > 0: chars.append(value % 62) value //= 62 numvalues //= 62 return string.translate(''.join([chr(c) for c in reversed(chars)]), v2ctranstable) # make it big-endian def num_octets_that_encode_to_this_many_chars(numcs): return log_floor(62**numcs, 256) def num_chars_that_this_many_octets_encode_to(numos): return log_ceil(256**numos, 62) def a2b(cs): """ @param cs the base-62 encoded data (a string) """ return a2b_l(cs, num_octets_that_encode_to_this_many_chars(len(cs))*8) def a2b_l(cs, lengthinbits): """ @param lengthinbits the number of bits of data in encoded into cs a2b_l() will return a result just big enough to hold lengthinbits bits. So for example if cs is 2 characters long (encoding between 5 and 12 bits worth of data) and lengthinbits is 8, then a2b_l() will return a string of length 1 (since 1 byte is sufficient to store 8 bits), but if lengthinbits is 9, then a2b_l() will return a string of length 2. Please see the warning in the docstring of b2a_l() regarding the use of b2a() versus b2a_l(). @return the data encoded in cs """ cs = [ord(c) for c in reversed(string.translate(cs, c2vtranstable))] # treat cs as big-endian -- and we want to process the least-significant c first value = 0 numvalues = 1 # the number of possible values that value could be for c in cs: c *= numvalues value += c numvalues *= 62 numvalues = 2**lengthinbits bytes = [] while numvalues > 1: bytes.append(value % 256) value //= 256 numvalues //= 256 return ''.join([chr(b) for b in reversed(bytes)]) # make it big-endian
z-base-62
/z-base-62-1.0.1.tar.gz/z-base-62-1.0.1/base62/base62.py
base62.py
from __future__ import print_function import datetime from pprint import pprint import sys doc = """ up next... """ #-------------------- # global variables #-------------------- blank_space = " " colon_mark = ":" def stop(): out("Stoped manually...") exit() #------------------------ # Module => say_hello() #------------------------ def hello(): # out(f"Good evening!\tout will auto print nicely!", show_time=True) t = int(time(time_format="hour")) if t in range(0, 6): print("🔥 OMG!现在是清晨!您起得太早了吧?燃起来了^_^") elif t in range(6, 12): print("🌅 早上好,🍵咖啡+牛奶,开启美好一天!") elif t in range(12, 14): print("😎 要记得午休!中午不睡,下午瞌睡!记得保护眼睛!") elif t in range(14, 18): print("🎶 上班ing...") elif t in range(18, 19): print("🍕 下班!吃饭!") elif t in range(19, 23): print("🌙 晚上好!据说这个时间点可以培养一生的爱好!") elif t in range(23, 24): print("🌆 该睡觉了!关机!上床!晚安!") #--------------------- # Module => time_str print #--------------------- def time(time_format="time", time_symlink = ":"): """ - 时间参数: - time_format = "time" # "time": hour,minute,second,可选"date"(year,month,day), "datetime" - time_symlink = ":" # 时间之间的连接符 hour:minute:second - test code: print("time:", time("time", ":")) print("date:", time("date", "-")) print("datetime:", time("datetime", "-")) """ import datetime assert time_format in ["time", "date", "datetime", "hour"], "time_format invalid!" fmt = "" if time_format == "time": fmt = time_symlink.join(["%H", "%M", "%S"]) elif time_format == "date": # fmt = time_symlink.join(["%Y", "%m", "%d"]) fmt = "%Y-%m-%d" elif time_format == "datetime": fmt = "%Y-%m-%d " + time_symlink.join(["%H", "%M", "%S"]) elif time_format == "hour": fmt = "%H" return datetime.datetime.now().strftime(fmt) # -------------------------------------------------------- # Module => Use out() to print to console and to file. # -------------------------------------------------------- def out(*message, to_console=True, # 输出到console(default) to_file=None, # 输出到file,两种类型,str和io_text. 1.str类型是传入地址,自动创建并且打开文件,需要指定文件的mode,即to_file_mode;2.IO_text类型,提前创建文件,直接传入open后的文件名 to_file_mode="a+", # to_file为地址时设定,默认为"w+",如果是IO_text类型,不需要使用此参数。 show_time=False, # 是否显示时间 time_format="time", # 可选 "time", "date", "datetime" time_symlink = ":", # 时间之间的连接符 hour:minute:second identifier = "(🍉 z_box)", # 标识符, (out) 12:12:31 => message msg_symlink=" ==> ", # message之前的连接符号 pp_stream=None, pp_indent=1, pp_width=80, pp_depth=None, pp_compact=False, # pretty print config end="\n", # 默认打印完换行 ): ''' #----------------------------- # 1.Quick Use #----------------------------- epoch, acc, loss = 77, 0.96712, 0.123 ==> 1.输出到file # 方式1 save_out = "test.log" # <class '_io.TextIOWrapper'> f = open(save_out, "a+") out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", to_file=f, to_console=False) f.close() # 方式2(recommanded) out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", to_file="training_info.txt", to_file_mode="a+", to_console=False) ==> 2.输出到console out("123", show_time=True, time_format="time") out("") # (🍉 z_box) ==> Nothing typed... out() # (🍉 z_box) ==> #--------------------------- # 2.Finished #--------------------------- - 1.自定义前缀,带有标识,(out) 12:12:31 --> - 2.两种方式写入file:# 输出到file,两种类型,str和io_text.  - str类型是传入地址,自动创建并且打开文件,需要指定文件的mode,即to_file_mode; - IO_text类型,提前创建文件,直接传入open后的文件名; -> out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", to_file="training_info.txt", to_file_mode="a+", to_console=True) -> out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", show_time=True ,to_file="training_info.txt", to_file_mode="a+", to_console=False) -> save_out = "test.log" # <class '_io.TextIOWrapper'> -> f = open(save_out, "a+") -> # out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", to_file=f, to_console=True, show_time=True) -> out(f"{epoch}\t{acc}\t{loss}\tcat", to_file=f, show_time=False, to_console=False) -> f.close() - 3. out() => 纳入pretty print,自动根据输入数据的类型进行调整,支持类型如下: -> out("111123", "hhhelo", dict_case) # support for type print(a,b,c) -> out(f"dictionay is:", "123213", dict_case, "----------") # support for type print(a,b,c) -> out(dict_case, f"dictionay is:", "123213", "----------") # support for type print(a,b,c) -> out(f"dictionay is:", array_case, "----------") # support for type print(a,b,c) -> out(dict_case, pp_indent=2, show_time=True) # pretty print -> out("epoch:{}, acc:{:.2f}, loss:{:.2f}".format(66, 0.94823, 0.1234), show_time=True, time_format="date") # support for format-string -> out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", show_time=True) # support for f-string - 4.time() => 根据fomat返回时间字符串,目前支持 "年月日 时分秒" - 5.hello() => 问候函数 #--------------------------- # 3.To do #--------------------------- - time() 提供对 week 的支持。 - 显示代码的文件名和函数 - 配置函数config - 打印一些常用的图、表、分割符号 ''' #------------------------ # global variables #------------------------ global blank_space global colon_mark # at least one output assert to_console or to_file, "Error: you have to choose to output ot [file] or [console]" #------------------------ # ===> Part 1. output to file #------------------------ if to_file: # 1. string to be write into file content_2_file = "" # 2. show time or not (optional) if show_time: content_2_file += f"{time(time_format, time_symlink)}{msg_symlink}" # 3. concat message content_2_file += f"{message[0]}" # unwrap tuple, or pick the first item # 4. check the file input is "str" or "IO_Text" if isinstance(to_file, str): # str -> open then print f = open(to_file, to_file_mode) print(f"{content_2_file}", end=end, file=f) f.close() else: # IO_Text -> print directly print(f"{content_2_file}", end=end, file=to_file) #--------------------------------------------------------------------- # ===> Part 2. output to Console # case one : sigle item e.g. out(f"xxx") # case two : multi itemS e.g. out(f"xxx", x_1, x_2, "xxxx") # solution => [1. str -> print() 2.not str -> pprint()] #--------------------------------------------------------------------- if to_console: # 1.prefix (fixed but can modified) content_2_console = f"{identifier}" # 2.show time or not (optional) if show_time: content_2_console += f"{blank_space}{time(time_format, time_symlink)}" # 3.msg symlink (fixed) content_2_console += f"{msg_symlink}" # 4.print first print(content_2_console, end="") # To here, it should be like this: (🍉 out) 21:44:56 ==> # print("##########", len(message)) # 0.nothing input if len(message) == 0: print("") elif len(message) > 1: # 5.multi itemS in message pre_is_str = True for idx, item in enumerate(message): if isinstance(item, str): # string item -> print() if idx == len(message) - 1: print(item) else: print(item, end=blank_space*2) pre_is_str = True else: # not string, e.g. list or dict -> pprint() if pre_is_str: print("") pprint(item, stream=pp_stream, indent=pp_indent, width=pp_width, depth=pp_depth, compact=pp_compact) # \n else: pprint(item, stream=pp_stream, indent=pp_indent, width=pp_width, depth=pp_depth, compact=pp_compact) pre_is_str = False else: # 6.only one item in message if message[0] == "": # print("") print("Nothing typed...") elif isinstance(*message, str): # string item -> print() print(*message) else: # [dict or list] item -> pprint() print("") pprint(*message, stream=pp_stream, indent=pp_indent, width=pp_width, depth=pp_depth, compact=pp_compact) if __name__ == '__main__': hello() # epoch, acc, loss = 77, 0.96712, 0.123 # import numpy as np # array_case = np.random.randn(4,4) # dict_case = { # "a": 123, # "b": {"123": 123, "456": 456}, # "c": ["777", "Beijing", 1, 2, 3, 4, 5, 6, 7, 8, 9], # "d": 456, # "e": 999 # } # ------------------------------------ # 1. use case to test Console output # ------------------------------------ # out(f"Good evening!\tout will auto print nicely!", show_time=True) # out(dict_case, pp_indent=2, show_time=True) # prety print # out("epoch:{}, acc:{:.2f}, loss:{:.2f}".format(66, 0.94823, 0.1234), show_time=True, time_format="date") # # support for format-string # out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", show_time=True) # support for f-string # out("111123", "hhhelo", dict_case) # support for type print(a,b,c) # out(f"dictionay is:", "123213", dict_case, "----------") # support for type print(a,b,c) # out(dict_case, f"dictionay is:", "123213", "----------") # support for type print(a,b,c) # out(f"dictionay is:", array_case, "----------") # support for type print(a,b,c) # out("epoch:{}, acc:{}, loss:{}".format(epoch, acc, loss)) # ------------------------------------ # 2. use case to test File output # ------------------------------------ # out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", to_file="training_info.txt", to_file_mode="a+", to_console=True) # out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", show_time=True ,to_file="training_info.txt", to_file_mode="a+", to_console=False) # save_out = "test.log" # <class '_io.TextIOWrapper'> # f = open(save_out, "a+") # # out(f"epoch: {epoch} | accuracy: {acc:.2f}% | loss: {loss:.2f}%", to_file=f, to_console=True, show_time=True) # out(f"{epoch}\t{acc}\t{loss}\tcat", to_file=f, show_time=False, to_console=False) # f.close() # out("") # out() # out() # out(array_case, f"epoch: {epoch} | acc: {acc}", dict_case, "time to go!")
z-box
/z_box-0.1.1-py3-none-any.whl/z_box/z.py
z.py
import sys import datetime import time from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR #------------ # to do #----------------- # 触发事件退出 # listener doc = """ #--------------------------- # Quick Start #--------------------------- from z_box import cron from z_box import z #------------------------- # => define your work #------------------------- def work(): print("test----------------") print("job done! If not stop, please press [ctrl + c] => exit") #-------------------------------------------- # => 3-func() to cope with common siatuation #-------------------------------------------- # cron.execute_at(work, at = "2021-7-24-23-52-50") # cron.execute_at(work, at = "23-53-50") # cron.execute_after(work, after="2s") # , scheduler = "background" # cron.execute_circularly(work, interval="1s", begin_at="2021-07-20", end_at="2021-7-25 16:11:30") cron.execute_circularly(work, interval="1s") #---------------------------- # => 另一种方式(不完善) #---------------------------- # while True: # cron.execute_after(work, after="3s", scheduler="background") # time.sleep(4) # sys.exit() """ # 1. [固定时间(年月日时分秒)执行一次] def execute_at( job = None, at = "2021-7-24-11-11-30", # 2-way: [today -"12-27-30"] or ["2021-7-24-11-11-30"] scheduler = "blocking", # blocking , background triger = "cron", ): # time parse # "2021-7-24-11-11-30" or "11-11-30" # time now # prompt print(f"job wil be excuted at {at}, please wait...") time_str = at.strip().split("-") if len(time_str) == 3: hour = at.split("-")[0] minute = at.split("-")[1] second = at.split("-")[2] year = datetime.datetime.today().strftime("%Y") month = datetime.datetime.today().strftime("%m") day = datetime.datetime.today().strftime("%d") elif len(time_str) == 6: year = at.split("-")[0] month = at.split("-")[1] day = at.split("-")[2] hour = at.split("-")[3] minute = at.split("-")[4] second = at.split("-")[5] if scheduler == "blocking": sched = BlockingScheduler() elif scheduler == "background": sched = BackgroundScheduler() if job: sched.add_job(job, triger, year=year, month=month, day=day, hour=hour, minute=minute, second=second) try: sched.start() except (KeyboardInterrupt, SystemExit): sched.shutdown() # 2. [x分钟、x小时后 执行一次] def execute_after( job = None, after = "10s", # 3-way: [1s] [1m] [1d] -> 1分钟、1小时后 scheduler = "blocking", # blocking , background triger = "cron", ): span_unit = after.strip()[-1] span_time = int(after.strip()[: -1]) # prompt print(f"job wil be excuted after {after}, please wait...") now = datetime.datetime.today() if span_unit == "s": timedelta = datetime.timedelta(seconds=span_time) elif span_unit == "m": timedelta = datetime.timedelta(minutes=span_time) elif span_unit == "d": timedelta = datetime.timedelta(days=span_time) execute_time = now + timedelta year = execute_time.strftime("%Y") month = execute_time.strftime("%m") day = execute_time.strftime("%d") hour = execute_time.strftime("%H") minute = execute_time.strftime("%M") second = execute_time.strftime("%S") if scheduler == "blocking": sched = BlockingScheduler() elif scheduler == "background": sched = BackgroundScheduler() if job: sched.add_job(job, triger, year=year, month=month, day=day, hour=hour, minute=minute, second=second) # sched.add_listener(job_exception_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) # print(sched.get_jobs()) try: sched.start() except (KeyboardInterrupt, SystemExit): sched.shutdown() print(sched.get_jobs()) # [间隔时间 区间 循环执行] def execute_circularly( job = None, interval = "5s", # execute at every 5second begin_at = None, # "2021-07-20". format: "2021-7-24 14:11:30" end_at = None, # "2021-7-25" : 24号晚24点结束,25号这一天不包括 scheduler = "blocking", # blocking , background triger = "cron", # day_of_week="0-6" ): second = None minute = None hour = None day = None month = None year = None # prompt if begin_at and end_at: print(f"job wil be excuted during {begin_at} - {end_at}, at every {interval}, please wait...") else: print(f"job wil be excuted at every {interval}, please wait...") span_unit = interval[-1] span_time = int(interval[: -1]) if span_unit == "s": second = "*/{}".format(span_time) elif span_unit == "m": minute = "*/{}".format(span_time) elif span_unit == "d": day = "*/{}".format(span_time) elif span_unit == "M": month = "*/{}".format(span_time) elif span_unit == "h": hour = "*/{}".format(span_time) elif span_unit == "y": year = "*/{}".format(span_time) if scheduler == "blocking": sched = BlockingScheduler() elif scheduler == "background": sched = BackgroundScheduler() if job: sched.add_job(job, triger, year=year, month=month, day=day, hour=hour, minute=minute, second=second, start_date=begin_at, end_date=end_at, ) try: sched.start() except (KeyboardInterrupt, SystemExit): sched.shutdown() def execute_weekly(): # scheduler.add_job(job, 'cron', day_of_week="0-6", second="*/2") pass #---------------- # jobs #--------------- def job_example(): print("aps testing....") def job_execute_py(py_file="test.py"): import os command = "python " + py_file os.system(command) print("done") if __name__ == '__main__': # print(z.time()) # execute_at(job_example, at = "2021-7-24-12-26-50") # execute_at(job_example, at = "12-27-30") # execute_after(job_example, after = "1m") # execute_after(job_execute_py, after="2s") # , scheduler = "background" # execute_circularly(job_example, interval="1s", begin_at="2021-07-20", end_at="2021-7-24 16:11:30") execute_circularly(job_example, interval="1s")
z-box
/z_box-0.1.1-py3-none-any.whl/z_box/cron.py
cron.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Gaussian(Distribution): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu=0, sigma=1): Distribution.__init__(self, mu, sigma) def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.calculate_mean() sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y def __add__(self, other): """Function to add together two Gaussian distributions Args: other (Gaussian): Gaussian instance Returns: Gaussian: Gaussian distribution """ result = Gaussian() result.mean = self.mean + other.mean result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) return result def __repr__(self): """Function to output the characteristics of the Gaussian instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}".format(self.mean, self.stdev)
z-distributions
/z_distributions-0.1.tar.gz/z_distributions-0.1/z_distributions/Gaussiandistribution.py
Gaussiandistribution.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) number of trials TODO: Fill out all functions below """ def __init__(self, prob=.5, size=20): self.n = size self.p = prob Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ self.mean = self.p * self.n return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ self.stdev = math.sqrt(self.n * self.p * (1 - self.p)) return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.n = len(self.data) self.p = 1.0 * sum(self.data) / len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n]) plt.title('Bar Chart of Data') plt.xlabel('outcome') plt.ylabel('count') def pdf(self, k): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k))) b = (self.p ** k) * (1 - self.p) ** (self.n - k) return a * b def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for i in range(self.n + 1): x.append(i) y.append(self.pdf(i)) # make the plots plt.bar(x, y) plt.title('Distribution of Outcomes') plt.ylabel('Probability') plt.xlabel('Outcome') plt.show() return x, y def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
z-distributions
/z_distributions-0.1.tar.gz/z_distributions-0.1/z_distributions/Binomialdistribution.py
Binomialdistribution.py
# Standard Python Library Imports import os.path import argparse import sys import re # 3rd Party Imports import jsbeautifier import cssformatter from jsmin import jsmin # 1st Party Imports def remove_css_variables(css_content): """Remove CSS variables from the CSS and replace each usage of the variable with its value (via RegEx). - Useful for IE 11, which does not support CSS variables: http://caniuse.com/#feat=css-variables """ # Find all of the CSS variable declarations css_var_definitions = re.compile(r"--(?P<var_name>[\w-]+?):\s+?(?P<var_val>.+?);") variables = re.findall(css_var_definitions, css_content) # Some CSS variables use other nested CSS variables in their definition. Replace each by working backwards. for var_name, var_value in reversed(variables): css_content = css_content.replace("var(--" + var_name + ")", var_value) # Remove the :root{} section with all of the CSS variable declarations css_content = css_content.replace(re.match(r":root \{[\s\S]*?\}", css_content).group(0), "") return css_content def format_css(content, minify): if minify: content = remove_css_variables(content) return cssformatter.format_css(content, 'compress') else: return cssformatter.format_css(content, 'expand-bs', ' ') def format_js(content, minify): if minify: return jsmin(content, quote_chars="""'\"`""") else: return jsbeautifier.beautify(content) def format_file(path, minify): """Unified formatting function for files. """ path = os.path.abspath(path) if not os.path.isfile(path): sys.exit("Error: file does not exist {}".format(path)) content = open(path, 'r').read() root, extension = os.path.splitext(path) formatters = { ".js": format_js, ".css": format_css, } if extension not in formatters.keys(): sys.exit("Error: unknown file extension {}".format(extension)) fm_func = formatters[extension] result = fm_func(content, minify) if minify: path = root + ".min" + extension open(path, 'w').write(result) def main(): """Command Line entry point. """ arg_parser = argparse.ArgumentParser( description="An opinionated CLI formatter for JavaScript and CSS (beautify or minimize).\n\n " "If the file is being beautified, the file's contents are replaced with the new " "formatting. If the file is being minimized, we create a new file with `.min` " "before the normal file extensions (e.g. `.min.js` or `.min.css`).\n\n For CSS " "minification, this will remove CSS variables by using search and replace to " "support IE 11." ) arg_parser.add_argument('path', type=str, help="file's path to format") arg_parser.add_argument('-m', '--minify', default=False, action="store_true", help="minimize the file's content instead of beautifying") args = arg_parser.parse_args() format_file(args.path, args.minify) if __name__ == "__main__": main()
z-format
/z_format-0.7.0-py3-none-any.whl/format.py
format.py
import re def format_css(code, action='compact', indentation='\t'): actFuns = { 'expand' : expand_rules, 'expand-bs' : expand_rules, # expand (break selectors) 'compact' : compact_rules, 'compact-bs' : compact_rules, # compact (break selectors) 'compact-ns' : compact_ns_rules, # compact (no spaces) 'compact-bs-ns' : compact_ns_rules, # compact (break selectors, no spaces) 'compress' : compress_rules } if action not in actFuns: return code # Comments if action == 'compress': # Remove comments code = re.sub(r'\s*\/\*[\s\S]*?\*\/\s*', '', code) else: # Protect comments commentReg = r'[ \t]*\/\*[\s\S]*?\*\/' comments = re.findall(commentReg, code) code = re.sub(commentReg, '!comment!', code) # Protect strings stringReg = r'(content\s*:|[\w-]+\s*=)\s*(([\'\"]).*?\3)\s*' strings = re.findall(stringReg, code) code = re.sub(stringReg, r'\1!string!', code) # Protect urls urlReg = r'((?:url|url-prefix|regexp)\([^\)]+\))' urls = re.findall(urlReg, code) code = re.sub(urlReg, '!url!', code) # Pre process code = re.sub(r'\s*([\{\}:;,])\s*', r'\1', code) # remove \s before and after characters {}:;, code = re.sub(r'([\[\(])\s*', r'\1', code) # remove space inner [ or ( code = re.sub(r'\s*([\)\]])', r'\1', code) # remove space inner ) or ] # code = re.sub(r'(\S+)\s*([\+>~])\s*(\S+)', r'\1\2\3', code) # remove \s before and after relationship selectors code = re.sub(r',[\d\s\.\#\+>~:]*\{', '{', code) # remove invalid selectors without \w code = re.sub(r'([;,])\1+', r'\1', code) # remove repeated ;, if action != 'compress': # Group selector if re.search('-bs', action): code = break_selectors(code) # break after selectors' , else: code = re.sub(r',\s*', ', ', code) # add space after , # Add space if re.search('-ns', action): code = re.sub(r', +', ',', code) # remove space after , code = re.sub(r'\s+!important', '!important', code) # remove space before !important else: code = re.sub(r'([A-Za-z-](?:\+_?)?):([^;\{]+[;\}])', r'\1: \2', code) # add space after properties' : code = re.sub(r'\s*!important', ' !important', code) # add space before !important # Process action rules code = actFuns[action](code) if action == 'compress': # Remove last semicolon code = code.replace(';}', '}') else: # Add blank line between each block in `expand-bs` mode if action == 'expand-bs': code = re.sub(r'\}\s*', '}\n\n', code) # double \n after } # Fix comments code = re.sub(r'\s*!comment!\s*@', '\n\n!comment!\n@', code) code = re.sub(r'\s*!comment!\s*([^\/\{\};]+?)\{', r'\n\n!comment!\n\1{', code) code = re.sub(r'\s*\n!comment!', '\n\n!comment!', code) # Backfill comments for i in range(len(comments)): code = re.sub(r'[ \t]*!comment!', comments[i], code, 1) # Indent code = indent_code(code, indentation) # Backfill strings for i in range(len(strings)): code = code.replace('!string!', strings[i][1], 1) # Backfill urls for i in range(len(urls)): code = code.replace('!url!', urls[i], 1) # Trim code = re.sub(r'^\s*(\S+(\s+\S+)*)\s*$', r'\1', code) return code # Expand Rules def expand_rules(code): code = re.sub('{', ' {\n', code) # add space before { and add \n after { code = re.sub(';', ';\n', code) # add \n after ; code = re.sub(r';\s*([^\{\};]+?)\{', r';\n\n\1{', code) # double \n between ; and include selector code = re.sub(r'\s*(!comment!)\s*;\s*', r' \1 ;\n', code) # fix comment before ; code = re.sub(r'(:[^:;]+;)\s*(!comment!)\s*', r'\1 \2\n', code) # fix comment after ; code = re.sub(r'\s*\}', '\n}', code) # add \n before } code = re.sub(r'\}\s*', '}\n', code) # add \n after } return code # Compact Rules def compact_rules(code): code = re.sub('{', ' { ', code) # add space before and after { code = re.sub(r'(@[\w-]*(document|font-feature-values|keyframes|media|supports)[^;]*?\{)\s*', r'\1\n', code) # add \n after @xxx { code = re.sub(';', '; ', code) # add space after ; code = re.sub(r'(@(charset|import|namespace).+?;)\s*', r'\1\n', code) # add \n after @charset & @import code = re.sub(r';\s*([^\};]+?\{)', r';\n\1', code) # add \n before included selector code = re.sub(r'\s*(!comment!)\s*;', r' \1 ;', code) # fix comment before ; code = re.sub(r'(:[^:;]+;)\s*(!comment!)\s*', r'\1 \2 ', code) # fix comment after ; code = re.sub(r'\s*\}', ' }', code) # add space before } code = re.sub(r'\}\s*', '}\n', code) # add \n after } return code # Compact Rules (no space) def compact_ns_rules(code): code = re.sub(r'(@[\w-]*(document|font-feature-values|keyframes|media|supports)[^;]*?\{)\s*', r'\1\n', code) # add \n after @xxx { code = re.sub(r'(@(charset|import|namespace).+?;)\s*', r'\1\n', code) # add \n after @charset & @import code = re.sub(r';\s*([^\};]+?\{)', r';\n\1', code) # add \n before included selector code = re.sub(r'\s*(!comment!)\s*;', r'\1;', code) # fix comment before ; code = re.sub(r'(:[^:;]+;)\s*(!comment!)\s*', r'\1\2', code) # fix comment after ; code = re.sub(r'\}\s*', '}\n', code) # add \n after } return code # Compress Rules def compress_rules(code): code = re.sub(r'\s*([\{\}:;,])\s*', r'\1', code) # remove \s before and after characters {}:;, again code = re.sub(r'\s+!important', '!important', code) # remove space before !important code = re.sub(r'((?:@charset|@import)[^;]+;)\s*', r'\1\n', code) # add \n after @charset & @import return code # Break after Selector def break_selectors(code): block = code.split('}') for i in range(len(block)): b = block[i].split('{') bLen = len(b) for j in range(bLen): if j == bLen - 1: b[j] = re.sub(r',\s*', ', ', b[j]) # add space after properties' , else: s = b[j].split(';') sLen = len(s) sLast = s[sLen - 1] for k in range(sLen - 1): s[k] = re.sub(r',\s*', ', ', s[k]) # add space after properties' , # For @document, @media if re.search(r'\s*@(document|media)', sLast): s[sLen - 1] = re.sub(r',\s*', ', ', sLast) # add space after @media's , # For mixins elif re.search(r'(\(|\))', sLast): u = sLast.split(')') for m in range(len(u)): v = u[m].split('(') vLen = len(v) if vLen < 2: continue v[0] = re.sub(r',\s*', ',\n', v[0]) v[1] = re.sub(r',\s*', ', ', v[1]) # do not break arguments u[m] = '('.join(v) s[sLen - 1] = ')'.join(u) # For selectors else: s[sLen - 1] = re.sub(r',\s*', ',\n', sLast) # add \n after selectors' , b[j] = ';'.join(s) block[i] = '{'.join(b) code = '}'.join(block) return code # Code Indent def indent_code(code, indentation='\t'): lines = code.split('\n') level = 0 inComment = False outPrefix = '' for i in range(len(lines)): if not inComment: # Quote level adjustment validCode = re.sub(r'\/\*[\s\S]*?\*\/', '', lines[i]) validCode = re.sub(r'\/\*[\s\S]*', '', validCode) adjustment = validCode.count('{') - validCode.count('}') # Trim m = re.match(r'^(\s+)\/\*.*', lines[i]) if m is not None: outPrefix = m.group(1) lines[i] = re.sub(r'^' + outPrefix + '(.*)\s*$', r'\1', lines[i]) else: lines[i] = re.sub(r'^\s*(.*)\s*$', r'\1', lines[i]) else: # Quote level adjustment adjustment = 0 # Trim lines[i] = re.sub(r'^' + outPrefix + '(.*)\s*$', r'\1', lines[i]) # Is next line in comment? commentQuotes = re.findall(r'\/\*|\*\/', lines[i]) for quote in commentQuotes: if inComment and quote == '*/': inComment = False elif quote == '/*': inComment = True # Quote level adjustment nextLevel = level + adjustment thisLevel = level if adjustment > 0 else nextLevel level = nextLevel # Add indentation lines[i] = indentation * thisLevel + lines[i] if lines[i] != '' else '' code = '\n'.join(lines) return code
z-format
/z_format-0.7.0-py3-none-any.whl/cssformatter.py
cssformatter.py
# z-format An opinionated CLI formatter for JavaScript and CSS (beautify or minimize). If the file is being beautified, the file's contents are replaced with the new formatting. If the file is being minimized, we create a new file with `.min` before the normal file extensions (e.g. `.min.js` or `.min.css`). ## Usage ```sh usage: format.py [-h] [-m] path An opinionated CLI formatter for JavaScript and CSS (beautify or minimize). positional arguments: path file's path to format optional arguments: -h, --help show this help message and exit -m, --minify minimize the file's content instead of beautifying ``` ## Install ```sh pip install z-format ``` ## Dependencies This is a simple wrapper for several libraries which it installs by default: - jsbeautifier - JavaScript beautification - jsmin - JavaScript minification - cssformatter - CSS beautification and minification ## License MIT License Copyright (c) 2017 Joshua S. Ziegler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
z-format
/z_format-0.7.0-py3-none-any.whl/z_format-0.7.0.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
from __future__ import annotations from typing import Any, Dict, Iterable from zormpg.base import DataModel import peewee as pee import json import copy import logging logger = logging.getLogger(__name__) class DictValue: def __init__(self, default) -> None: """ default: default value the type of default value must be in str, int, float, bool, list, dict """ self.default = default t = type(self.default) if t not in [str, int, float, bool, list, dict]: raise Exception(f'默认值类型必须在str, int, float, bool, list, dict中,但获得的是{t}') self.key = None self.owner: DictModel = None self._cache = None @property def cache(self): return copy.deepcopy(self._cache) @cache.setter def cache(self,value): self._cache = value def _get_row(self) -> DictModel: return self.owner.select().where(self.owner.__class__._model_key == self.key).get() def _get(self): if self.cache is not None: return self.cache v = self.default n = self._count() if n == 0: self.cache = self.default return self.cache try: v = self._get_row()._model_value self.cache = json.loads(v) return self.cache except: logger.warning(f'表{self.owner._table_name}的键{self.key}的值{v}解析失败.返回原始值') return v def _count(self): return self.owner.select().where(self.owner.__class__._model_key == self.key).count() def _set(self, value): if self._count() == 0: row = self.owner.__class__() row._model_key = self.key else: row = self._get_row() row._model_value = json.dumps(value) row.save() self.cache = value logger.debug(f'设置表 {self.owner._table_name} 的 {self.key} 为 {value}') class DictModel(DataModel): _model_key = pee.CharField() _model_value = pee.TextField() def __init__(self, *args, **kwargs): self._stored_dict: Dict[str, DictValue] = {} for k, v in self.__class__.__dict__.items(): if isinstance(v, DictValue): v.key = k v.owner = self self._stored_dict[k] = v super().__init__(*args, **kwargs) def __getattribute__(self, _name: str) -> Any: if _name == '_stored_dict': return super().__getattribute__(_name) if _name in self._stored_dict: return self._stored_dict[_name]._get() return super().__getattribute__(_name) def __setattr__(self, __name: str, __value: Any) -> None: if __name == '_stored_dict': return super().__setattr__(__name, __value) if __name in self._stored_dict: return self._stored_dict[__name]._set(__value) else: return super().__setattr__(__name, __value)
z-orm-pg
/z-orm-pg-0.1.1.tar.gz/z-orm-pg-0.1.1/zormpg/dict_model.py
dict_model.py
from typing import Dict import peewee as pee from zormpg.connect import ZormPgConnect from playhouse.migrate import PostgresqlMigrator, migrate import logging logger = logging.getLogger(__name__) TYPE_MAP = { pee.CharField: "character varying", pee.IntegerField: "integer", pee.PrimaryKeyField: "integer", pee.BigIntegerField: "bigint", pee.TextField: "text", pee.DoubleField: "double precision", pee.ForeignKeyField: "integer" } DEFAULT_VALUE = { pee.CharField: "", pee.IntegerField: 0, pee.BigIntegerField: 0, pee.TextField: "", pee.DoubleField: 0 } db = ZormPgConnect.db class DataModel(pee.Model): _table_name:str = 'data_model' id = pee.PrimaryKeyField() class Meta: database = db def table_function(c): return c._table_name @classmethod def migrate(cls): if '_table_name' not in cls.__dict__: raise Exception('请用类静态属性:_table_name 指定表名') if cls.table_exists(): logger.info(f"已存在表: {cls.__name__}") cls.migrate_columns() else: logger.info(f"创建表: {cls.__name__}") db.create_tables([cls]) @classmethod def get_fields(cls): fields: Dict[str, pee.Field] = {} for key, value in cls.__dict__.items(): field = getattr(value, "field", False) if isinstance(field, pee.Field): fields[key] = field return fields @classmethod def migrate_columns(cls): fields = cls.get_fields() table = cls._table_name sql = """ SELECT column_name, data_type FROM information_schema.COLUMNS WHERE table_name = '%s'; """ % table existed_cols = dict(db.execute_sql(sql).fetchall()) col_to_field = {} for field in fields.values(): if isinstance(field, pee.ForeignKeyField): if field.model != cls: continue if field.default == None: field.default = DEFAULT_VALUE.get(type(field),None) col_to_field[field.column_name] = field need_drop = [] need_add = [] for col, field in col_to_field.items(): if col in existed_cols: if TYPE_MAP[type(field)] == existed_cols[col]: continue need_drop.append(col) need_add.append(col) for col in existed_cols: if col not in col_to_field: need_drop.append(col) migrator = PostgresqlMigrator(db) operations = [] for name in need_drop: operations.append(migrator.drop_column(table, name)) for name in need_add: operations.append(migrator.add_column(table, name, col_to_field[name])) migrate(*operations)
z-orm-pg
/z-orm-pg-0.1.1.tar.gz/z-orm-pg-0.1.1/zormpg/base.py
base.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Gaussian(Distribution): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu=0, sigma=1): Distribution.__init__(self, mu, sigma) def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.calculate_mean() sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y def __add__(self, other): """Function to add together two Gaussian distributions Args: other (Gaussian): Gaussian instance Returns: Gaussian: Gaussian distribution """ result = Gaussian() result.mean = self.mean + other.mean result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) return result def __repr__(self): """Function to output the characteristics of the Gaussian instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}".format(self.mean, self.stdev)
z-probability
/z_probability-0.1.tar.gz/z_probability-0.1/z_probability/Gaussiandistribution.py
Gaussiandistribution.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) number of trials TODO: Fill out all functions below """ def __init__(self, prob=.5, size=20): self.n = size self.p = prob Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ self.mean = self.p * self.n return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ self.stdev = math.sqrt(self.n * self.p * (1 - self.p)) return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.n = len(self.data) self.p = 1.0 * sum(self.data) / len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n]) plt.title('Bar Chart of Data') plt.xlabel('outcome') plt.ylabel('count') def pdf(self, k): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k))) b = (self.p ** k) * (1 - self.p) ** (self.n - k) return a * b def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for i in range(self.n + 1): x.append(i) y.append(self.pdf(i)) # make the plots plt.bar(x, y) plt.title('Distribution of Outcomes') plt.ylabel('Probability') plt.xlabel('Outcome') plt.show() return x, y def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
z-probability
/z_probability-0.1.tar.gz/z_probability-0.1/z_probability/Binomialdistribution.py
Binomialdistribution.py
from __future__ import annotations from typing import Iterable from . import unit as u from .unit import Unit, BaseUnit class UnitRegistry: def __init__(self, units: Iterable[Unit], base_unit: Unit = None): self._base_unit = base_unit self._symbol_to_unit = {} if self._base_unit is None: for unit in units: self._symbol_to_unit[unit.symbol] = unit if isinstance(unit, BaseUnit): self._base_unit = unit elif self._base_unit not in units: raise ValueError(f"Base unit {self._base_unit} is not in the list of units") if self._base_unit is None: raise ValueError("No base unit found") self._units = units @property def base_unit(self): return self._base_unit def get_unit(self, symbol: str): if unit := self._symbol_to_unit.get(symbol): return unit raise ValueError(f"Unit '{symbol}' not found") @property def units(self): return self._units length = UnitRegistry(units=[ u.meter, u.kilometer, u.decimeter, u.centimeter, u.millimeter, u.micrometer, u.foot, u.inch ]) area = UnitRegistry([ u.square_meter, u.square_kilometer, u.square_decimeter, u.square_centimeter, u.square_millimeter, u.square_micrometer, u.square_foot, u.square_inch ]) volume = UnitRegistry(units=[ u.cubic_meter, u.cubic_centimeter, u.cubic_millimeter, u.millimeter, u.liter, u.milliliter, u.cubic_foot, u.cubic_inch, u.gallon, u.barrel ]) time = UnitRegistry(units=[ u.second, u.minute, u.hour, u.day, u.week, u.year, u.month ]) mass = UnitRegistry(units=[ u.kilogram, u.gram, u.tonne, u.pound ]) force = UnitRegistry([ u.newton, u.kilogram_meter_per_second_squared, u.kilo_newton, u.dyne, u.kilogram_force, u.tonne_force, u.pound_force, ]) substance = UnitRegistry(units=[ u.kilomole, u.mole, u.normal_cubic_meter, u.standard_cubic_meter, u.standard_cubic_foot, u.kilo_standard_cubic_foot, u.million_standard_cubic_foot ]) energy = UnitRegistry(units=[ u.kilojoule, u.joule, u.megajoule, u.gigajoule, u.kilowatt_hour, u.kilowatt_year, u.calorie, u.kilocalorie, u.megacalorie, u.gigacalorie, u.million_kilocalorie, u.british_thermal_unit, u.million_british_thermal_unit, u.pound_force_foot ]) velocity = UnitRegistry([ u.meter_per_second, u.meter_per_minute, u.meter_per_hour, u.kilometer_per_hour, u.centimeter_per_second, u.foot_per_second, u.foot_per_minute, u.foot_per_hour ]) temperature = UnitRegistry(units=[ u.celsius, u.kelvin, u.fahrenheit, u.rankine ]) delta_temperature = UnitRegistry([ u.delta_celsius, u.delta_kelvin, u.delta_rankine, u.delta_fahrenheit ]) pressure = UnitRegistry(units=[ u.kilopascal, u.megapascal, u.bar, u.millibar, u.pascal, u.atm, u.kg_force_per_square_centimeter, u.psi, u.pound_force_per_square_foot, u.torr, u.mm_Hg, u.inch_Hg, u.inch_Hg_60F, u.kilopascal_gauge, u.megapascal_gauge, u.bar_gauge, u.millibar_gauge, u.kg_force_per_square_centimeter_gauge, u.psi_gauge, u.pound_force_per_square_foot_gauge, u.torr_gauge, u.mm_Hg_gauge, u.inch_Hg_gauge, u.inch_Hg_60F_gauge ]) molar_flow = UnitRegistry(units=[ u.kilomole_per_second, u.kilomole_per_hour, u.kilomole_per_minute, u.normal_cubic_meter_per_hour, u.normal_cubic_meter_per_day, u.standard_cubic_meter_per_hour, u.standard_cubic_meter_per_day, u.mole_per_hour, u.mole_per_minute, u.mole_per_second, u.standard_cubic_foot_per_day, u.kilo_standard_cubic_foot_per_hour, u.kilo_standard_cubic_foot_per_day, u.million_standard_cubic_foot_per_hour, u.million_standard_cubic_foot_per_day ]) mass_flow = UnitRegistry(units=[ u.kilogram_per_hour, u.kilogram_per_minute, u.kilogram_per_second, u.kilogram_per_day, u.tonne_per_day, u.tonne_per_hour, u.tonne_per_year, u.gram_per_hour, u.gram_per_minute, u.gram_per_second, u.pound_per_hour, u.pound_per_day, u.kilo_pound_per_hour, u.kilo_pound_per_day, u.million_pound_per_day ]) volume_flow = UnitRegistry(units=[ u.cubic_meter_per_hour, u.cubic_meter_per_minute, u.cubic_meter_per_second, u.cubic_meter_per_day, u.liter_per_hour, u.liter_per_day, u.liter_per_minute, u.liter_per_second, u.milliliter_per_hour, u.milliliter_per_minute, u.milliliter_per_second, u.barrel_per_day, u.barrel_per_hour, u.million_gallon_per_day, u.US_gallon_per_minute, u.US_gallon_per_hour, u.cubic_foot_per_hour, u.cubic_foot_per_day ]) energy_flow = UnitRegistry(units=[ u.kilojoule_per_hour, u.kilojoule_per_minute, u.kilojoule_per_second, u.megajoule_per_hour, u.gigajoule_per_hour, u.kilowatt, u.megawatt, u.kilocalorie_per_hour, u.kilocalorie_per_minute, u.kilocalorie_per_second, u.million_kilocalorie_per_hour, u.calorie_per_hour, u.calorie_per_minute, u.calorie_per_second, u.Btu_per_hour, u.million_Btu_per_hour, u.million_Btu_per_day, u.horse_power ]) heat_flow = energy_flow molar_density = UnitRegistry([ u.kilomole_per_cubic_meter, u.mole_per_liter, u.mole_per_cubic_centimeter, u.mole_per_milliliter ]) molar_heat_capacity = UnitRegistry([ u.kilojoule_per_mole_celsius, u.kilojoule_per_mole_kelvin, u.kilojoule_per_kilomole_celsius, u.kilojoule_per_kilomole_kelvin, u.joule_per_mole_celsius, u.joule_per_mole_kelvin, u.joule_per_kilomole_celsius, u.joule_per_kilomole_kelvin, u.kilocalorie_per_mole_celsius, u.kilocalorie_per_mole_kelvin, u.kilocalorie_per_kilomole_celsius, u.kilocalorie_per_kilomole_kelvin, u.calorie_per_mole_celsius, u.calorie_per_mole_kelvin, u.calorie_per_kilomole_celsius, u.calorie_per_kilomole_kelvin ]) molar_entropy = molar_heat_capacity thermal_conductivity = UnitRegistry([ u.watt_per_meter_kelvin, u.Btu_per_hour_foot_fahrenheit, u.kilocalorie_per_meter_hour_celsius, u.calorie_per_centimeter_second_celsius ]) viscosity = UnitRegistry([ u.centipoise, u.millipoise, u.micropoise, u.poise, u.pascal_second, u.pound_force_second_per_square_foot, u.pound_mass_per_foot_second, u.pound_mass_per_foot_hour ]) surface_tension = UnitRegistry([ u.dyne_per_centimeter, u.dyn_per_centimeter, u.pound_force_per_foot ]) mass_heat_capacity = UnitRegistry([ u.kilojoule_per_gram_celsius, u.kilojoule_per_gram_kelvin, u.kilojoule_per_kilogram_celsius, u.kilojoule_per_kilogram_kelvin, u.joule_per_gram_celsius, u.joule_per_gram_kelvin, u.joule_per_kilogram_celsius, u.joule_per_kilogram_kelvin, u.kilocalorie_per_gram_celsius, u.kilocalorie_per_gram_kelvin, u.kilocalorie_per_kilogram_celsius, u.kilocalorie_per_kilogram_kelvin, u.calorie_per_gram_celsius, u.calorie_per_gram_kelvin, u.calorie_per_kilogram_celsius, u.calorie_per_kilogram_kelvin ]) mass_density = UnitRegistry([ u.kilogram_per_cubic_meter, u.gram_per_liter, u.gram_per_cubic_centimeter, u.gram_per_milliliter ]) standard_gas_flow = UnitRegistry([ u.Unit('sm**3/h', factor=1 / u.hour.factor), u.Unit('sm**3/d', factor=1 / u.day.factor), u.Unit('sm**3/min', factor=1 / u.minute.factor), u.BaseUnit('sm**3/s') ]) molar_enthalpy = UnitRegistry([ u.kilojoule_per_mole, u.kilojoule_per_kilomole, u.joule_per_mole, u.joule_per_kilomole, u.megajoule_per_kilomole, u.kilocalorie_per_mole, u.kilocalorie_per_kilomole, u.calorie_per_mole, u.calorie_per_kilomole ]) molar_heat = molar_enthalpy molar_energy = molar_heat molar_volume = UnitRegistry([ u.cubic_meter_per_mole, u.cubic_meter_per_kilomole, u.liter_per_mole, u.cubic_centimeter_per_mole, u.milliliter_per_mole ]) mass_entropy = mass_heat_capacity mass_heat = UnitRegistry([ u.kilojoule_per_gram, u.kilojoule_per_kilogram, u.joule_per_gram, u.joule_per_kilogram, u.megajoule_per_kilogram, u.kilocalorie_per_gram, u.kilocalorie_per_kilogram, u.calorie_per_gram, u.calorie_per_kilogram, u.Btu_per_pound, ]) mass_enthalpy = mass_heat mass_energy = mass_heat kinematic_viscosity = UnitRegistry([ u.BaseUnit('cSt') ]) fraction = UnitRegistry([ u.dimensionless, u.percent, u.parts_per_million ]) dimensionless = UnitRegistry([ u.dimensionless ])
z-units
/z_units-0.1.4-py3-none-any.whl/z_units/unit_registry.py
unit_registry.py
from __future__ import annotations from typing import Union, Callable from .config import get_local_atmospheric_pressure, get_standard_temperature from .util import multi_replace from . import constant class Unit: """ Class used to represent a Unit. For unit conversion, units belong to same 'family' (unit set) shall be converted from/to one 'base unit' as reference. Creation: unit = Unit(name[, factor, offset]) name: str the quick style name(symbol) of the unit, example: 'kg/s', 'm3/s', 'kJ/mol-C' Simple form used to represent definition, as: 'm3' = 'm**3', 'mol-C' = 'mol*C' factor, offset: numeric value or function, for converting this unit to base unit. unit * factor + offset = base unit If unit conversion is nonlinear, to_base_unit() & from_base_unit() have to be overridden. Example ------- >>> kilometer = Unit('km', factor=1e3) Which meter is base unit Properties ---------- symbol: str the quick style name(symbol) of the unit. factor: float factor value offset: float offset value """ def __init__(self, symbol: str, defined_by=None, factor: Union[float, Callable] = 1, offset: Union[float, Callable] = 0): if isinstance(defined_by, Unit): factor = defined_by.factor if factor == 0: raise ValueError("Factor shall not be 0") self._symbol = symbol.replace(' ', '') self._factor = factor self._offset = offset def to_base_unit(self, value: float): """ Convert value from this unit to base unit :param value: numerical value :return: converted value """ return self.factor * value + self.offset def from_base_unit(self, value: float): """ Convert value from base unit to this unit :param value: numerical valve :return: converted valve """ return (value - self.offset) / self.factor @property def symbol_quick_style(self): """ The default style, quick & easy to typing Quick Style Convention: * No space separator * Power: x ** y -> xy * Multiply: x * y -> x-y * Parentheses will be omitted: x / (y * z) -> x/y-z Examples: m ** 2 -> m2 m * s -> m-s kJ / (C * kg) -> kJ/C-kg :return: quick style symbol in str """ if self._symbol: return multi_replace(self._symbol, { '**': '', '*': '-', '(': '', ')': '', }) return self._symbol @property def symbol_python_style(self): """ Defined Style shows formula :return: defined style symbol in str """ return self._symbol @property def symbol(self): return self.symbol_quick_style @property def factor(self): if callable(self._factor): return self._factor() return self._factor @property def offset(self): if callable(self._offset): return self._offset() return self._offset def __repr__(self): return f"<Unit('{self}')>" def __str__(self): return self.symbol def __format__(self, format_spec=''): if format_spec == '': return self.symbol if format_spec == 'q': return self.symbol_quick_style if format_spec == 'p': return self.symbol_python_style raise ValueError('Invalid format specifier') def __mul__(self, other): # only for factor definition if isinstance(other, Unit): factor = self.factor * other.factor symbol = f"{self.symbol_python_style}*{other.symbol_python_style}" return Unit(symbol, factor=factor) if isinstance(other, (int, float)): factor = self.factor * other return Unit('dummy', factor=factor) return NotImplemented def __rmul__(self, other): factor = other * self.factor return Unit('dummy', factor=factor) def __truediv__(self, other): if isinstance(other, Unit): symbol = f"{self.symbol_python_style}/{other.symbol_python_style}" factor = self.factor / other.factor return Unit(symbol, factor=factor) if isinstance(other, (int, float)): factor = self.factor / other return Unit('dummy', factor=factor) return NotImplemented def __rtruediv__(self, other): if isinstance(other, (int, float)): factor = other / self.factor return Unit('dummy', factor=factor) return NotImplemented def __pow__(self, power, modulo=None): if isinstance(power, (int, float)): symbol = f"{self.symbol_python_style}**{power}" factor = self.factor ** power return Unit(symbol, factor=factor) return NotImplemented class BaseUnit(Unit): """ A class used to represent Base Unit. Creation: base_unit= BaseUnit(name) return a Unit instance with .is_base = True """ def __init__(self, symbol: str): super().__init__(symbol) # basic unit # length, m meter = BaseUnit('m') kilometer = Unit('km', defined_by=1e3 * meter) decimeter = Unit('dm', defined_by=1e-1 * meter) centimeter = Unit('cm', defined_by=1e-2 * meter) millimeter = Unit('mm', defined_by=1e-3 * meter) micrometer = Unit('um', defined_by=1e-6 * meter) foot = Unit('ft', factor=3.048e-1) inch = Unit('in', factor=2.54e-2) # area, m2 square_meter = BaseUnit('m**2') square_kilometer = Unit('km**2', defined_by=kilometer**2) square_decimeter = Unit('dm**2', defined_by=decimeter**2) square_centimeter = Unit('cm**2', defined_by=centimeter**2) square_millimeter = Unit('mm**2', defined_by=millimeter**2) square_micrometer = Unit('um**2', defined_by=micrometer**2) square_foot = Unit('ft**2', defined_by=foot**2) square_inch = Unit('in**2', defined_by=inch**2) # volume, m3 cubic_meter = BaseUnit('m**3') cubic_centimeter = Unit('cm**3', defined_by=centimeter**3) cubic_millimeter = Unit('mm**3', defined_by=millimeter**3) liter = Unit('L', defined_by=decimeter**3) milliliter = Unit('mL', defined_by=centimeter**3) cubic_foot = Unit('ft**3', defined_by=foot**3) cubic_inch = Unit('in**3', defined_by=inch**3) # US_gallon gallon = Unit('gal', defined_by=231 * cubic_inch) barrel = Unit('bbl', defined_by=42 * gallon) # time, s second = BaseUnit('s') minute = Unit('min', defined_by=60 * second) hour = Unit('hr', defined_by=60 * minute) day = Unit('day', defined_by=24 * hour) week = Unit('week', defined_by=7 * day) year = Unit('yr', defined_by=365 * day) month = Unit('mon', defined_by=year / 12) # velocity, m/s meter_per_second = BaseUnit('m/s') meter_per_minute = Unit('m/min', defined_by=meter / minute) meter_per_hour = Unit('m/hr', defined_by=meter / hour) kilometer_per_hour = Unit('km/hr', defined_by=kilometer / hour) centimeter_per_second = Unit('cm/s', defined_by=centimeter / second) foot_per_second = Unit('ft/s', defined_by=foot / second) foot_per_minute = Unit('ft/min', defined_by=foot / minute) foot_per_hour = Unit('ft/hr', defined_by=foot / hour) # temperature base unit celsius = BaseUnit('C') kelvin = Unit('K', offset=-273.15) rankine = Unit('R', factor=5 / 9, offset=-273.15) fahrenheit = Unit('F', factor=5 / 9, offset=-32 * 5 / 9) # mass, kg kilogram = BaseUnit('kg') gram = Unit('g', defined_by=1e-3 * kilogram) tonne = Unit('t', defined_by=1e3 * kilogram) pound = Unit('lb', defined_by=0.45359237 * kilogram) # force, N newton = BaseUnit('N') kilogram_meter_per_second_squared = Unit('kg*m/s**2', defined_by=newton) kilo_newton = Unit('kN', defined_by=1e3 * newton) dyne = Unit('dyn', defined_by=1e-5 * newton) kilogram_force = Unit('kgf', defined_by=constant.G * kilogram) tonne_force = Unit('tonf', defined_by=constant.G * tonne) pound_force = Unit('lbf', defined_by=constant.G * pound) # substance, kmol kilomole = BaseUnit('kmol') mole = Unit('mol', defined_by=1e-3 * kilomole) normal_cubic_meter = Unit('Nm**3', factor=1 / 22.414) # @20 degC standard_cubic_meter = Unit('Sm**3', factor=lambda: normal_cubic_meter.factor * 273.15 / (273.15 + get_standard_temperature())) # scf is @60 degF, so some math need to be done T_60F = kelvin.from_base_unit(fahrenheit.to_base_unit(60)) T_0C = kelvin.from_base_unit(0) standard_cubic_foot = Unit('SCF', defined_by=normal_cubic_meter * cubic_foot * T_0C / T_60F) kilo_standard_cubic_foot = Unit('MSCF', defined_by=1e3 * standard_cubic_foot) million_standard_cubic_foot = Unit('MMSCF', defined_by=1e6 * standard_cubic_foot) # energy, kJ kilojoule = BaseUnit('kJ') joule = Unit('J', defined_by=1e-3 * kilojoule) megajoule = Unit('MJ', defined_by=1e6 * joule) gigajoule = Unit('GJ', defined_by=1e9 * joule) kilowatt_hour = Unit('kW*h', defined_by=kilojoule * hour) kilowatt_year = Unit('kW*yr', defined_by=kilojoule * year) calorie = Unit('cal', factor=4.184e-3) kilocalorie = Unit('kcal', defined_by=1e3 * calorie) megacalorie = Unit('Mcal', defined_by=1e6 * calorie) gigacalorie = Unit('Gcal', defined_by=1e9 * calorie) million_kilocalorie = Unit('MMkcal', defined_by=1e6 * kilocalorie) british_thermal_unit = Unit('Btu', factor=1.055056) million_british_thermal_unit = Unit('MMBtu', defined_by=1e6 * british_thermal_unit) pound_force_foot = Unit('lbf*ft', defined_by=1e-3 * pound_force * foot) # delta temperature delta_celsius = BaseUnit('C') delta_kelvin = Unit('K', factor=1) delta_rankine = Unit('R', factor=5 / 9) delta_fahrenheit = Unit('F', factor=5 / 9) # pressure base unit pascal = BaseUnit('Pa') kilopascal = Unit('kPa', defined_by=1e3 * pascal) megapascal = Unit('MPa', defined_by=1e6 * pascal) bar = Unit('bar', defined_by=1e5 * pascal) millibar = Unit('mbar', defined_by=1e-3 * bar) atm = Unit('atm', factor=constant.ATM) kg_force_per_square_centimeter = Unit('kgf/cm**2', defined_by=kilogram_force / square_centimeter) psi = Unit('psi', defined_by=pound_force / square_inch) pound_force_per_square_foot = Unit('lbf/ft**2', defined_by=pound_force / square_foot) torr = Unit('torr', defined_by=atm / 760) mm_Hg = Unit('mmHg_0C', defined_by=torr) inch_Hg = Unit('inHg_32F', factor=1e3 * 3.386389) inch_Hg_60F = Unit('inHg_60F', factor=1e3 * 3.37685) kilopascal_gauge = Unit('kPag', factor=kilopascal.factor, offset=get_local_atmospheric_pressure) megapascal_gauge = Unit('MPag', factor=megapascal.factor, offset=get_local_atmospheric_pressure) bar_gauge = Unit('barg', factor=bar.factor, offset=get_local_atmospheric_pressure) millibar_gauge = Unit('mbarg', factor=millibar.factor, offset=get_local_atmospheric_pressure) kg_force_per_square_centimeter_gauge = Unit('kgf/cm**2_g', factor=kg_force_per_square_centimeter.factor, offset=get_local_atmospheric_pressure) psi_gauge = Unit('psig', factor=psi.factor, offset=get_local_atmospheric_pressure) pound_force_per_square_foot_gauge = Unit('lbf/ft**2_g', factor=pound_force_per_square_foot.factor, offset=get_local_atmospheric_pressure) torr_gauge = Unit('torr_g', factor=torr.factor, offset=get_local_atmospheric_pressure) mm_Hg_gauge = Unit('mmHg_0C_g', factor=mm_Hg.factor, offset=get_local_atmospheric_pressure) inch_Hg_gauge = Unit('inHg_32F_g', factor=inch_Hg.factor, offset=get_local_atmospheric_pressure) inch_Hg_60F_gauge = Unit('inHg_60F_g', factor=inch_Hg_60F.factor, offset=get_local_atmospheric_pressure) # molar flow, base: kmol/s kilomole_per_second = BaseUnit('kmol/s') kilomole_per_hour = Unit('kmol/h', defined_by=kilomole / hour) kilomole_per_minute = Unit('kmol/min', defined_by=kilomole / minute) normal_cubic_meter_per_hour = Unit('Nm**3/h', defined_by=normal_cubic_meter / hour) normal_cubic_meter_per_day = Unit('Nm**3/d', defined_by=normal_cubic_meter / day) standard_cubic_meter_per_hour = Unit('Sm**3/h', defined_by=standard_cubic_meter / hour) standard_cubic_meter_per_day = Unit('Sm**3/d', defined_by=standard_cubic_meter / day) mole_per_hour = Unit('mol/h', defined_by=mole / hour) mole_per_minute = Unit('mol/min', defined_by=mole / minute) mole_per_second = Unit('mol/s', defined_by=mole) standard_cubic_foot_per_day = Unit('SCFD', defined_by=standard_cubic_foot / day) kilo_standard_cubic_foot_per_hour = Unit('MSCFH', defined_by=kilo_standard_cubic_foot / hour) kilo_standard_cubic_foot_per_day = Unit('MSCFD', defined_by=kilo_standard_cubic_foot / day) million_standard_cubic_foot_per_hour = Unit('MMSCFH', defined_by=million_standard_cubic_foot / hour) million_standard_cubic_foot_per_day = Unit('MMSCFD', defined_by=million_standard_cubic_foot / day) # mass flow, base: kg/s kilogram_per_second = BaseUnit('kg/s') kilogram_per_hour = Unit('kg/h', defined_by=kilogram / hour) kilogram_per_minute = Unit('kg/min', defined_by=kilogram / minute) kilogram_per_day = Unit('kg/d', defined_by=kilogram / day) tonne_per_day = Unit('t/d', defined_by=tonne / day) tonne_per_hour = Unit('t/h', defined_by=tonne / hour) tonne_per_year = Unit('t/yr', defined_by=tonne / year) gram_per_hour = Unit('g/h', defined_by=gram / hour) gram_per_minute = Unit('g/min', defined_by=gram / minute) gram_per_second = Unit('g/s', defined_by=gram / second) pound_per_hour = Unit('lb/h', defined_by=pound / hour) kilo_pound_per_hour = Unit('klb/h', defined_by=1e3 * pound / hour) pound_per_day = Unit('lb/d', defined_by=pound / day) kilo_pound_per_day = Unit('klb/d', defined_by=1e3 * pound / day) million_pound_per_day = Unit('MMlb/d', defined_by=1e6 * pound / day) # volume flow, base: m3/s cubic_meter_per_second = BaseUnit('m**3/s') cubic_meter_per_hour = Unit('m**3/h', defined_by=cubic_meter / hour) cubic_meter_per_minute = Unit('m**3/min', defined_by=cubic_meter / minute) cubic_meter_per_day = Unit('m**3/d', defined_by=cubic_meter / day) liter_per_hour = Unit('L/h', defined_by=liter / hour) liter_per_day = Unit('L/d', defined_by=liter / day) liter_per_minute = Unit('L/min', defined_by=liter / minute) liter_per_second = Unit('L/s', defined_by=liter / second) milliliter_per_hour = Unit('mL/h', defined_by=milliliter / hour) milliliter_per_minute = Unit('mL/min', defined_by=milliliter / minute) milliliter_per_second = Unit('mL/s', defined_by=milliliter / second) barrel_per_day = Unit('bbl/d', defined_by=barrel / day) barrel_per_hour = Unit('bbl/h', defined_by=barrel / hour) million_gallon_per_day = Unit('MMgal/d', defined_by=1e6 * gallon / day) US_gallon_per_minute = Unit('USGPM', defined_by=gallon / minute) US_gallon_per_hour = Unit('USGPH', defined_by=gallon / hour) cubic_foot_per_hour = Unit('ft**3/h', defined_by=cubic_foot / hour) cubic_foot_per_day = Unit('ft**3/d', defined_by=cubic_foot / day) # Energy 'kJ/s' kilojoule_per_second = BaseUnit('kJ/s') kilojoule_per_hour = Unit('kJ/h', defined_by=kilojoule / hour) kilojoule_per_minute = Unit('kJ/min', defined_by=kilojoule / minute) megajoule_per_hour = Unit('MJ/h', defined_by=megajoule / hour) gigajoule_per_hour = Unit('GJ/h', defined_by=gigajoule / hour) kilowatt = Unit('kW', defined_by=kilojoule / second) megawatt = Unit('MW', defined_by=1e3 * kilowatt) kilocalorie_per_hour = Unit('kcal/h', defined_by=kilocalorie / hour) kilocalorie_per_minute = Unit('kcal/min', defined_by=kilocalorie / minute) kilocalorie_per_second = Unit('kcal/s', defined_by=kilocalorie / second) million_kilocalorie_per_hour = Unit('MMkcal/h', defined_by=million_kilocalorie / hour) calorie_per_hour = Unit('cal/h', defined_by=calorie / hour) calorie_per_minute = Unit('cal/min', defined_by=calorie / minute) calorie_per_second = Unit('cal/s', defined_by=calorie / second) Btu_per_hour = Unit('Btu/h', defined_by=british_thermal_unit / hour) million_Btu_per_hour = Unit('MMBtu/h', defined_by=million_british_thermal_unit / hour) million_Btu_per_day = Unit('MMBtu/d', defined_by=million_british_thermal_unit / day) horse_power = Unit('hp', defined_by=0.745699 * kilowatt) # molar density, 'kmol/m3 kilomole_per_cubic_meter = BaseUnit('kmol/m**3') mole_per_liter = Unit('mol/L', defined_by=mole / liter) mole_per_cubic_centimeter = Unit('mol/cm**3', defined_by=mole / cubic_centimeter) mole_per_milliliter = Unit('mol/mL', defined_by=mole / milliliter) # heat capacity, entropy, 'kJ/kmol-C' kilojoule_per_mole_celsius = Unit('kJ/(mol*C)', defined_by=kilojoule / (mole * delta_celsius)) kilojoule_per_mole_kelvin = Unit('kJ/(mol*K)', defined_by=kilojoule / (mole * delta_kelvin)) kilojoule_per_kilomole_celsius = BaseUnit('kJ/(kmol*C)') kilojoule_per_kilomole_kelvin = Unit('kJ/(kmol*K)', defined_by=kilojoule / (kilomole * delta_kelvin)) joule_per_mole_celsius = Unit('J/(mol*C)', defined_by=joule / (mole * delta_celsius)) joule_per_mole_kelvin = Unit('J/(mol*K)', defined_by=joule / (mole * delta_kelvin)) joule_per_kilomole_celsius = Unit('J/(kmol*C)', defined_by=joule / (kilomole * delta_celsius)) joule_per_kilomole_kelvin = Unit('J/(kmol*K)', defined_by=joule / (kilomole * delta_kelvin)) kilocalorie_per_mole_celsius = Unit('kcal/(mol*C)', defined_by=kilocalorie / (mole * delta_celsius)) kilocalorie_per_mole_kelvin = Unit('kcal/(mol*K)', defined_by=kilocalorie / (mole * delta_kelvin)) kilocalorie_per_kilomole_celsius = Unit('kcal/(kmol*C)', defined_by=kilocalorie / (kilomole * delta_celsius)) kilocalorie_per_kilomole_kelvin = Unit('kcal/(kmol*K)', defined_by=kilocalorie / (kilomole * delta_kelvin)) calorie_per_mole_celsius = Unit('cal/(mol*C)', defined_by=calorie / (mole * delta_celsius)) calorie_per_mole_kelvin = Unit('cal/(mol*K)', defined_by=calorie / (mole * delta_kelvin)) calorie_per_kilomole_celsius = Unit('cal/(kmol*C)', defined_by=calorie / (kilomole * delta_celsius)) calorie_per_kilomole_kelvin = Unit('cal/(kmol*K)', defined_by=calorie / (kilomole * delta_kelvin)) # thermal conductivity, W/m-K watt_per_meter_kelvin = BaseUnit('W/(m*K)') Btu_per_hour_foot_fahrenheit = Unit('Btu/(h*ft*F)', defined_by=1e3 * british_thermal_unit / ( hour * foot * delta_fahrenheit)) kilocalorie_per_meter_hour_celsius = Unit('kcal/(m*h*C)', defined_by=1e3 * kilocalorie / hour) calorie_per_centimeter_second_celsius = Unit('cal/(cm*s*C)', defined_by=1e3 * calorie / centimeter) # viscosity, cP centipoise = BaseUnit('cP') millipoise = Unit('mP', factor=0.1) micropoise = Unit('microP', defined_by=1e-3 * millipoise) poise = Unit('P', factor=100) pascal_second = Unit('Pa-s', factor=1000) pound_force_second_per_square_foot = Unit('lbf*s/ft**2', defined_by=1e3 * pound_force / square_foot) pound_mass_per_foot_second = Unit('lbm/(ft*s)', defined_by=1e3 * pound / foot) pound_mass_per_foot_hour = Unit('lbm/(ft*h)', defined_by=1e3 * pound / (foot * hour)) # surface tension, dyne/cm dyne_per_centimeter = BaseUnit('dyne/cm') dyn_per_centimeter = Unit('dyn/cm', factor=1) pound_force_per_foot = Unit('lbf/ft', defined_by=1e3 * pound_force / foot) # mass capacity, kJ/kg-C kilojoule_per_gram_celsius = Unit('kJ/(g*C)', defined_by=kilojoule / (gram * delta_celsius)) kilojoule_per_gram_kelvin = Unit('kJ/(g*K)', defined_by=kilojoule / (gram * delta_kelvin)) kilojoule_per_kilogram_celsius = BaseUnit('kJ/(kg*C)') kilojoule_per_kilogram_kelvin = Unit('kJ/(kg*K)', defined_by=kilojoule / (kilogram * delta_kelvin)) joule_per_gram_celsius = Unit('J/(g*C)', defined_by=joule / (gram * delta_celsius)) joule_per_gram_kelvin = Unit('J/(g*K)', defined_by=joule / (gram * delta_kelvin)) joule_per_kilogram_celsius = Unit('J/(kg*C)', defined_by=joule / (kilogram * delta_celsius)) joule_per_kilogram_kelvin = Unit('J/(kg*K)', defined_by=joule / (kilogram * delta_kelvin)) kilocalorie_per_gram_celsius = Unit('kcal/(g*C)', defined_by=kilocalorie / (gram * delta_celsius)) kilocalorie_per_gram_kelvin = Unit('kcal/(g*K)', defined_by=kilocalorie / (gram * delta_kelvin)) kilocalorie_per_kilogram_celsius = Unit('kcal/(kg*C)', defined_by=kilocalorie / (kilogram * delta_celsius)) kilocalorie_per_kilogram_kelvin = Unit('kcal/(kg*K)', defined_by=kilocalorie / (kilogram * delta_kelvin)) calorie_per_gram_celsius = Unit('cal/(g*C)', defined_by=calorie / (gram * delta_celsius)) calorie_per_gram_kelvin = Unit('cal/(g*K)', defined_by=calorie / (gram * delta_kelvin)) calorie_per_kilogram_celsius = Unit('cal/(kg*C)', defined_by=calorie / (kilogram * delta_celsius)) calorie_per_kilogram_kelvin = Unit('cal/(kg*K)', defined_by=calorie / (kilogram * delta_kelvin)) # mass density, kg/m3 kilogram_per_cubic_meter = BaseUnit('kg/m**3') gram_per_liter = Unit('g/L', defined_by=gram / liter) gram_per_cubic_centimeter = Unit('g/cm**3', defined_by=gram / cubic_centimeter) gram_per_milliliter = Unit('g/mL', defined_by=gram / milliliter) # molar_enthalpy kilojoule_per_mole = Unit('kJ/mol', defined_by=kilojoule / mole) kilojoule_per_kilomole = BaseUnit('kJ/kmol') joule_per_mole = Unit('J/mol', defined_by=joule / mole) joule_per_kilomole = Unit('J/kmol', defined_by=joule / kilomole) megajoule_per_kilomole = Unit('MJ/kmol', defined_by=megajoule / kilomole) kilocalorie_per_mole = Unit('kcal/mol', defined_by=kilocalorie / mole) kilocalorie_per_kilomole = Unit('kcal/kmol', defined_by=kilocalorie / kilomole) calorie_per_mole = Unit('cal/mol', defined_by=calorie / mole) calorie_per_kilomole = Unit('cal/kmol', defined_by=calorie / kilomole) # molar_volume cubic_meter_per_mole = Unit('m**3/mol', defined_by=cubic_meter / mole) cubic_meter_per_kilomole = BaseUnit('m**3/kmol') liter_per_mole = Unit('L/mol', defined_by=liter / mole) cubic_centimeter_per_mole = Unit('cm**3/mol', defined_by=cubic_centimeter / mole) milliliter_per_mole = Unit('mL/mol', defined_by=milliliter / mole) # mass_heat kilojoule_per_gram = Unit('kJ/g', defined_by=kilojoule / gram) kilojoule_per_kilogram = BaseUnit('kJ/kg') joule_per_gram = Unit('J/g', defined_by=joule / gram) joule_per_kilogram = Unit('J/kg', defined_by=joule / kilogram) megajoule_per_kilogram = Unit('MJ/kg', defined_by=megajoule / kilogram) kilocalorie_per_gram = Unit('kcal/g', defined_by=kilocalorie / gram) kilocalorie_per_kilogram = Unit('kcal/kg', defined_by=kilocalorie / kilogram) calorie_per_gram = Unit('cal/g', defined_by=calorie / gram) calorie_per_kilogram = Unit('cal/kg', defined_by=calorie / kilogram) Btu_per_pound = Unit('Btu/lb', defined_by=british_thermal_unit / pound) # fraction dimensionless = BaseUnit('') percent = Unit('%', factor=1e-2) parts_per_million = Unit('ppm', factor=1e-6) # molecular_weight gram_per_mole = Unit('g/mol', factor=1) kilogram_per_kilomole = BaseUnit('kg/kmol') kilogram_per_mole = Unit('kg/mol', factor=1e3)
z-units
/z_units-0.1.4-py3-none-any.whl/z_units/unit.py
unit.py
from __future__ import annotations from typing import List, Union from .unit import Unit from .unit_registry import UnitRegistry from . import unit_registry as reg class Quantity: """ Class used to represent a Quantity A quantity has a value and a unit """ def __init__(self, value, unit: Union[str, Unit] = None): self.value = value if unit is None: self._unit = self.unit_registry.base_unit else: self._unit = self.unit_registry.get_unit(str(unit)) def to(self, unit: Union[str, Unit]): if self.value is None: return None unit = self.unit_registry.get_unit(str(unit)) if unit == self.unit: return self ref_value = self._unit.to_base_unit(self.value) value = unit.from_base_unit(ref_value) return self.__class__(value, unit) @property def unit_registry(self) -> UnitRegistry: return self.get_unit_registry() def get_unit_registry(self): return UnitRegistry(reg.dimensionless) @property def base_unit(self) -> Unit: return self.unit_registry.base_unit @property def units(self) -> List[Unit]: return self.unit_registry.units def to_base(self): return self.to(self.base_unit) def __repr__(self): if isinstance(self.value, float): return f"<{self.__class__.__name__}({self.value:.9}, '{self.unit.symbol}')>" return f"<{self.__class__.__name__}({self.value}, '{self.unit.symbol}')>" def __str__(self): return f'{self.value}' def __format__(self, format_spec=''): if (pos := format_spec.find('u')) > -1: unit = format(self.unit, format_spec[pos + 1:]) format_spec = format_spec[0:pos] if unit: return ' '.join([format(self.value, format_spec), unit]) return format(self.value, format_spec) def __mul__(self, other): if isinstance(other, (int, float)): return self.__class__(self.value * other, self.unit) return NotImplemented def __rmul__(self, other): return self * other def __eq__(self, other): if isinstance(other, self.__class__): return self.to_base().value == other.to_base().value return False def __gt__(self, other): if isinstance(other, self.__class__): return self.to_base().value > other.to_base().value def __ge__(self, other): if isinstance(other, self.__class__): return self.to_base().value >= other.to_base().value @property def unit(self) -> Unit: return self._unit class Length(Quantity): def get_unit_registry(self): return reg.length class Area(Quantity): def get_unit_registry(self): return reg.area class Volume(Quantity): def get_unit_registry(self): return reg.volume class Time(Quantity): def get_unit_registry(self): return reg.time class Mass(Quantity): def get_unit_registry(self): return reg.mass class Force(Quantity): def get_unit_registry(self): return reg.force class Substance(Quantity): def get_unit_registry(self): return reg.substance class Energy(Quantity): def get_unit_registry(self): return reg.energy class Velocity(Quantity): def get_unit_registry(self): return reg.velocity class Temperature(Quantity): def get_unit_registry(self): return reg.temperature class DeltaTemperature(Quantity): def get_unit_registry(self): return reg.delta_temperature class Pressure(Quantity): def get_unit_registry(self): return reg.pressure class VolumeFlow(Quantity): def get_unit_registry(self): return reg.volume_flow class MassDensity(Quantity): def get_unit_registry(self): return reg.mass_density class HeatFlow(Quantity): def get_unit_registry(self): return reg.heat_flow class MolarFlow(Quantity): def get_unit_registry(self): return reg.molar_flow class MassFlow(Quantity): def get_unit_registry(self): return reg.mass_flow class MolarDensity(Quantity): def get_unit_registry(self): return reg.molar_density class MolarHeatCapacity(Quantity): def get_unit_registry(self): return reg.molar_heat_capacity class MolarEntropy(Quantity): def get_unit_registry(self): return reg.molar_entropy class MolarHeat(Quantity): def get_unit_registry(self): return reg.molar_heat class ThermalConductivity(Quantity): def get_unit_registry(self): return reg.thermal_conductivity class Viscosity(Quantity): def get_unit_registry(self): return reg.viscosity class SurfaceTension(Quantity): def get_unit_registry(self): return reg.surface_tension class MassHeatCapacity(Quantity): def get_unit_registry(self): return reg.mass_heat_capacity class MassEntropy(Quantity): def get_unit_registry(self): return reg.mass_entropy class MassHeat(Quantity): def get_unit_registry(self): return reg.mass_heat class StandardGasFlow(Quantity): def get_unit_registry(self): return reg.standard_gas_flow class KinematicViscosity(Quantity): def get_unit_registry(self): return reg.kinematic_viscosity class MolarVolume(Quantity): def get_unit_registry(self): return reg.molar_volume class Fraction(Quantity): def get_unit_registry(self): return reg.fraction class Dimensionless(Quantity): def get_unit_registry(self): return reg.dimensionless
z-units
/z_units-0.1.4-py3-none-any.whl/z_units/quantity.py
quantity.py
======= 2.0.11 ======= |Maturity| |license gpl| Overview ======== Zeroincombenze® continuous testing for odoo ------------------------------------------- This package is an plug-in of **zerobug** package and aim to easily create odoo tests. It replaces OCA MQT with some nice additional features. *z0bug_odoo* is built on follow concepts: * Odoo version independent; it can test Odoo from 6.1 until 16.0 * It is designed to run in local environment too, using `local travis emulator <https://github.com/zeroincombenze/tools/tree/master/travis_emulator>`_ * It can run with full or reduced set of pylint tests * Test using ready-made database records * Quality Check Id travis ci support ----------------- The goal of z0bug_odoo is to provide helpers to ensure the quality of Odoo addons. The code was forked from OCA MQT but some improvements were added. This package and OCA MQT differ by: * z0bug_odoo can also test Odoo 6.1 and 7.0 where OCA MQT fails with these versions * z0bug_odoo is designed to execute some debug statements, mainly in local environment * z0bug_odoo has more options to run with reduced set of lint tests * OCA MQT is the only component to build environment and test Odoo while z0bug_odoo is part of `Zeroincombenze® tools <https://github.com/zeroincombenze/tools>`_ * As per prior rule, building test environment is made by `vem <https://github.com/zeroincombenze/tools/tree/master/https://github.com/zeroincombenze/tools/tree/master/python_plus>`_, `clodoo <https://github.com/zeroincombenze/tools/tree/master/https://github.com/zeroincombenze/tools/tree/master/clodoo>`_ and `lisa <https://github.com/zeroincombenze/tools/tree/master/https://github.com/zeroincombenze/tools/tree/master/lisa>`_. These commands can also build a complete Odoo environment out of the box To make a complete test on TravisCI your project following 3 files are required: * .travis.yml * requirements.txt * oca_dependencies.txt File .travis.yml ~~~~~~~~~~~~~~~~ In order to setup TravisCI continuous integration for your project, just copy the content of the `sample_files <https://github.com/zeroincombenze/tools/tree/master/travis_emulator/template_travis.yml>`_ to your project’s root directory. Then execute the command: :: make_travis_conf <TOOLS_PATH>/travis_emulator/template_travis.yml .travis.yml You can check travis syntax with the `lint checker <http://lint.travis-ci.org/>`_ of travis, if available. Notice: if you do not use travisCi web site, you can avoid to set .travis.yml file. Local travis emulator and z0bug_odoo create local .travis.yml dinamically. Odoo test integration ~~~~~~~~~~~~~~~~~~~~~ Current Odoo project version is declared by **VERSION** variable. If your Odoo module must be tested against Odoo core, you can test specific github repository by **ODOO_REPO** variable. You can test against: * odoo/odoo * OCA/OCB * zeroincombenze/OCB * librerp/OCB You can test against specific Odoo core version with ODOO_BRANCH variable if differs from your project version: :: # Odoo Branch 16.0 - VERSION="16.0" ODOO_REPO="odoo/odoo" # Pull request odoo/odoo#143 - VERSION="pull/143" ODOO_REPO="OCA/OCB" # Branch saas-17 - ODOO_REPO="odoo/odoo" ODOO_BRANCH="saas-17" OCB / core test ~~~~~~~~~~~~~~~ Zeroincombenze® OCB uses submodules. When test is starting, travis-ci upgrades repository and submodules. To avoid submodules upgrade use this directive compatible with OCA MQT: :: - git: submodules: false z0bg_odoo set security environment. You do not need to add any security statements. You can avoid the following OCA MQT directive: :: - pip install urllib3[secure] --upgrade; true z0bg_odoo does some code upgrade. You can avoid following directive in ODOO_TEST_SELECT="APPLICATIONS": :: - sed -i "s/self.url_open(url)/self.url_open(url, timeout=100)/g" ${TRAVIS_BUILD_DIR}/addons/website/tests/test_crawl.py; You can avoid following directive in ODOO_TEST_SELECT="LOCALIZATION": :: - sed -i "/'_auto_install_l10n'/d" ${TRAVIS_BUILD_DIR}/addons/account/__manifest__.py Python version ~~~~~~~~~~~~~~ Odoo version from 6.1 to 10.0 are tested with python 2.7 From Odoo 11.0, python3 is used. You can test against 3.5, 3.6, 3.7 and 3.8 python versions. Currently, python 3.8 is not yet supported. This is the declaration: :: python: - "3.5" - "3.6" - "3.7" - "3.8" Notice: python 3.5 support is ended on 2020 and 3,6 is ended on 2021. Python 3.8 is no yet full supported by Odoo (2021), so use python 3.7 Deployment and setup environment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to deploy test environment and setup code you have to declare some .travis.yml directives divides in following 3 parts: * Linux packages needed * PYPI packages * Odoo repositories dependencies Linux packages must be declared in `<addons/apt>` section of .travis.yml using Ubuntu namespace. If you run test in local environment, travis emulator automatically translate Ubuntu names into your local distro names, if necessary. See `travis emulator <https://github.com/zeroincombenze/tools/tree/master/travis_emulator>`_ guide for furthermore info. The PYPI packages, installable by PIP are declared in standard PIP way, using **requirements.txt** file. If your project depends on other Odoo Github repositories like OCA, create a file called **oca_dependencies.txt** at the root of your project and list the dependencies there. One per line like so: project_name optional_repository_url optional_branch_name During testbed setup, z0bug_odoo will automatically download and place these repositories accordingly into the addon path. Note on addons path ordering: they will be placed after your own repo, but before the odoo core repo. If missed optional_repository_url, the repository is searched for repository with the same owner of tested project. Please note this behaviour differs from OCA MQT. OCA MQT always loads OCA repository while z0bug_odoo searches for current owner repository. So you will test both with z0bug_ood and both OCA MQT, always insert the full repository URL. Test execution ~~~~~~~~~~~~~~ Tests run by travis_run_test command. The script is deployed in _travis directory of **zerobug** package. Command have to be in `<script>` section of .travis.yml file: :: script: - travis_run_tests Isolated pylint+flake8 checks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you want to make a build for these checks, you can add a line on the `<env>` section of the .travis.yml file with this content: :: - VERSION="12.0" LINT_CHECK="1" To avoid making again these checks on other builds, you have to add LINT_CHECK="0" variable on the line: :: - VERSION="12.0" ODOO_REPO="odoo/odoo" LINT_CHECK="0" You can superset above options in local travis emulator. Reduced set of lint check ~~~~~~~~~~~~~~~~~~~~~~~~~ You can execute reduced set of check, in order to gradually evolve your code quality when you meet too many errors. To enable reduced set of check add one of follow lines: :: - LINT_CHECK="1" LINT_CHECK_LEVEL="MINIMAL" - LINT_CHECK="1" LINT_CHECK_LEVEL="REDUCED" - LINT_CHECK="1" LINT_CHECK_LEVEL="AVERAGE" - LINT_CHECK="1" LINT_CHECK_LEVEL="NEARBY" - LINT_CHECK="1" LINT_CHECK_LEVEL="OCA" Odoo core has internal pylint test that checks for all modules even the dependecies. So if some dependecies module does not meet this test, then the full travis test fails without testing the target repository. Please, add test_lint to EXCLUDE variable to avoid this fail-over. See below for furthermore informations. Look at follow table to understand which tests are disabled at specific level: FLAKE8 (see http://flake8.pycqa.org/en/latest/user/error-codes.html for deatils) +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | Test | MINIMAL | REDUCED | AVERAGE | NEARBY | OCA | Note | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E117 | |no_check| | |no_check| | | | |no_check| | over-indented | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E121 | |no_check| | |no_check| | | | |no_check| | `continuation line under-indented for hanging indent <https://lintlyci.github.io/Flake8Rules/rules/E121.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E123 | |no_check| | |no_check| | | | |no_check| | `Closing bracket does not match indentation of opening bracket's line <https://lintlyci.github.io/Flake8Rules/rules/E123.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E124 | |no_check| | |no_check| | | | |check| | `Closing bracket does not match visual indentation <https://lintlyci.github.io/Flake8Rules/rules/E124.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E126 | |no_check| | |no_check| | | | |check| | `Continuation line over-indented for hanging indent <https://lintlyci.github.io/Flake8Rules/rules/E126.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E127 | |no_check| | |no_check| | | | |check| | `continuation line over-indented for visual indent <https://lintlyci.github.io/Flake8Rules/rules/E127.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E128 | |no_check| | |no_check| | | | |check| | `Continuation line under-indented for visual indent <https://lintlyci.github.io/Flake8Rules/rules/E128.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E131 | |no_check| | |no_check| | | | |no_check| | `continuation line unaligned for hanging indent <https://lintlyci.github.io/Flake8Rules/rules/E131.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E133 | |no_check| | |no_check| | | | |no_check| | `Closing bracket is missing indentation <https://lintlyci.github.io/Flake8Rules/rules/E133.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E201 | |no_check| | |check| | | | |check| | `Whitespace after '(' <https://lintlyci.github.io/Flake8Rules/rules/E201.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E202 | |no_check| | |check| | | | |check| | `Whitespace before ')' <https://lintlyci.github.io/Flake8Rules/rules/E202.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E203 | |no_check| | |check| | | | |check| | `Whitespace before ':' <https://lintlyci.github.io/Flake8Rules/rules/E203.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E211 | |no_check| | |check| | | | |check| | `whitespace before '(' <https://lintlyci.github.io/Flake8Rules/rules/E211.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E221 | |no_check| | |check| | | | |check| | `Multiple spaces before operator <https://lintlyci.github.io/Flake8Rules/rules/E221.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E222 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E225 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E226 | |no_check| | |no_check| | | | |no_check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E231 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E241 | |no_check| | |no_check| | | | |no_check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E242 | |no_check| | |no_check| | | | |no_check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E251 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E261 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E262 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E265 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E266 | |no_check| | |no_check| | | | |check| | `too many leading '#' for block comment <https://lintlyci.github.io/Flake8Rules/rules/E266.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E271 | |no_check| | |no_check| | | | |check| | `multiple spaces after keyword <https://lintlyci.github.io/Flake8Rules/rules/E271.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E272 | |no_check| | |no_check| | | | |check| | `multiple spaces before keyword <https://lintlyci.github.io/Flake8Rules/rules/E272.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | W291 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | W292 | |no_check| | |no_check| | | | |check| | `no newline at end of file <https://lintlyci.github.io/Flake8Rules/rules/W292.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | W293 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E301 | |no_check| | |no_check| | | | |check| | `Expected 1 blank line <https://lintlyci.github.io/Flake8Rules/rules/E301.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E302 | |no_check| | |no_check| | | | |check| | No __init__.py | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E303 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E305 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | W391 | |no_check| | |no_check| | | | |check| | blank line at end of file | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | F401 | |no_check| | |check| | | | |no_check| | module imported but unused | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E501 | |no_check| | |no_check| | | | |check| | | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E502 | |no_check| | |no_check| | | | |check| | `the backslash is redundant between brackets <https://lintlyci.github.io/Flake8Rules/rules/E502.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | W503 | |no_check| | |no_check| | | | |no_check| | No __init__.py | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | W504 | |no_check| | |no_check| | | | |no_check| | No __init__.py | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | F601 | |no_check| | |no_check| | | | |no_check| | dictionary key name repeated with different values | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E701 | |no_check| | |no_check| | | | |check| | multiple statements on one line (colon) | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | E722 | |no_check| | |no_check| | | | |check| | do not use bare except | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | F811 | |no_check| | |no_check| | | | |no_check| | redefinition of unused name from line N (No __init__.py) | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ | F841 | |no_check| | |no_check| | | | |no_check| | `local variable 'context' is assigned to but never used <https://lintlyci.github.io/Flake8Rules/rules/F841.html>`_ | +------+------------+------------+---------+--------+------------+----------------------------------------------------------------------------------------------------------------------------------+ PYLINT (see http://pylint-messages.wikidot.com/all-codes for details) +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | Test | MINIMAL | REDUCED | AVERAGE | NEARBY | OCA | Notes | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W0101 | |no_check| | |no_check| | | | |check| | `unreachable <http://pylint-messages.wikidot.com/messages:w0101>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W0312 | |no_check| | |check| | | | |check| | `wrong-tabs-instead-of-spaces <http://pylint-messages.wikidot.com/messages:w0312>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W0403 | |no_check| | |no_check| | | | |check| | relative-import | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W1401 | |no_check| | |check| | | | |check| | anomalous-backslash-in-string | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | E7901 | |no_check| | |no_check| | | | |check| | `rst-syntax-error <https://pypi.org/project/pylint-odoo/1.4.0>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | C7902 | |no_check| | |check| | | | |check| | missing-readme | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7903 | |no_check| | |no_check| | | | |check| | javascript-lint | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7908 | |no_check| | |no_check| | | | |check| | missing-newline-extrafiles | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7909 | |no_check| | |no_check| | | | |check| | redundant-modulename-xml | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7910 | |no_check| | |check| | | | |check| | wrong-tabs-instead-of-spaces | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7930 | |no_check| | |no_check| | | | |check| | `file-not-used <https://pypi.org/project/pylint-odoo/1.4.0>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7935 | |no_check| | |no_check| | | | |check| | missing-import-error | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7940 | |no_check| | |no_check| | | | |check| | dangerous-view-replace-wo-priority | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W7950 | |no_check| | |no_check| | | | |check| | odoo-addons-relative-import | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | E8102 | |no_check| | |check| | | | |check| | invalid-commit | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | C8103 | |no_check| | |check| | | | |check| | `manifest-deprecated-key <https://pypi.org/project/pylint-odoo/1.4.0>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W8103 | |no_check| | |no_check| | | | |check| | translation-field | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | C8104 | |no_check| | |no_check| | | | |check| | `class-camelcase <https://pypi.org/project/pylint-odoo/1.4.0>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W8104 | |no_check| | |no_check| | | | |check| | api-one-deprecated | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | C8105 | |no_check| | |check| | | | |check| | `license-allowed <https://pypi.org/project/pylint-odoo/1.4.0>`_ | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | C8108 | |no_check| | |no_check| | | | |check| | method-compute | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | R8110 | |no_check| | |check| | | | |check| | old-api7-method-defined | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | W8202 | |no_check| | |check| | | | |check| | use-vim-comment | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |check| | | | |check| | sql-injection | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |check| | | | |check| | duplicate-id-csv | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |no_check| | | | |check| | create-user-wo-reset-password | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |no_check| | | | |check| | dangerous-view-replace-wo-priority | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |no_check| | | | |check| | translation-required | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |check| | | | |check| | duplicate-xml-record-id | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |no_check| | | | |check| | no-utf8-coding-comment | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |check| | | | |check| | attribute-deprecated | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ | N/A | |no_check| | |no_check| | | | |check| | consider-merging-classes-inherited | +-------+------------+------------+---------+--------+---------+-------------------------------------------------------------------------------------+ Disable some pylint and/or flake8 checks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can disable some specific test or some file from lint checks. To disable flake8 checks on specific file you can add following line at the beginning of python file: :: # flake8: noqa To disable pylint checks on specific file you can add following line at the beginning of python file: :: # pylint: skip-file To disable both flake8 and pylint checks on specific file you can add following line at the beginning of python file: :: # flake8: noqa - pylint: skip-file To disable pylint checks on specific XML file you can add following line in XML file after xml declaration: :: <!-- pylint:disable=deprecated-data-xml-node --> You can disable specific flake8 check in some source part of python file adding a comment at the same statement to disable check. Here an example to disable sql error (notice comment must be at beginning of the statement): :: from builtins import * # noqa: F403 If you have to disable more than one error you can add following declaration: :: from builtins import * # noqa You can also disable specific pylint check in some source part of python file adding a comment at the same statement to disable check. Here an example to disable sql error (notice comment must be at beginning of the statement): :: self._cr.execute() # pylint: disable=E8103 Disable unit test ~~~~~~~~~~~~~~~~~ If you want to make a build without tests, you can use the following directive: `TEST_ENABLE="0"` You will simply get the databases with packages installed, but without running any tests. Reduced set of unit test ~~~~~~~~~~~~~~~~~~~~~~~~ Odoo modules may fail in Travis CI or in local environment. Currently Odoo OCB core tests fail; we are investigating for the causes. However you can use a simple workaround, disabling some test. Currently tests fail are: * test_impex * test_ir_actions * test_lint * test_main_flows * test_search * test_user_has_group Example: :: - export EXCLUDE=test_impex,test_ir_actions,test_lint,test_main_flows,test_search,test_user_has_group - TESTS="1" ODOO_TEST_SELECT="ALL" - TESTS="1" ODOO_TEST_SELECT="NO-CORE" - .... You can set parameter local GBL_EXCLUDE to disable these test for all repositories. You will be warned that local GBL_EXCLUDE has only effect for local emulation. To avoid these test on web travis-ci you have to set EXCLUDE value in .travis.yml file. Look at follow table to understand which set of tests are enabled or disabled: +-----------------+-------------+---------------+-------------+---------------------+ | statement | application | module l10n_* | odoo/addons | addons + dependenci | +-----------------+-------------+---------------+-------------+---------------------+ | ALL | |check| | |check| | |check| | |check| | +-----------------+-------------+---------------+-------------+---------------------+ | APPLICATIONS | |check| | |no_check| | |no_check| | Only if application | +-----------------+-------------+---------------+-------------+---------------------+ | LOCALIZATION | |no_check| | |check| | |no_check| | Only module l10n_* | +-----------------+-------------+---------------+-------------+---------------------+ | CORE | |no_check| | |no_check| | |check| | |no_check| | +-----------------+-------------+---------------+-------------+---------------------+ | NO-APPLICATION | |no_check| | |check| | |check| | No if application | +-----------------+-------------+---------------+-------------+---------------------+ | NO-LOCALIZATION | |check| | |no_check| | |check| | No if module l10n_* | +-----------------+-------------+---------------+-------------+---------------------+ | NO-CORE | |check| | |check| | |no_check| | |check| | +-----------------+-------------+---------------+-------------+---------------------+ Dependencies test ~~~~~~~~~~~~~~~~~ Since late Summer 2021, z0bug_odoo checks for dependencies. This test is a sub test of unit test. This is the directive: :: - TESTS="1" TEST_DEPENDENCIES="1" Module unit tests ~~~~~~~~~~~~~~~~~ z0bug_odoo is also capable to test each module individually. The intention is to check if all dependencies are correctly defined. Activate it through the `UNIT_TEST` directive. An additional line should be added to the `env:` section, similar to this one: :: - VERSION="12.0" UNIT_TEST="1" Automatic module translation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Since late Summer 2021, z0bug_odoo activate automatic module translation after test ended with success. This is the directive: :: - VERSION="12.0" ODOO_TNLBOT="1" This feature is still experimental. Names used for the test databases ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ z0bug_odoo has a nice feature of organizing your testing databases. You might want to do that if you want to double them up as staging DBs or if you want to work with an advanced set of templates in order to speed up your CI pipeline. Just specify at will: `MQT_TEMPLATE_DB='odoo_template' MQT_TEST_DB='odoo_test'`. In your local travis you can declare the default value but these values are not applied in web TravisCi web site. Database user is the current username. This behavior works both in local test both in TravisCi web site. However, sometimes, local user and db username can be different. You can set the default value in travis emulator. Coveralls/Codecov configuration file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `Coveralls <https://coveralls.io/>`_ and `Codecov <https://codecov.io/>`_ services provide information on the test coverage of your modules. Currently both configurations are automatic (check default configuration `here <cfg/.coveragerc>`_. So, as of today, you don't need to include a `.coveragerc` into the repository, If you do it, it will be simply ignored. Other configurations ~~~~~~~~~~~~~~~~~~~~ You can highly customize you test: look at below table. +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | variable | default value | meaning | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | CHROME_TEST | | Set value to 1 to use chrome client to test | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | DATA_DIR | ~/data_dir | Odoo data directory (data_dir in config file) | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | EXCLUDE | | Modules to exclude from test | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | INCLUDE | | Modules to test (all | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | INSTALL_OPTIONS | | Options passed to odoo-bin/openerp-server to install modules | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | MQT_DBSUER | $USER | Database username | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | MQT_TEMPLATE_DB | template_odoo | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | MQT_TEST_DB | test_odoo | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | NPM_CONFIG_PREFIX | \$HOME/.npm-global | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | ODOO_COMMIT_TEST | 0 | Test result will be committed; require specific code at tear_off function | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | ODOO_REPO | odoo/odoo | OCB repository against test repository | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | ODOO_SETUPS | __manifest__.py __openerp__.py __odoo__.py __terp__.py | Names of Odoo manifest files | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | ODOO_TEST_SELECT | ALL | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | ODOO_TNLBOT | 0 | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | OPTIONS | | Options passed to odoo-bin/openerp-server to execute tests | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PHANTOMJS_VERSION | | Version of PhantomJS | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PS_TXT_COLOR | 0;97;40 | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PS_RUN_COLOR | 1;37;44 | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PS_NOP_COLOR | 34;107 | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PS_HDR1_COLOR | 97;42 | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PS_HDR2_COLOR | 30;43 | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PS_HDR3_COLOR | 30;45 | N/D | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | PYPI_RUN_PYVER | (2.7|3.5|3.6|3.7|3.8) | python versions to run (only PYPI projects) | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | SERVER_EXPECTED_ERRORS | | # of expected errors after tests | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | TEST_DEPENDENCIES | 0 | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | TRAVIS_DEBUG_MODE | 0 | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | TRAVIS_PDB | | The value 'true' activates pdb in local 'travis -B' | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | UNBUFFER | 1 | Use unbuffer (colors) to log results | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | UNIT_TEST | | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | TEST | | Read above | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | VERSION | | Odoo version to test (see above) | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | WEBSITE_REPO | | Load package for website tests | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ | WKHTMLTOPDF_VERSION | 0.12.5 | Version of wkhtmltopdf (value are 0.12.1 | +------------------------+--------------------------------------------------------+---------------------------------------------------------------------------+ Debug information ~~~~~~~~~~~~~~~~~ If you declare the following directive in <env global> section: `TRAVIS_DEBUG_MODE="n"` where "n" means: +------------------------+------------+------------+------------+---------+-------------+ | Parameter | 0 | 1 | 2 | 3 | 9 | +------------------------+------------+------------+------------+---------+-------------+ | Informative messages | |no_check| | |check| | |check| | |check| | |check| | +------------------------+------------+------------+------------+---------+-------------+ | Inspect internal data | |no_check| | |no_check| | |check| | |check| | |check| | +------------------------+------------+------------+------------+---------+-------------+ | MQT tests | |no_check| | |no_check| | |no_check| | |check| | |check| | +------------------------+------------+------------+------------+---------+-------------+ | Installation log level | ERROR | WARN | INFO | INFO | |no_check| | +------------------------+------------+------------+------------+---------+-------------+ | Execution log level | INFO | TEST | TEST | TEST | |no_check| | +------------------------+------------+------------+------------+---------+-------------+ Note this feature does not work with OCA MQT. Local test and TravisCI test have slightly different behavior. When MQT is execute in local environment the value `TRAVIS_DEBUG_MODE="9"` does not execute unit test. It is used to debug MQT itself. See `local travis emulator <https://github.com/zeroincombenze/tools/tree/master/travis_emulator>`_ Tree directory ~~~~~~~~~~~~~~ While travis is running this is the tree directory: :: ${HOME} # home of virtual environment (by TravisCI) ┣━━ build # build root (by TravisCI) ┃ ┣━━ ${TRAVIS_BUILD_DIR} # testing repository (by TravisCI) ┃ ┗━━ ${ODOO_REPO} # odoo or OCB repository to check with (0) (1) (2) ┃ ┣━━ ${ODOO_REPO}-${VERSION} # symlink of ${HOME}/build/{ODOO_REPO} (0) (1) ┃ ┣━━ dependencies # Odoo dependencies of repository (0) (3) ┃ ┣━━ tools # clone of Zeroincombenze tools (3) (4) ┃ ┃ ┃ ┣━━ zerobug # z0bug testing library ┃ ┃ ┗━━ _travis # testing commands ┃ ┗━━ z0bug_odoo # Odoo testing library ┃ ┗━━ travis # testing commands ┃ ┗━━ maintainer-quality-tools # OCA testing library ┗━━ travis # testing commands (0) Same behavior of OCA MQT (1) Cloned odoo/odoo or OCA/OCB repository to check compatibility of testing modules (2) If the testing project is OCB, travis_install_env ignore this directory (3) Done by then following statements in .travis.yml: - travis_install_env Above statements replace the OCA statements: - travis_install_nightly (4) Done by following statements in .travis.yml:: - git clone https://github.com/zeroincombenze/tools.git ${HOME}/tools --depth=1 - \${HOME}/tools/install_tools.sh -qpt - source ${HOME}/devel/activate_tools -t Above statements replace OCA following statements: - git clone https://github.com/OCA/maintainer-quality-tools.git ${HOME}/maintainer-quality-tools --depth=1 - export PATH=${HOME}/maintainer-quality-tools/travis:${PATH} TestEnv: the test environment ----------------------------- TestEnv makes available a test environment ready to use in order to test your Odoo module in quick and easy way. The purpose of this software are: * Create the Odoo test environment with records to use for your test * Make available some useful functions to test your module (in z0bug_odoo) * Simulate the wizard to test wizard functions (wizard simulator) * Environment running different Odoo modules versions Please, pay attention to test data: TestEnv use internal unicode even for python 2 based Odoo (i.e. 10.0). You should declare unicode date whenever is possible. Note, Odoo core uses unicode even on old Odoo version. Tests are based on test environment created by module mk_test_env in repository https://github.com/zeroincombenze/zerobug-test Requirements ~~~~~~~~~~~~ Ths TestEnv software requires: * python_plus PYPI package * z0bug_odoo PYPI package * python 2.7 / 3.6 / 3.7 / 3.8 TestEnv is full integrated with Zeroincombenze(R) tools. See https://zeroincombenze-tools.readthedocs.io/ and https://github.com/zeroincombenze/tools.git Zeroincombenze(R) tools help you to test Odoo module with pycharm. | Features -------- Data to use in tests are store in csv files in data directory. File names are tha name of the models (table) with characters '.' (dot) replaced by '_' (underscore) Header of file must be the names of table fields. Rows can contains value to store or Odoo external reference or macro. For type char, text, html, int, float, monetary: value are constants inserted as is. For type many2one: value may be an integer (record id) or Odoo external reference (format "module.name"). For type data, datetime: value may be a constant or relative date | Usage ===== Copy the testenv.py file in tests directory of your module. You can locate testenv.py in testenv directory of this module (z0bug_odoo) Please copy the documentation testenv.rst file in your module too. The __init__.py must import testenv. Your python test file have to contain some following example lines: :: import os import logging from .testenv import MainTest as SingleTransactionCase _logger = logging.getLogger(__name__) TEST_RES_PARTNER = {...} TEST_SETUP_LIST = ["res.partner", ] class MyTest(SingleTransactionCase): def setUp(self): super().setUp() # Add following statement just for get debug information self.debug_level = 2 data = {"TEST_SETUP_LIST": TEST_SETUP_LIST} for resource in TEST_SETUP_LIST: item = "TEST_%s" % resource.upper().replace(".", "_") data[item] = globals()[item] self.declare_all_data(data) # TestEnv swallows the data self.setup_env() # Create test environment def tearDown(self): super().tearDown() if os.environ.get("ODOO_COMMIT_TEST", ""): # Save test environment, so it is available to dump self.env.cr.commit() # pylint: disable=invalid-commit _logger.info("✨ Test data committed") def test_mytest(self): _logger.info( "🎺 Testing test_mytest" # Use unicode char to best log reading ) ... def test_mywizard(self): self.wizard(...) # Test requires wizard simulator An important helper to debug is self.debug_level. When you begins your test cycle, you are hinted to set self.debug_level = 3; then you can decrease the debug level when you are developing stable tests. Final code should have self.debug_level = 0. TestEnv logs debug message with symbol "🐞 " so you can easily recognize them. Ths TestEnv software requires: * python_plus PYPI package * z0bug_odoo PYPI package * python 2.7 / 3.6 / 3.7 / 3.8 Model data declaration ---------------------- Each model is declared in a dictionary which key which is the external reference used to retrieve the record. i.e. the following record is named 'z0bug.partner1' in res.partner: :: TEST_RES_PARTNER = { "z0bug.partner1": { "name": "Alpha", "street": "1, First Avenue", ... } ) Please, do not to declare 'product.product' records: they are automatically created as child of 'product.template'. The external reference must contain the pattern '_template' (see below). Magic relationship ~~~~~~~~~~~~~~~~~~ Some models/tables should be managed together, i.e. 'account.move' and 'account.move.line'. TestEnv manages these models/tables, called header/detail, just as a single object. Where header record is created, all detail lines are created with header. To do this job you must declare external reference as explained below (external reference). Warning: you must declare header and lines data before create header record. :: TEST_SALE_ORDER = { "z0bug.order_1": { ... } } TEST_SALE_ORDER_LINE = { "z0bug.order_1_1": { ... } } TEST_SETUP_LIST = ["sale.order", "sale.order.line"] class MyTest(SingleTransactionCase): def test_something(self): data = {"TEST_SETUP_LIST": TEST_SETUP_LIST} for resource in TEST_SETUP_LIST: item = "TEST_%s" % resource.upper().replace(".", "_") data[item] = globals()[item] # Declare order data in specific group to isolate data self.declare_all_data(data, group="order") # Create the full sale order with lines self.resource_make(model, xref, group="order") Another magic relationship is the 'product.template' (product) / 'product.product' (variant) relationship. Whenever a 'product.template' (product) record is created, Odoo automatically creates one variant (child) record for 'product.product'. If your test module does not need to manage product variants you can avoid to declare 'product.product' data even if this model is used in your test data. For example, you have to test 'sale.order.line' which refers to 'product.product'. You simply declare a 'product.template' record with external reference uses "_template" magic text. :: TEST_PRODUCT_TEMPLATE = { "z0bug.product_template_1": { "name": "Product alpha", ... } ) ... TEST_SALE_ORDER_LINE = { "z0bug.order_1_1": { "product_id": "z0bug.product_product_1", ... } ) ... # Get 'product.template' record self.resource_bind("z0bug.product_template_1") # Get 'product.product' record self.resource_bind("z0bug.product_product_1") External reference ~~~~~~~~~~~~~~~~~~ Every record is tagged by an external reference. The external reference may be: * Ordinary Odoo external reference (a), format "module.name" * Test reference, format "z0bug.name" (b) * Key value, format "external.key" (c) * 2 keys reference, for header/detail relationship (d) * Magic reference for 'product.template' / 'product.product' (e) Ordinary Odoo external reference (a) is a record of 'ir.model.data'; you can see them from Odoo GUI interface. Test reference (b) are visible just in the test environment. They are identified by "z0bug." prefix module name. External key reference (c) is identified by "external." prefix followed by the key value used to retrieve the record. If key value is an integer it is the record "id". The field "code" or "name" are used to search record; for account.tax the "description" field is used. Please set self.debug_level = 2 (or more) to log these field keys. The 2 keys reference (d) needs to address child record inside header record at 2 level model (header/detail) relationship. The key MUST BE the same key of the parent record, plus "_", plus line identifier (usually 'sequence' field). i.e. "z0bug.move_1_3" means: line with sequence 3 of 'account.move.line' which is child of record "z0bug.move_1" of 'account.move'. Please set self.debug_level = 2 (or more) to log these relationships. For 'product.template' (product) you must use '_template' text in reference (e). TestEnv inherit 'product.product' (variant) external reference (read above 'Magic relationship). Examples: :: TEST_ACCOUNT_ACCOUNT = { "z0bug.customer_account": { "code": "", ... } "z0bug.supplier_account": { "code": "111100", ... } ) ... self.resource_edit( partner, web_changes = [ ("country_id", "base.it"), # Odoo external reference (type a) ("property_account_receivable_id", "z0bug.customer_account"), # Test reference (type b) ("property_account_payable_id", "external.111100"), # External key (type c) ], ) Module test execution session ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Module test execution workflow should be: #. Data declaration, in setUp() function #. Base data creation, in setUp() function #. Supplemental data declaration #. Supplemental data creation Test data may be managed by one or more data group; if not declared, "base" group name is used. The "base" group must be created at the setUp() level: it is the base test data. Testing function may declare and manage other group data. Look at the following example: :: import os import logging from .testenv import MainTest as SingleTransactionCase _logger = logging.getLogger(__name__) TEST_PRODUCT_TEMPLATE = { "z0bug.product_template_1": {...} } TEST_RES_PARTNER = { "z0bug.partner1": {...} ) TEST_SETUP_LIST = ["res.partner", "product.template"] TEST_SALE_ORDER = { "z0bug.order_1": { "partner_id": "z0bug.partner1", ... } } TEST_SALE_ORDER_LINE = { "z0bug.order_1_1": { "product_id": "z0bug.product_product_1", ... } ) class MyTest(SingleTransactionCase): def setUp(self): super().setUp() # Add following statement just for get debug information self.debug_level = 2 data = {"TEST_SETUP_LIST": TEST_SETUP_LIST} for resource in TEST_SETUP_LIST: item = "TEST_%s" % resource.upper().replace(".", "_") data[item] = globals()[item] self.declare_all_data(data) # TestEnv swallows the data self.setup_env() # Create test environment def test_something(self): data = {"TEST_SETUP_LIST": ["sale.order", "sale.order.line"]} for resource in TEST_SETUP_LIST: item = "TEST_%s" % resource.upper().replace(".", "_") data[item] = globals()[item] # Declare order data in specific group to isolate data self.declare_all_data(data, group="order") # Create the full sale order with lines self.setup_env(group="order") Note the external reference are globals and they are visible from any groups. After base data is created it starts the real test session. You can simulate various situation; the most common are: #. Simulate web form create record #. Simulate web form update record #. Simulate the multi-record windows action #. Download any binary data created by test #. Engage wizard Notice: you can also create / update record with usually create() / write() Odoo function but they do not really simulate the user behavior. They do not engage the onchange methods, they do not load any view and so on. The real best way to test a create session is like the follow example based on res,partner model: :: record = self.resource_edit( resource="res.partner", web_changes=[ ("name", "Adam"), ("country_id", "base.us"), ... ], ) You can also simulate the update session, issuing the record: :: record = self.resource_edit( resource=record, web_changes=[ ("name", "Adam Prime"), ... ], ) Look at resource_edit() documentation for furthermore details. In you test session you should need to test a wizard. This test is very easy to execute as in the follow example that engage the standard language install wizard: :: # We engage language translation wizard with "it_IT" language # see "<ODOO_PATH>/addons/base/module/wizard/base_language_install*" _logger.info("🎺 Testing wizard.lang_install()") act_windows = self.wizard( module="base", action_name="action_view_base_language_install", default={ "lang": "it_IT" "overwrite": False, }, button_name="lang_install", ) self.assertTrue( self.is_action(act_windows), "No action returned by language install" ) # Now we test the close message self.wizard( act_windows=act_windows ) self.assertTrue( self.env["res.lang"].search([("code", "=", "it_IT")]), "No language %s loaded!" % "it_IT" ) Look at wizard() documentation for furthermore details. Data values ~~~~~~~~~~~ Data values may be raw data (string, number, dates, etc.) or external reference or some macro. You can declare data value on your own but you can discover th full test environment in https://github.com/zeroincombenze/zerobug-test/mk_test_env/ and get data from this environment. company_id ~~~~~~~~~~ If value is empty, user company is used. When data is searched by resource_bind() function the "company_id" field is automatically filled and added to search domain. This behavior is not applied on "res.users", "res.partner","product.template" and "product.product" models. For these models you must fill the "company_id" field. For these models resource_bind() function searches for record with company_id null or equal to current user company. boolean ~~~~~~~ You can declare boolean value: * by python boolean False or True * by integer 0 o 1 * by string "0" / "False" or "1" / "True" :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "supplier": False, "customer": "True", "is_company": 1, } } ) char / text ~~~~~~~~~~~ Char and Text values are python string; please use unicode whenever is possible even when you test Odoo 10.0 or less. :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "name": "Alpha", "street": "1, First Avenue", ... } } ) integer / float / monetary ~~~~~~~~~~~~~~~~~~~~~~~~~~ Integer, Floating and Monetary values are python integer or float. If numeric value is issued as string, it is internally converted as integer/float. :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "color": 1, "credit_limit": 500.0, "payment_token_count": "0", } } ) date / datetime ~~~~~~~~~~~~~~~ Date and Datetime value are managed in special way. They are processed by compute_date() function (read below). You can issue a single value or a 2 values list, 1st is the date, 2nd is the reference date. :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "activity_date_deadline": "####-1>-##", # Next month "signup_expiration": "###>-##-##", # Next year "date": -1, # Yesterday "last_time_entries_checked": [+2, another_date], # 2 days after another day "message_last_post": "2023-06-26", # Specific date } } ) many2one ~~~~~~~~ You can issue an integer (if you exactly know the ID) or an external reference. Read above about external reference. :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "country_id": "base.it", # Odoo external reference "property_account_payable_id": "z0bug.customer_account", # Test record "title": "external.Mister" # Record with name=="Mister" } } ) one2many / many2many ~~~~~~~~~~~~~~~~~~~~ The one2many and many2many field may contains one or more ID; every ID use the many2one notation using external reference. Value may be a string (just 1 value) or a list. :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "bank_ids": [ "base.bank_partner_demo", "base_iban.bank_iban_china_export", ], "category_id": "base.res_partner_category_0", } } ) binary ~~~~~~ Binary file are supplied with os file name. Test environment load file and get binary value. File must be located in ./tests/data directrory. :: self.resource_create( "res.partner", xref="z0bug.partner1", values={ { ... "image": "z0bug.partner1.png" } } ) Functions --------- store_resource_data ~~~~~~~~~~~~~~~~~~~ Store a record data definition for furthermore use. Data stored is used by setup_env() function and/or by: * resource_create() without values * resource_write() without values * resource_make() without values def store_resource_data(self, resource, xref, values, group=None, name=None): :: Args: resource (str): Odoo model name xref (str): external reference values (dict): record data group (str): used to manager group data; default is "base" name (str): label of dataset; default is resource name compute_date ~~~~~~~~~~~~ Compute date or datetime against today or a reference date. Date may be: * python date/datetime value * string with ISO format "YYYY-MM-DD" / "YYYY-MM-DD HH:MM:SS" * string value that is a relative date against today / reference date Relative string format is like ISO, with 3 groups separated by '-' (dash). Every group may be an integer or a special notation: * starting with '<' meas subtract; i.e. '<2' means minus 2 * ending with '>' meas add; i.e. '2>' means plus 2 * '#' with '<' or '>' means 1; i.e. '<###' means minus 1 * all '#' means same value of reference date A special notation '+N' and '-N', where N is an integer means add N days or subtract N day from reference date. Here, in following examples, are used python iso date convention: * '+N': return date + N days to refdate (python timedelta) * '-N': return date - N days from refdate (python timedelta) * '%Y-%m-%d': strftime of issued value * '%Y-%m-%dT%H:%M:%S': same datetime * '%Y-%m-%d %H:%M:%S': same datetime * '####-%m-%d': year from refdate (or today), month '%m', day '%d' * '####-##-%d': year and month from refdate (or today), day '%d' * '2022-##-##': year 2022, month and day from refdate (or today) * '<###-%m-%d': year -1 from refdate (or today), month '%m', day '%d' * '<001-%m-%d': year -1 from refdate (or today), month '%m', day '%d' * '<###-#>-%d': year -1 from refdate, month +1 from refdate, day '%d' * '<005-2>-##': year -5, month +2 and day from refdate Notes: Returns a ISO format string. Returned date is always a valid date; i.e. '####-#>-31', with ref month January result '####-02-31' becomes '####-03-03' To force last day of month, set '99': i.e. '####-<#-99' becomes the last day of previous month of refdate def compute_date(self, date, refdate=None): date (date or string or integer): formula; read aboove refdate (date or string): reference date resource_bind ~~~~~~~~~~~~~ Bind record by xref or searching it or browsing it. This function returns a record using issued parameters. It works in follow ways: * With valid xref it work exactly like self.env.ref() * If xref is an integer it works exactly like self.browse() * I xref is invalid, xref is used to search record * xref is searched in stored data * xref ("MODULE.NAME"): if MODULE == "external", NAME is the record key def resource_bind(self, xref, raise_if_not_found=True, resource=None): :: Args: xref (str): external reference raise_if_not_found (bool): raise exception if xref not found or if more records found resource (str): Odoo model name, i.e. "res.partner" Returns: obj: the Odoo model record Raises: ValueError: if invalid parameters issued resource_create ~~~~~~~~~~~~~~~ Create a test record and set external ID to next tests. This function works as standard Odoo create() with follow improvements: * It can create external reference too * It can use stored data if no values supplied def resource_create(self, resource, values=None, xref=None, group=None): :: Args: resource (str): Odoo model name, i.e. "res.partner" values (dict): record data (default stored data) xref (str): external reference to create group (str): used to manager group data; default is "base" Returns: obj: the Odoo model record, if created resource_write ~~~~~~~~~~~~~~ Update a test record. This function works as standard Odoo write() with follow improvements: * If resource is a record, xref is ignored (it should be None) * It resource is a string, xref must be a valid xref or an integer * If values is not supplied, record is restored to stored data values def resource_write(self, resource, xref=None, values=None, raise_if_not_found=True, group=None): :: Args: resource (str|obj): Odoo model name or record to update xref (str): external reference to update: required id resource is string values (dict): record data (default stored data) raise_if_not_found (bool): raise exception if xref not found or if more records found group (str): used to manager group data; default is "base" Returns: obj: the Odoo model record Raises: ValueError: if invalid parameters issued resource_make ~~~~~~~~~~~~~ Create or write a test record. This function is a hook to resource_write() or resource_create(). def resource_make(self, resource, xref, values=None, group=None): declare_resource_data ~~~~~~~~~~~~~~~~~~~~~ Declare data to load on setup_env(). def declare_resource_data(self, resource, data, name=None, group=None, merge=None) :: Args: resource (str): Odoo model name, i.e. "res.partner" data (dict): record data name (str): label of dataset; default is resource name group (str): used to manager group data; default is "base" merge (str): merge data with public data (currently just "zerobug") Raises: TypeError: if invalid parameters issued declare_all_data ~~~~~~~~~~~~~~~~ Declare all data to load on setup_env(). def declare_resource_data(self, resource, data, name=None, group=None, merge=None) :: Args: message (dict): data message TEST_SETUP_LIST (list): resource list to load TEST_* (dict): resource data; * is the uppercase resource name where dot are replaced by "_"; (see declare_resource_data) group (str): used to manager group data; default is "base" merge (str): merge data with public data (currently just "zerobug") Raises: TypeError: if invalid parameters issuedd get_resource_data ~~~~~~~~~~~~~~~~~ Get declared resource data; may be used to test compare. def get_resource_data(self, resource, xref, group=None): :: Args: resource (str): Odoo model name or name assigned, i.e. "res.partner" xref (str): external reference group (str): if supplied select specific group data; default is "base" Returns: dictionary with data or empty dictionary get_resource_data_list ~~~~~~~~~~~~~~~~~~~~~~ Get declared resource data list. def get_resource_data_list(self, resource, group=None): :: Args: resource (str): Odoo model name or name assigned, i.e. "res.partner" group (str): if supplied select specific group data; default is "base" Returns: list of data get_resource_list ~~~~~~~~~~~~~~~~~ Get declared resource list. def get_resource_list(self, group=None): :: Args: group (str): if supplied select specific group data; default is "base" setup_company ~~~~~~~~~~~~~ Setup company values for current user. This function assigns company to current user and / or can create xref aliases and /or can update company values. This function is useful in multi companies tests where different company values will be used in different tests. May be used in more simple test where company data will be updated in different tests. You can assign partner_xref to company base by group; then all tests executed after setup_env(), use the assigned partner data for company of the group. You can also create more companies and assign one of them to test by group. def setup_company(self, company, xref=None, partner_xref=None, values={}, group=None): :: Args: company (obj): company to update; if not supplied a new company is created xref (str): external reference or alias for main company partner_xref (str): external reference or alias for main company partner values (dict): company data to update immediately group (str): if supplied select specific group data; default is "base" Returns: default company for user setup_env ~~~~~~~~~ Create all record from declared data. This function starts the test workflow creating the test environment. Test data must be declared before engage this function with declare_all_data() function (see above). setup_env may be called more times with different group value. If it is called with the same group, it recreates the test environment with declared values; however this feature might do not work for some reason: i.e. if test creates a paid invoice, the setup_env() cannot unlink invoice. If you want to recreate the same test environment, assure the conditions for unlink of all created and tested records. If you create more test environment with different group you can use all data, even record created by different group. In this way you can test a complex process the evolved scenario. def setup_env(self, lang=None, locale=None, group=None): :: Args: lang (str): install & load specific language locale (str): install locale module with CoA; i.e l10n_it group (str): if supplied select specific group data; default is "base" Returns: None resource_edit ~~~~~~~~~~~~~ Server-side web form editing. Ordinary Odoo test use the primitive create() and write() function to manage test data. These methods create an update records, but they do not properly reflect the behaviour of user editing form with GUI interface. This function simulates the client-side form editing in the server-side. It works in the follow way: * It can simulate the form create record * It can simulate the form update record * It can simulate the user data input * It calls the onchange functions automatically * It may be used to call button in the form User action simulation: The parameter <web_changes> is a list of user actions to execute sequentially. Every element of the list is another list with 2 or 3 values: * Field name to assign value * Value to assign * Optional function to execute (i.e. specific onchange) If field is associate to an onchange function the relative onchange functions are execute after value assignment. If onchange set another field with another onchange the relative another onchange are executed until all onchange are exhausted. This behavior is the same of the form editing. Warning: because function are always executed at the server side the behavior may be slightly different from actual form editing. Please take note of following limitations: * update form cannot simulate discard button * some required data in create must be supplied by default parameter * form inconsistency cannot be detected by this function * nested function must be managed by test code (i.e. wizard from form) See test_testenv module for test examples https://github.com/zeroincombenze/zerobug-test/tree/12.0/test_testenv def resource_edit(self, resource, default={}, web_changes=[], actions=[], ctx={}): :: Args: resource (str or obj): if field is a string simulate create web behavior of Odoo model issued in resource; if field is an obj simulate write web behavior on the issued record default (dict): default value to assign web_changes (list): list of tuples (field, value); see <wiz_edit> Returns: windows action to execute or obj record wizard ~~~~~~ Execute a full wizard. Engage the specific wizard, simulate user actions and return the wizard result, usually a windows action. It is useful to test: * view names * wizard structure * wizard code Both parameters <module> and <action_name> must be issued in order to call <wiz_by_action_name>; they are alternative to act_windows. *** Example of use *** :: XML view file: <record id="action_example" model="ir.actions.act_window"> <field name="name">Example</field> <field name="res_model">wizard.example</field> [...] </record> Python code: :: act_windows = self.wizard(module="module_example", action_name="action_example", ...) if self.is_action(act_windows): act_windows = self.wizard(act_windows=act_windows, ...) User action simulation: The parameter <web_changes> is a list of user actions to execute sequentially. Every element of the list is another list with 2 or 3 values: * Field name to assign value * Value to assign * Optional function to execute (i.e. specific onchange) If field is associate to an onchange function the relative onchange functions are execute after value assignment. If onchange set another field with another onchange the relative another onchange are executed until all onchange are exhausted. This behavior is the same of the form editing. def wizard(self, module=None, action_name=None, act_windows=None, records=None, default=None, ctx={}, button_name=None, web_changes=[], button_ctx={},): :: Args: module (str): module name for wizard to test; if "." use current module name action_name (str): action name act_windows (dict): Odoo windows action (do not issue module & action_name) records (obj): objects required by the download wizard default (dict): default value to assign ctx (dict): context to pass to wizard during execution button_name (str): function name to execute at the end of then wizard web_changes (list): list of tuples (field, value); see above button_ctx (dict): context to pass to button_name function Returns: result of the wizard Raises: ValueError: if invalid parameters issued validate_record ~~~~~~~~~~~~~~~ Validate records against template values. During the test will be necessary to check result record values. This function aim to validate all the important values with one step. You have to issue 2 params: template with expected values and record to check. You can declare just some field value in template which are important for you. Both template and record are lists, record may be a record set too. This function do following steps: * matches templates and record, based on template supplied data * check if all template are matched with 1 record to validate * execute self.assertEqual() for every field in template * check for every template record has matched with assert def validate_records(self, template, records): :: Args: template (list of dict): list of dictionaries with expected values records (list or set): records to validate values Returns: list of matched coupled (template, record) + # of assertions Raises: ValueError: if no enough assertions or one assertion is failed get_records_from_act_windows ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Get records from a windows message. def get_records_from_act_windows(self, act_windows): :: Args: act_windows (dict): Odoo windows action returned by a wizard Returns: records or False Raises: ValueError: if invalid parameters issued | | Getting started =============== For stable version: `pip install z0bug_odoo` For current version: `cd $HOME` `[email protected]:zeroincombenze/tools.git` `cd $HOME/tools` `./install_tools.sh` Upgrade ------- Stable version via Python Package ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: pip install -U | Current version via Git ~~~~~~~~~~~~~~~~~~~~~~~ :: cd $HOME ./install_tools.sh -U source $HOME/devel/activate_tools History ------- 2.0.10 (2023-07-02) ~~~~~~~~~~~~~~~~~~~ * [IMP] TestEnv: new feature, external reference with specific field value * [REF] TestEnv: tomany casting refactoring 2.0.9 (2023-06-24) ~~~~~~~~~~~~~~~~~~ * [FIX] TestEnv: sometimes, validate_records does not match many2one fields * [FIX[ TestEnv: sometime crash in wizard on Odoo 11.0+ due inexistent ir.default * [FIX] TestEnv: default value in wizard creation, overlap default function * [FIX] TestEnv: record not found for xref of other group * [IMP] TestEnv: resource_bind is not more available: it is replaced by resource_browse 2.0.8 (2023-04-26) ~~~~~~~~~~~~~~~~~~ * [FIX] TestEnv: multiple action on the same records 2.0.7 (2023-04-08) ~~~~~~~~~~~~~~~~~~ * [NEW] TestEnv: assertion counter * [IMP] TestEnv: is_xref recognizes dot name, i.e "zobug.external.10" * [IMP] TestEnv: the field <description> is not mode key (only acount.tax) * [IMP] TestEnv: 3th level xref may be a many2one field type 2.0.6 (2023-02-20) ~~~~~~~~~~~~~~~~~~ * [FIX] TestEnv: _get_xref_id recognize any group * [FIX] TestEnv: datetime field more precise (always with time) * [FIX] TestEnv: resource_make / resource_write fall in crash if repeated on headr/detail models * [NEW] TestEnv: 2many fields accepts more xref values * [IMP] TestEnv: debug message with more icons and more readable * [IMP] TestEnv: cast_types with formatting for python objects * [IMP] TestEnv: validate_record now uses intelligent algorithm to match pattern templates and records 2.0.5 (2023-01-25) ~~~~~~~~~~~~~~~~~~ * [FIX] TestEnv: in some rare cases, wizard crashes * [NEW] TestEnv: get_records_from_act_windows() * [IMP] TestEnv: resource_make now capture demo record if available * [IMP] TestEnv: resource is not required for declared xref * [IMP] TestEnv: self.module has all information about current testing module * [IMP] TestEnv: conveyance functions for all fields (currenly jsust for account.payment.line) * [IMP] TestEnv: fields many2one accept object as value * [IMP] TestEnv: function validate_records() improvements * [FIX] TestEnv: company_setup, now you can declare bank account * [IMP] TesEnv: minor improvements 2.0.4 (2023-01-13) ~~~~~~~~~~~~~~~~~~ * [FIX] TestEnv: resource_create does not duplicate record * [FIX] TestEnv: resource_write after save calls write() exactly like Odoo behavior * [NEW] TestEnv: new function field_download() * [NEW] TestEnv: new function validate_records() * [IMP] TestEnv: convert_to_write convert binary fields too * [IMP] TestEnv: minor improvements 2.0.3 (2022-12-29) ~~~~~~~~~~~~~~~~~~ * [IMP] TestEnv: more debug messages * [IMP] TestEnv: more improvements * [FIX] TestEnv: sometime crashes if default use context * [FIX] TestEnv: bug fixes 2.0.2 (2022-12-09) ~~~~~~~~~~~~~~~~~~ * [FIX] Automatic conversion of integer into string for 'char' fields * [IMP] TestEnv 2.0.1.1 (2022-11-03) ~~~~~~~~~~~~~~~~~~~~ * [REF] clone_oca_dependencies.py 2.0.1 (2022-10-20) ~~~~~~~~~~~~~~~~~~ * [IMP] Stable version 2.0.0.1 (2022-10-15) ~~~~~~~~~~~~~~~~~~~~ * [FIX] Crash in travis | | Credits ======= Copyright --------- SHS-AV s.r.l. <https://www.shs-av.com/> Contributors ------------ * Antonio M. Vigliotti <[email protected]> * Antonio Maria Vigliotti <[email protected]> | This module is part of project. Last Update / Ultimo aggiornamento: .. |Maturity| image:: https://img.shields.io/badge/maturity-Beta-yellow.png :target: https://odoo-community.org/page/development-status :alt: .. |license gpl| image:: https://img.shields.io/badge/licence-AGPL--3-blue.svg :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html :alt: License: AGPL-3 .. |license opl| image:: https://img.shields.io/badge/licence-OPL-7379c3.svg :target: https://www.odoo.com/documentation/user/9.0/legal/licenses/licenses.html :alt: License: OPL .. |Tech Doc| image:: https://www.zeroincombenze.it/wp-content/uploads/ci-ct/prd/button-docs-2.svg :target: https://wiki.zeroincombenze.org/en/Odoo/2.0/dev :alt: Technical Documentation .. |Help| image:: https://www.zeroincombenze.it/wp-content/uploads/ci-ct/prd/button-help-2.svg :target: https://wiki.zeroincombenze.org/it/Odoo/2.0/man :alt: Technical Documentation .. |Try Me| image:: https://www.zeroincombenze.it/wp-content/uploads/ci-ct/prd/button-try-it-2.svg :target: https://erp2.zeroincombenze.it :alt: Try Me .. |Zeroincombenze| image:: https://avatars0.githubusercontent.com/u/6972555?s=460&v=4 :target: https://www.zeroincombenze.it/ :alt: Zeroincombenze .. |en| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/flags/en_US.png :target: https://www.facebook.com/Zeroincombenze-Software-gestionale-online-249494305219415/ .. |it| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/flags/it_IT.png :target: https://www.facebook.com/Zeroincombenze-Software-gestionale-online-249494305219415/ .. |check| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/check.png .. |no_check| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/no_check.png .. |menu| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/menu.png .. |right_do| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/right_do.png .. |exclamation| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/exclamation.png .. |warning| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/warning.png .. |same| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/same.png .. |late| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/late.png .. |halt| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/halt.png .. |info| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/info.png .. |xml_schema| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/certificates/iso/icons/xml-schema.png :target: https://github.com/zeroincombenze/grymb/blob/master/certificates/iso/scope/xml-schema.md .. |DesktopTelematico| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/certificates/ade/icons/DesktopTelematico.png :target: https://github.com/zeroincombenze/grymb/blob/master/certificates/ade/scope/Desktoptelematico.md .. |FatturaPA| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/certificates/ade/icons/fatturapa.png :target: https://github.com/zeroincombenze/grymb/blob/master/certificates/ade/scope/fatturapa.md .. |chat_with_us| image:: https://www.shs-av.com/wp-content/chat_with_us.gif :target: https://t.me/Assitenza_clienti_powERP
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/README.rst
README.rst
from __future__ import print_function, unicode_literals from past.builtins import long # import sys import base64 import csv import os from openpyxl import load_workbook from python_plus import unicodes __version__ = "2.0.11" class Z0bugOdoo(object): def __init__(self, release=None): try: import odoo.release as release self.release = release except ImportError: try: import openerp.release as release self.release = release except ImportError: self.release = None def get_image_filename(self, xref): file_image = os.path.join(os.path.dirname(__file__), 'data', '%s.png' % xref) if os.path.isfile(file_image): return file_image return False def get_image(self, xref): file_image = self.get_image_filename(xref) if file_image: with open(file_image, 'rb') as fd: image = fd.read() return base64.b64encode(image) return False def save_row(self, model, row): if 'id' in row: for field in row.copy().keys(): if row[field] == r'\N': del row[field] elif row[field] == r'\\N': row[field] = r'\N' if model == "account_account" and isinstance(row["code"], (int, long)): row["code"] = "%s" % row["code"] getattr(self, model)[row['id']] = unicodes(row) def get_data_file_xlsx(self, model, full_fn): pymodel = model.replace('.', '_') wb = load_workbook(full_fn) for sheet in wb: break colnames = [] for column in sheet.columns: colnames.append(column[0].value) hdr = True for line in sheet.rows: if hdr: hdr = False setattr(self, pymodel, {}) continue row = {} for column, cell in enumerate(line): row[colnames[column]] = cell.value self.save_row(pymodel, row) def get_data_file_csv(self, model, full_fn): pymodel = model.replace('.', '_') with open(full_fn, 'r') as fd: hdr = True csv_obj = csv.DictReader(fd, fieldnames=[], restkey='undef_name') for row in csv_obj: if hdr: hdr = False csv_obj.fieldnames = row['undef_name'] setattr(self, pymodel, {}) continue self.save_row(pymodel, row) def get_data_file(self, model, filename): full_fn = os.path.join(os.path.dirname(__file__), 'data', filename) if os.path.isfile('%s.xlsx' % full_fn): return self.get_data_file_xlsx(model, '%s.xlsx' % full_fn) else: return self.get_data_file_csv(model, '%s.csv' % full_fn) def get_test_xrefs(self, model): """Return model xref list""" pymodel = model.replace('.', '_') if not hasattr(self, pymodel): self.get_data_file(model, pymodel) return list(getattr(self, pymodel)) def get_test_values(self, model, xref): """Return model values for test""" xids = xref.split('.') if len(xids) == 1: xids[0], xids[1] = 'z0bug', xids[0] pymodel = model.replace('.', '_') if not hasattr(self, pymodel): self.get_data_file(model, pymodel) if xref not in getattr(self, pymodel): if xids[0] == 'z0bug': raise KeyError('Invalid xref %s for model %s!' % (xref, model)) return {} return getattr(self, pymodel)[xref] def initialize_model(self, model): """Write all record of model with test values""" pymodel = model.replace('.', '_') if not hasattr(self, pymodel): self.get_data_file(model, pymodel) for xref in getattr(self, pymodel): pass
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/z0bug_odoo_lib.py
z0bug_odoo_lib.py
import os import sys import pkg_resources import gzip import shutil __version__ = "2.0.11" def fake_setup(**kwargs): globals()["setup_args"] = kwargs def read_setup(): setup_info = os.path.abspath(os.path.join(os.path.dirname(__file__), "setup.info")) if not os.path.isfile(setup_info): setup_info = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "setup.py") ) setup_args = {} if os.path.isfile(setup_info): with open(setup_info, "r") as fd: exec(fd.read().replace("setup(", "fake_setup(")) setup_args = globals()["setup_args"] else: print("Not internal configuration file found!") setup_args["setup"] = setup_info try: pkg = pkg_resources.get_distribution(__package__.split(".")[0]) setup_args["name"] = pkg.key setup_args["version"] = pkg.version except BaseException: pass return setup_args def get_pypi_paths(): local_venv = "/devel/venv/" pkgpath = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) bin_path = lib_path = "" path = pkgpath while not bin_path and path != "/" and path != os.environ["HOME"]: path = os.path.dirname(path) if os.path.isdir(path) and os.path.basename(path) in ("bin", "lib"): if os.path.isdir( os.path.join(os.path.dirname(path), "bin") ) and os.path.isdir(os.path.join(os.path.dirname(path), "lib")): bin_path = os.path.join(os.path.dirname(path), "bin") lib_path = os.path.join(os.path.dirname(path), "lib") if not bin_path and local_venv: for path in sys.path: if local_venv in path: bin_path = os.path.join( path[: path.find(local_venv)], *[x for x in local_venv.split("/") if x][:-1] ) break return pkgpath, bin_path, lib_path def copy_pkg_data(setup_args, verbose): if setup_args.get("package_data"): pkgpath, bin_path, lib_path = get_pypi_paths() if bin_path: # TODO> compatibility mode bin2_path = os.path.join(os.environ["HOME"], "devel") if not os.path.isdir(bin2_path): bin2_path = "" man_path = os.path.join(bin_path, "man", "man8") if not os.path.isdir(man_path): man_path = "" for pkg in setup_args["package_data"].keys(): for fn in setup_args["package_data"][pkg]: base = os.path.basename(fn) if base in ("setup.info", "*"): continue full_fn = os.path.abspath(os.path.join(pkgpath, fn)) if base.endswith(".man") and man_path: with open(full_fn, "r") as fd: help_text = fd.read() tgt_fn = os.path.join(man_path, "%s.8.gz" % base[:-4]) with gzip.open(tgt_fn, "w") as fd: if sys.version_info[0] == 3: fd.write(help_text.encode("utf-8")) else: fd.write(help_text) if verbose: print("$ gzip -c %s > %s" % (full_fn, tgt_fn)) continue if lib_path: tgt_fn = os.path.join(lib_path, base) if sys.version_info[0] == 3: try: shutil.copy(full_fn, tgt_fn) if verbose: print("$ cp %s %s" % (full_fn, tgt_fn)) except shutil.SameFileError: pass else: try: shutil.copy(full_fn, tgt_fn) if verbose: print("$ cp %s %s" % (full_fn, tgt_fn)) except BaseException: pass # TODO> compatibility mode tgt_fn = os.path.join(bin_path, base) if os.path.isfile(tgt_fn): os.unlink(tgt_fn) if not os.path.exists(tgt_fn): if verbose: print("$ ln -s %s %s" % (full_fn, tgt_fn)) os.symlink(full_fn, tgt_fn) if bin2_path: tgt_fn = os.path.join(bin2_path, base) if os.path.isfile(tgt_fn): os.unlink(tgt_fn) # TODO> compatibility mode to remove early if lib_path and bin2_path: for base in ("z0librc", "odoorc", "travisrc"): full_fn = os.path.join(bin2_path, base) tgt_fn = os.path.join(bin_path, base) if os.path.exists(full_fn) and not os.path.exists(tgt_fn): if verbose: print("$ cp %s %s" % (full_fn, tgt_fn)) shutil.copy(full_fn, tgt_fn) def main(cli_args=None): if not cli_args: cli_args = sys.argv[1:] action = "-H" verbose = False for arg in cli_args: if arg in ("-h", "-H", "--help", "-V", "--version", "--copy-pkg-data"): action = arg elif arg == "-v": verbose = True setup_args = read_setup() if action == "-h": print( "%s [-h][-H][--help][-V][--version][-C][--copy-pkg-data]" % setup_args["name"] ) elif action in ("-V", "--version"): if setup_args["version"] == __version__: print(setup_args["version"]) else: print("Version mismatch %s/%s" % (setup_args["version"], __version__)) elif action in ("-H", "--help"): for text in __doc__.split("\n"): print(text) elif action in ("-C", "--copy-pkg-data"): copy_pkg_data(setup_args, verbose) return 0
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/scripts/main.py
main.py
import os import sys import re import logging from odoo import api, SUPERUSER_ID from odoo.exceptions import UserError _logger = logging.getLogger(__name__) def check_4_depending(cr): """check_4_depending v2.0.11 This function check for valid modules which current module depends on. Usually Odoo checks for depending on through "depends" field in the manifest, but Odoo does not check for the version range neither check for incompatibilities. With three new fields "version_depends", "conflicts" (for odoo modules) and "version_external_dependencies" (for python packages), this function checks for version range, like pip or apt/yum etc. Example: "version_depends": ["dep_module>=12.0.2.0"], "version_external_dependencies": ["Werkzeug>=0.16"], "conflicts": [ "incompatible!", "quite_incompatible", "inv_auth!=~Danger", "req_auth=~?MySelf" ], "pre_init_hook": "check_4_depending", In above example, current module installation fails if: * version of the module named "dep_module" is less than 12.0.2.0 * modules named "incompatible" is installed * module "quite_incompatible" is installed (*) * author name or maintainer name of module "inv_auth" is 'Danger' (**) * author name or maintainer name of module "req_ath" is not 'MySelf' (**) * python package Werkzeug is less than 0.16. Installation can even continue if system parameter "disable_module_incompatibility" is True when: (*) module name to match does not end with symbol "!" (**) regex operators are '=~?' or '!=~?' Summary: - Operators == != >= <= > < match always with module version - Conflicts key 'name' (can disable) or 'name!' (always) match installed module - Operators =~ (always) !=~ (negate+always) =~? (disable) !=~? (negate+disable) match module author o maintainer Notice: __init__.py in current module root must contain the statement: from ._check4deps_ import check_4_depending """ def comp_versions(version): return [ "%05d" % int(x) if x.isdigit() else x for x in version.split(".") ] def display_name(mtype): return "Package" if mtype == "pypi" else "Module" def eval_condition_conflicts(mtype, app, op, disable_check): if app["version"]: uninstallable_reason = ( "Module '%s' conflicts with installed %s '%s'" % ( cur_module, display_name(mtype), app["name"], ) ) if "!" not in op: uninstallable_reason += ( " - Use config param <disable_module_incompatibility> to install!") _logger.error(uninstallable_reason) if not disable_check or "!" in op: return uninstallable_reason return False def eval_regex(mtype, app, op, ver_to_match, disable_check): a = re.search("(?i)" + ver_to_match, app["author"]) m = re.search("(?i)" + ver_to_match, app["maintainer"]) if op.startswith("=~") and ((not a and not m) or not app["version"]): uninstallable_reason = ( "%s '%s' is not installable because author or maintainer of module '%s'" " must match with '%s'" % ( display_name(mtype), cur_module, app["name"], ver_to_match, ) ) if "?" in op: uninstallable_reason += ( " - Use config param <disable_module_incompatibility> to install!") _logger.error(uninstallable_reason) if not disable_check or "?" not in op: return uninstallable_reason elif op.startswith("!=~") and (a or m) and app["version"]: uninstallable_reason = ( "%s '%s' is not installable because found author or maintainer '%s'" " in module '%s'" % ( display_name(mtype), cur_module, ver_to_match, app["name"], ) ) if "?" in op: uninstallable_reason += ( " - Use config param <disable_module_incompatibility> to install!") _logger.error(uninstallable_reason) if not disable_check or "?" not in op: return uninstallable_reason return False def eval_version_match(mtype, app, op, ver_to_match, condition): if not eval("%s%s%s" % (comp_versions(app["version"]), op, comp_versions(ver_to_match))): uninstallable_reason = ( "%s '%s' is not installable because it does not match with '%s%s'" " (is %s)" % ( display_name(mtype), cur_module, app["name"], condition, app["version"], ) ) _logger.error(uninstallable_reason) return uninstallable_reason def eval_condition(mtype, app, condition, disable_check): """evaluate condition and return reason for match""" x = op_re.match(condition) if x: op = condition[x.start(): x.end()] ver_to_match = condition[x.end():] else: op = ver_to_match = "" if op in ("", "!"): return eval_condition_conflicts(mtype, app, op, disable_check) elif op in ("=~", "!=~", "=~?", "!=~?"): return eval_regex(mtype, app, op, ver_to_match, disable_check) elif not app["version"]: uninstallable_reason = "%s '%s' not installed" % ( display_name(mtype), app["name"], ) _logger.error(uninstallable_reason) return uninstallable_reason return eval_version_match(mtype, app, op, ver_to_match, condition) def get_odoo_module_info(app_name): odoo_module = env["ir.module.module"].search([("name", "=", app_name)]) if not odoo_module or odoo_module[0].state != "installed": app = {"name": app_name, "version": False, "author": "", "maintainer": ""} else: app = {"name": app_name, "version": odoo_module[0].installed_version, "author": odoo_module[0].author or "", "maintainer": odoo_module[0].maintainer or ""} return app def get_pypi_info(app_name): if sys.version_info[0] == 2: import pkg_resources try: version = pkg_resources.get_distribution(app_name).version except BaseException: version = False elif sys.version_info < (3, 8): import importlib_metadata as metadata try: version = metadata.version(app_name) except BaseException: version = False else: from importlib import metadata try: version = metadata.version(app_name) except BaseException: version = False return {"name": app_name, "version": version} def check_for_all_dependecies(dependecies_list, mtype="odoo", disable_check=False): if not isinstance(dependecies_list, (list, tuple)): dependecies_list = [dependecies_list] uninstallable_reason = "" for pkg_with_ver in dependecies_list: x = item_re.match(pkg_with_ver) if not x and mtype == "conflicts": app_name = pkg_with_ver conditions = [] else: ix = x.end() app_name = pkg_with_ver[x.start(): ix] conditions = pkg_with_ver[ix:].split(",") if mtype in ("odoo", "conflicts"): app = get_odoo_module_info(app_name) elif mtype == "pypi": app = get_pypi_info(app_name) else: raise UserError("Unknown depend on type %s" % mtype) for condition in conditions: uninstallable_reason = eval_condition( mtype, app, condition, disable_check) if uninstallable_reason: break if uninstallable_reason: break if uninstallable_reason: raise UserError(uninstallable_reason) env = api.Environment(cr, SUPERUSER_ID, {}) path = __file__ while path != "/": path = os.path.dirname(path) manifest_path = os.path.join(path, "__manifest__.py") if os.path.isfile(manifest_path): break manifest_path = os.path.join(path, "__openerp__.py") if os.path.isfile(manifest_path): break try: manifest = eval(open(manifest_path, "r").read()) except (ImportError, IOError, SyntaxError): manifest = {} cur_module = os.path.basename(os.path.dirname(manifest_path)) disable_check = env["ir.config_parameter"].search( [("key", "=", "disable_module_incompatibility")] ) disable_check = disable_check and eval(disable_check[0].value) or False item_re = re.compile("[^>=<~!?]+") op_re = re.compile("[>=<~!?]+") check_for_all_dependecies( manifest.get("version_external_dependencies", []), mtype="pypi", disable_check=disable_check ) check_for_all_dependecies( manifest.get("version_depends", []), mtype="odoo", disable_check=disable_check ) check_for_all_dependecies( manifest.get("conflicts", []), mtype="conflicts", disable_check=disable_check )
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/testenv/_check4deps_.py
_check4deps_.py
from __future__ import print_function import ast import os # import re import sys import inspect import click import pylint.lint try: import travis_helpers except ImportError: from . import travis_helpers try: from getaddons import get_modules_changed, is_module except ImportError: from .getaddons import get_modules_changed, is_module try: from git_run import GitRun except ImportError: from .git_run import GitRun try: import ConfigParser except ImportError: import configparser as ConfigParser CLICK_DIR = click.Path(exists=True, dir_okay=True, resolve_path=True) def get_extra_params(odoo_version): """Get extra pylint params by odoo version Transform a pseudo-pylint-conf to params, to overwrite base-pylint-conf values. Use a seudo-inherit of configuration file. To avoid having 2 config files (stable and pr-conf) by each odoo-version Example: pylint_master.conf pylint_master_pr.conf pylint_90.conf pylint_90_pr.conf pylint_80.conf pylint_80_pr.conf pylint_70.conf pylint_70_pr.conf pylint_61.conf pylint_61_pr.conf ... and new future versions. If you need to add new conventions in all versions, you will need to change all pr files or stable files. With this method you can use: pylint_lastest.conf pylint_lastest_pr.conf pylint_disabling_70.conf <- Overwrite params of pylint_lastest*.conf pylint_disabling_61.conf <- Overwrite params of pylint_lastest*.conf If you need to add new conventions in all versions, you will only need to change pylint_lastest_pr.conf or pylint_lastest.conf, similar to inherit. :param version: String to specify an Odoo's name or versio :return: List of extra pylint params """ # is_version_number = re.match(r'\d+\.\d+', odoo_version) # beta_msgs = get_beta_msgs() leverage_msgs = get_leverage_msgs() versioned_msgs = get_versioned_msgs(odoo_version) extra_params_cmd = [ '--sys-paths', os.path.join( os.path.dirname(os.path.realpath(__file__)), 'pylint_deprecated_modules' ), # '--extra-params', # '--load-plugins=pylint_odoo', ] extra_params = list(extra_params_cmd) # if is_version_number: # extra_params.extend( # ['--extra-params', '--valid_odoo_versions=%s' % odoo_version] # ) # for beta_msg in beta_msgs: # extra_params.extend( # ['--msgs-no-count', beta_msg, '--extra-params', '--enable=%s' % beta_msg] # ) # [antoniov: 2018-09-12] for leverage_msg in leverage_msgs: extra_params.extend( [ '--msgs-no-count', leverage_msg, '--extra-params', '--disable=%s' % leverage_msg, ] ) # [antoniov: 2020-07-20] for versioned_msg in versioned_msgs: extra_params.extend(['--extra-params', '--disable=%s' % versioned_msg]) return extra_params def get_versioned_msgs(odoo_version): """[antoniov: 2020-07-20] enable or disable some check depending on Odoo version :return: List of strings with beta message names""" odoo_version = odoo_version.replace('.', '') specific_cfg = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'cfg/travis_run_pylint_exclude_%s.cfg' % (odoo_version), ) if not os.path.isfile(specific_cfg): return [] config = ConfigParser.ConfigParser() config.readfp(open(specific_cfg)) params = [] for section in config.sections(): for option, value in config.items(section): params.extend(['--' + option, value.strip().replace('\n', '')]) return params def get_leverage_msgs(): """[antoniov: 2018-09-12] Based on LINT_CHECK_LEVEL, disable some check :return: List of strings with beta message names""" exclude_level = os.environ.get('LINT_CHECK_LEVEL', '') specific_cfg = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'cfg/travis_run_pylint_exclude_%s.cfg' % exclude_level, ) if not os.path.isfile(specific_cfg): return [] config = ConfigParser.ConfigParser() config.readfp(open(specific_cfg)) params = [] for section in config.sections(): for option, value in config.items(section): params.extend(['--' + option, value.strip().replace('\n', '')]) return params def get_beta_msgs(): """Get beta msgs from beta.cfg file :return: List of strings with beta message names""" beta_cfg = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'cfg/travis_run_pylint_beta.cfg' ) if not os.path.isfile(beta_cfg): return [] config = ConfigParser.ConfigParser() config.readfp(open(beta_cfg)) return [ msg.strip().replace('\n', '') for msg in config.get('MESSAGES CONTROL', 'enable').split(',') if msg.strip() ] def get_modules_cmd(dir): modules_cmd = [] include_lint = os.environ.get('INCLUDE_LINT') if include_lint: for path in include_lint.split(' '): modules_cmd.extend(['--path', path]) else: modules_cmd.extend(["--path", dir]) return modules_cmd def version_validate(version, dir): if not version and dir: repo_path = os.path.join(dir, '.git') branch_name = GitRun(repo_path).get_branch_name() version = branch_name.replace('_', '-').split('-')[:1] if branch_name else False version = version[0] if version else None if not version: print( travis_helpers.yellow( 'Undefined environment variable' ' `VERSION`.\nSet `VERSION` for ' 'compatibility with guidelines by version.' ) ) return version def get_branch_base(): branch_base = os.environ.get('TRAVIS_BRANCH') or os.environ.get('VERSION') if branch_base != 'HEAD': branch_base = 'origin/' + (branch_base and branch_base or '') return branch_base def pylint_run(is_pr, version, dir): # Look for an environment variable # whose value is the name of a proper configuration file for pylint # (this file will then be expected to be found in the 'cfg/' folder). # If such an environment variable is not found, # it defaults to the standard configuration file. pylint_config_file = os.environ.get('PYLINT_CONFIG_FILE', 'travis_run_pylint.cfg') pylint_rcfile = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'cfg', pylint_config_file ) pylint_rcfile_pr = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'cfg', "travis_run_pylint_pr.cfg" ) odoo_version = version_validate(version, dir) modules_cmd = get_modules_cmd(dir) beta_msgs = get_beta_msgs() branch_base = get_branch_base() extra_params_cmd = get_extra_params(odoo_version) extra_info = "extra_params_cmd %s " % extra_params_cmd print(extra_info) conf = ["--config-file=%s" % (pylint_rcfile)] cmd = conf + modules_cmd + extra_params_cmd real_errors = main(cmd, standalone_mode=False) # res = { # key: value # for key, value in (real_errors.get('by_msg') or {}).items() # if key not in beta_msgs # } res = { key: value for key, value in ( hasattr(real_errors, 'by_msg') and getattr(real_errors, 'by_msg') or {} ).items() } count_errors = get_count_fails(real_errors, list(beta_msgs)) count_info = "count_errors %s" % count_errors print(count_info) if is_pr: print(travis_helpers.green('Starting lint check only for modules changed')) modules_changed = get_modules_changed(dir, branch_base) if not modules_changed: print( travis_helpers.green( 'There are not modules changed from ' '"git --git-dir=%s diff ..%s"' % (dir, branch_base) ) ) return res modules_changed_cmd = [] for module_changed in modules_changed: modules_changed_cmd.extend(['--path', module_changed]) conf = ["--config-file=%s" % (pylint_rcfile_pr)] cmd = conf + modules_changed_cmd + extra_params_cmd pr_real_errors = main(cmd, standalone_mode=False) # pr_stats = { # key: value # for key, value in (pr_real_errors.get('by_msg') or {}).items() # if key not in beta_msgs # } pr_stats = { key: value for key, value in ( hasattr(pr_real_errors, 'by_msg') and getattr(pr_real_errors, 'by_msg') or {} ).items() } if pr_stats: pr_errors = get_count_fails(pr_real_errors, list(beta_msgs)) print( travis_helpers.yellow( "Found %s errors in modules changed." % (pr_errors) ) ) if pr_errors < 0: res = pr_stats else: new_dict = {} for val in res: new_dict[val] = new_dict.get(val, 0) + res[val] for val in pr_stats: new_dict[val] = new_dict.get(val, 0) + pr_stats[val] res = new_dict return res def get_count_fails(linter_stats, msgs_no_count=None): """Verify the dictionary statistics to get number of errors. :param linter_stats: Dict of type pylint.lint.Run().linter.stats :param no_count: List of messages that will not add to the failure count. :return: Integer with quantity of fails found. """ return sum( # [ # linter_stats['by_msg'][msg] # for msg in (linter_stats.get('by_msg') or {}) # if msg not in msgs_no_count # ] [ linter_stats['by_msg'][msg] for msg in ( hasattr(linter_stats, 'by_msg') and getattr(linter_stats, 'by_msg') or {} ) ] ) def is_installable_module(path): """return False if the path doesn't contain an installable odoo module, otherwise the full path to the module's manifest""" manifest_path = is_module(path) if manifest_path: manifest = ast.literal_eval(open(manifest_path).read()) if manifest.get('installable', True): return manifest_path return False def get_subpaths(paths, depth=1): """Get list of subdirectories if `__init__.py` file doesn't exists in root path, then get subdirectories. Why? More info here: https://www.mail-archive.com/[email protected]/msg00294.html :param paths: List of paths :param depth: How many folders can be opened in deep to find a module. :return: Return list of paths with subdirectories. """ subpaths = [] for path in paths: if depth < 0: continue if not os.path.isfile(os.path.join(path, '__init__.py')): new_subpaths = [ os.path.join(path, item) for item in os.listdir(path) if os.path.isdir(os.path.join(path, item)) ] if new_subpaths: subpaths.extend(get_subpaths(new_subpaths, depth - 1)) else: if is_installable_module(path): subpaths.append(path) return subpaths def run_pylint(paths, cfg, beta_msgs=None, sys_paths=None, extra_params=None): """Execute pylint command from original python library :param paths: List of paths of python modules to check with pylint :param cfg: String name of pylint configuration file :param sys_paths: List of paths to append to sys path :param extra_params: List of extra parameters to append in pylint command :return: Dict with python linter stats """ if sys_paths is None: sys_paths = [] if extra_params is None: extra_params = [] sys.path.extend(sys_paths) cmd = ['--rcfile=' + cfg] cmd.extend(extra_params) subpaths = get_subpaths(paths) if not subpaths: raise UserWarning("Python modules not found in paths %s" % (paths)) exclude = os.environ.get('EXCLUDE', '').split(',') subpaths = [path for path in subpaths if os.path.basename(path) not in exclude] if not subpaths: return {'error': 0} cmd.extend(subpaths) if ( sys.version_info[0] == 2 and 'do_exit' in inspect.getargspec(pylint.lint.Run.__init__)[0] ): # pylint has renamed this keyword argument pylint_res = pylint.lint.Run(cmd, do_exit=False) elif ( sys.version_info[0] > 2 and 'do_exit' in inspect.getfullargspec(pylint.lint.Run.__init__)[0] ): # pylint has renamed this keyword argument pylint_res = pylint.lint.Run(cmd, do_exit=False) else: pylint_res = pylint.lint.Run(cmd, exit=False) return pylint_res.linter.stats @click.command() @click.option( 'paths', '--path', envvar='TRAVIS_BUILD_DIR', multiple=True, type=CLICK_DIR, required=True, default=[os.getcwd()], help="Addons paths to check pylint", ) @click.option( '--config-file', '-c', type=click.File('r', lazy=True), required=True, help="Pylint config file", ) @click.option( '--sys-paths', '-sys-path', envvar='PYTHONPATH', multiple=True, type=CLICK_DIR, help="Additional paths to append in sys path.", ) @click.option( '--extra-params', '-extra-param', multiple=True, help="Extra pylint params to append " "in pylint command", ) @click.option( '--msgs-no-count', '-msgs-no-count', multiple=True, help="List of messages that will not add to the failure count.", ) def main(paths, config_file, msgs_no_count=None, sys_paths=None, extra_params=None): """Script to run pylint command with additional params to check fails of odoo modules. If expected errors is equal to count fails found then this program exits with zero, otherwise exits with counted fails""" try: stats = run_pylint( list(paths), config_file.name, sys_paths=sys_paths, extra_params=extra_params, ) except UserWarning: stats = {'error': -1} return stats if __name__ == '__main__': try: exit(main(standalone_mode=False)) except click.ClickException as e: e.show() exit(e.exit_code)
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/travis/run_pylint.py
run_pylint.py
from __future__ import print_function import ast import os import sys try: from git_run import GitRun except ImportError: try: from .git_run import GitRun except ImportError: from git_run import GitRun __version__ = '2.0.11' MANIFEST_FILES = ['__manifest__.py', '__odoo__.py', '__openerp__.py', '__terp__.py'] def is_module(path): """return False if the path doesn't contain an odoo module, and the full path to the module manifest otherwise""" path = os.path.expanduser(path) if not os.path.isdir(path): return False files = os.listdir(path) filtered = [x for x in files if x in (MANIFEST_FILES + ['__init__.py'])] if len(filtered) == 2 and '__init__.py' in filtered: return os.path.join(path, next(x for x in filtered if x != '__init__.py')) else: return False def get_modules(path, depth=1): """Return modules of path repo (used in test_server.py)""" return sorted(list(get_modules_info(path, depth).keys())) def get_modules_info(path, depth=1): """Return a digest of each installable module's manifest in path repo""" # Avoid empty basename when path ends with slash path = os.path.expanduser(path) if not os.path.basename(path): path = os.path.dirname(path) modules = {} if os.path.isdir(path) and depth > 0: for module in os.listdir(path): manifest_path = is_module(os.path.join(path, module)) if manifest_path: try: manifest = ast.literal_eval(open(manifest_path).read()) except ImportError: raise Exception('Wrong file %s' % manifest_path) if manifest.get('installable', True): modules[module] = { 'application': manifest.get('application'), 'depends': manifest.get('depends') or [], 'auto_install': manifest.get('auto_install'), } else: deeper_modules = get_modules_info(os.path.join(path, module), depth - 1) modules.update(deeper_modules) return modules def is_addons(path): """return if the path does contain one or more odoo modules""" res = get_modules(path) != [] return res def get_addons(path, depth=1): """Return repositories in path. Can search in inner folders as depth.""" path = os.path.expanduser(path) if not os.path.exists(path) or depth < 0: return [] res = [] if is_addons(path): res.append(path) else: new_paths = [ os.path.join(path, x) for x in sorted(os.listdir(path)) if os.path.isdir(os.path.join(path, x)) ] for new_path in new_paths: res.extend(get_addons(new_path, depth - 1)) return res def get_modules_changed(path, ref='HEAD'): """Get modules changed from git diff-index {ref} :param path: String path of git repo :param ref: branch or remote/branch or sha to compare :return: List of paths of modules changed """ path = os.path.expanduser(path) git_run_obj = GitRun(os.path.join(path, '.git')) if ref != 'HEAD': fetch_ref = ref if ':' not in fetch_ref: # to force create branch fetch_ref += ':' + fetch_ref git_run_obj.run(['fetch'] + fetch_ref.split('/', 1)) items_changed = git_run_obj.get_items_changed(ref) folders_changed = { item_changed.split('/')[0] for item_changed in items_changed if '/' in item_changed } modules = set(get_modules(path)) modules_changed = list(modules & folders_changed) modules_changed_path = [ os.path.join(path, module_changed) for module_changed in modules_changed ] return modules_changed_path def get_dependencies(modules, module_name): """Return a set of all the dependencies in deep of the module_name. The module_name is included in the result.""" result = set() for dependency in modules.get(module_name, {}).get('depends', []): result |= get_dependencies(modules, dependency) return result | {module_name} def get_dependents(modules, module_name): """Return a set of all the modules that are dependent of the module_name. The module_name is included in the result.""" result = set() for dependent in modules.keys(): if module_name in modules.get(dependent, {}).get('depends', []): result |= get_dependents(modules, dependent) return result | {module_name} def add_auto_install(modules, to_install): """Append automatically installed glue modules to to_install if their dependencies are already present. to_install is a set.""" found = True while found: found = False for module, module_data in modules.items(): if ( module_data.get('auto_install') and module not in to_install and all( dependency in to_install for dependency in module_data.get('depends', []) ) ): found = True to_install.add(module) return to_install def get_applications_with_dependencies(modules): """Return all modules marked as application with their dependencies. For our purposes, l10n modules cannot be an application.""" result = set() for module, module_data in modules.items(): if module_data.get('application') and not module.startswith('l10n_'): result |= get_dependencies(modules, module) return add_auto_install(modules, result) def get_localizations_with_dependents(modules): """Return all localization modules with the modules that depend on them""" result = set() for module in modules.keys(): if module.startswith('l10n_'): result |= get_dependents(modules, module) return result def main(argv=None): if argv is None: argv = sys.argv params = argv[1:] if not params: print(__doc__) return 1 list_modules = False application = None localization = None exclude_modules = [] while params and params[0].startswith('-'): param = params.pop(0) if param == '-h' or param == '--help': print(__doc__) return 1 elif param == '-V' or param == '--version': print(__version__) return 1 elif param == '-m': list_modules = True elif param == '-e': exclude_modules = [x for x in params.pop(0).split(',')] elif param == '--only-applications': application = True elif param == '--exclude-applications': application = False elif param == '--only-localization': localization = True elif param == '--exclude-localization': localization = False elif param.startswith('-'): raise Exception('Unknown parameter: %s' % param) if list_modules: modules = {} for path in params: modules.update(get_modules_info(path)) res = set(modules.keys()) applications, localizations = set(), set() if application is True or application is False: applications = get_applications_with_dependencies(modules) if not application: res -= applications applications = set() if localization is True or localization is False: localizations = get_localizations_with_dependents(modules) if not localization: res -= localizations localizations = set() if application or localization: res = applications | localizations res = sorted(list(res)) else: lists = [get_addons(path) for path in params] # return flatten list of lists without duplicates res = dict.fromkeys([x for lx in lists for x in lx]).keys() if exclude_modules: res = [x for x in res if x not in exclude_modules] print(','.join(res)) return res if __name__ == "__main__": sys.exit(main())
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/travis/getaddons.py
getaddons.py
import sys from contextlib import closing class _OdooBaseContext(object): """ Abstract class for odoo connections and translation export without version specification. Inherit from this class to implement version specific connection parameters. """ def __init__(self, server_path, addons_path, dbname): """ Create context object. Stock odoo server path and database name. :param str server_path: path to odoo root :param str addons_path: comma separated list of addon paths :param str dbname: database name with odoo installation """ self.server_path = server_path self.addons_path = addons_path self.dbname = dbname def __enter__(self): raise NotImplementedError( "The class %s is an abstract class which" "doesn't have __enter__ implemented." % self.__class__.__name__ ) def __exit__(self, exc_type, exc_val, exc_tb): """ Cleanly close cursor """ self.cr.close() def get_pot_contents(self, addon, lang=None): """ Export source translation files from addon. :param str addon: Addon name :returns str: Gettext from addon .pot content """ import codecs import cStringIO buffer = cStringIO.StringIO() codecs.getwriter("utf8")(buffer) self.trans_export(lang, [addon], buffer, 'po', self.cr) tmp = buffer.getvalue() buffer.close() return tmp def load_po(self, po, lang): self.trans_load_data(self.cr, po, 'po', lang) class Odoo10Context(_OdooBaseContext): """A context for connecting to a odoo 10 server with function to export .pot files. """ def __enter__(self): """ Context enter function. Temporarily add odoo 10 server path to system path and pop afterwards. Import odoo 10 server from path as library. Init logger, registry and environment. Add addons path to config. :returns Odoo10Context: This instance """ sys.path.append(self.server_path) from odoo import api, netsvc from odoo.modules.registry import Registry from odoo.tools import config, trans_export, trans_load_data self.trans_export = trans_export self.trans_load_data = trans_load_data sys.path.pop() netsvc.init_logger() config['addons_path'] = config.get('addons_path') + ',' + self.addons_path registry = Registry.new(self.dbname) self.environment_manage = api.Environment.manage() self.environment_manage.__enter__() self.cr = registry.cursor() return self def __exit__(self, exc_type, exc_val, exc_tb): """ Context exit function. Cleanly close environment manage and cursor. """ self.environment_manage.__exit__(exc_type, exc_val, exc_tb) super(Odoo10Context, self).__exit__(exc_type, exc_val, exc_tb) class Odoo11Context(Odoo10Context): """A context for connecting to a odoo 11 server with an special override for getting translations with Python 3. """ def get_pot_contents(self, addon, lang=None): """ Export source translation files from addon. :param str addon: Addon name :returns bytes: Gettext from addon .pot content """ from io import BytesIO with closing(BytesIO()) as buf: self.trans_export(lang, [addon], buf, 'po', self.cr) return buf.getvalue() class Odoo8Context(_OdooBaseContext): """ A context for connecting to a odoo 8 server with function to export .pot """ def __enter__(self): """ Context enter function. Temporarily add odoo 8 server path to system path and pop afterwards. Import odoo 8 server from path as library. Init logger, registry and environment. Add addons path to config. :returns Odoo8Context: This instance """ sys.path.append(self.server_path) from openerp import api, netsvc from openerp.modules.registry import RegistryManager from openerp.tools import config, trans_export, trans_load_data self.trans_export = trans_export self.trans_load_data = trans_load_data sys.path.pop() netsvc.init_logger() config['addons_path'] = config.get('addons_path') + ',' + self.addons_path registry = RegistryManager.new(self.dbname) self.environment_manage = api.Environment.manage() self.environment_manage.__enter__() self.cr = registry.cursor() return self def __exit__(self, exc_type, exc_val, exc_tb): """ Context exit function. Cleanly close environment manage and cursor. """ self.environment_manage.__exit__(exc_type, exc_val, exc_tb) super(Odoo8Context, self).__exit__(exc_type, exc_val, exc_tb) class Odoo7Context(_OdooBaseContext): """ A context for connecting to a odoo 7 server with function to export .pot """ def __enter__(self): """ Context enter function. Temporarily add odoo 7 server path to system path and pop afterwards. Import odoo 7 server from path as library. Init logger and pool. Add addons path to config. :returns Odoo8Context: This instance """ sys.path.append(self.server_path) from openerp import netsvc from openerp.pooler import get_db from openerp.tools import config, trans_export, trans_load_data self.trans_export = trans_export self.trans_load_data = trans_load_data sys.path.pop() netsvc.init_logger() config['addons_path'] = str(config.get('addons_path') + ',' + self.addons_path) self.cr = get_db(self.dbname).cursor() return self context_mapping = { "7.0": Odoo7Context, "8.0": Odoo8Context, "9.0": Odoo8Context, "10.0": Odoo10Context, "11.0": Odoo11Context, }
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/travis/odoo_connection.py
odoo_connection.py
import base64 import json import os import requests class ApiException(Exception): pass class Request(object): def __init__(self): self.session = requests.Session() def _check(self): if not self._token: raise ApiException("WARNING! Token not defined exiting early.") self.session.headers.update( { 'Accept': 'application/json', 'User-Agent': 'mqt', 'Authorization': 'Token %s' % self._token, } ) self._request(self.host) def _request(self, url, payload=None, is_json=True, patch=False): try: if not payload and not patch: response = self.session.get(url) elif patch: response = self.session.patch(url, data=payload) else: response = self.session.post(url, data=payload) response.raise_for_status() except requests.RequestException as error: raise ApiException(str(error)) return response.json() if is_json else response class GitHubApi(Request): def __init__(self): super(GitHubApi, self).__init__() self._token = os.environ.get("GITHUB_TOKEN") self.host = "https://api.github.com" self._owner, self._repo = os.environ.get("TRAVIS_REPO_SLUG").split('/') def create_pull_request(self, data): pull = self._request( self.host + '/repos/%s/%s/pulls' % (self._owner, self._repo), json.dumps(data), ) return pull def create_commit(self, message, branch, files): tree = [] info_branch = self._request( self.host + '/repos/%s/%s/git/refs/heads/%s' % (self._owner, self._repo, branch) ) branch_commit = self._request( self.host + '/repos/%s/%s/git/commits/%s' % (self._owner, self._repo, info_branch['object']['sha']) ) for item in files: with open(item) as f_po: blob_data = json.dumps( {'content': base64.b64encode(f_po.read()), 'encoding': 'base64'} ) blob_sha = self._request( self.host + '/repos/%s/%s/git/blobs' % (self._owner, self._repo), blob_data, ) tree.append( { 'path': item, 'mode': '100644', 'type': 'blob', 'sha': blob_sha['sha'], } ) tree_data = json.dumps( {'base_tree': branch_commit['tree']['sha'], 'tree': tree} ) info_tree = self._request( self.host + '/repos/%s/%s/git/trees' % (self._owner, self._repo), tree_data ) commit_data = json.dumps( { 'message': message, 'tree': info_tree['sha'], 'parents': [branch_commit['sha']], } ) info_commit = self._request( self.host + '/repos/%s/%s/git/commits' % (self._owner, self._repo), commit_data, ) update_branch = self._request( self.host + '/repos/%s/%s/git/refs/heads/%s' % (self._owner, self._repo, branch), json.dumps({'sha': info_commit['sha']}), patch=True, ) return info_commit['sha'] == update_branch['object']['sha']
z0bug-odoo
/z0bug_odoo-2.0.11.tar.gz/z0bug_odoo-2.0.11/z0bug_odoo/travis/apis.py
apis.py
====== 2.0.6 ====== |Maturity| |license gpl| Overview ======== Simple bash library +---------------+-----------------------------------------------------------+ | xuname | Detect and print more OS informations than uname command | +---------------+-----------------------------------------------------------+ | parse_optargs | Parse command line arguments in a professional way | +---------------+-----------------------------------------------------------+ | print_help | Print help for parse command line arguments | +---------------+-----------------------------------------------------------+ You can find more info here: http://wiki.zeroincombenze.org/en/Linux/dev http://docs.zeroincombenze.org/z0lib/ | | Getting started =============== Installation ------------ Zeroincombenze tools require: * Linux Centos 7/8 or Debian 9/10 or Ubuntu 18/20/22 * python 2.7+, some tools require python 3.6+ * bash 5.0+ Stable version via Python Package ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: pip install | Current version via Git ~~~~~~~~~~~~~~~~~~~~~~~ :: cd $HOME git clone https://github.com/zeroincombenze/tools.git cd ./tools ./install_tools.sh -p source $HOME/devel/activate_tools Upgrade ------- Stable version via Python Package ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: pip install -U | Current version via Git ~~~~~~~~~~~~~~~~~~~~~~~ :: cd $HOME ./install_tools.sh -U source $HOME/devel/activate_tools History ------- 2.0.5 (2023-05-14) ~~~~~~~~~~~~~~~~~~ * [FIX] Sometime configuration init fails * [IMP] Configuration name LOCAL_PKGS read real packages * [IMP] is_pypi function more precise 2.0.4 (2023-04-10) ~~~~~~~~~~~~~~~~~~ * [FIX] run_traced: cd does not work w/o alias * [IMP] coveralls and codecov are not more dependencies 2.0.3 (2022-12-22) ~~~~~~~~~~~~~~~~~~ * [FIX] run_traced: --switch sometime crashes * [FIX] run_traced: alias function 2.0.2 (2022-12-07) ~~~~~~~~~~~~~~~~~~ * [FIX] best recognition of python version * [FIX] run_traced: fail with python 2 2.0.1 (2022-10-20) ~~~~~~~~~~~~~~~~~~ * [IMP] Stable version 2.0.0.4.1 (2022-10-20) ~~~~~~~~~~~~~~~~~~~~~~ * [FIX] run_traced: wrong execution for "cd <path>; ..." * [IMP] CFG_init 'ALL': set ODOO_ROOT 2.0.0.4 (2022-10-05) ~~~~~~~~~~~~~~~~~~~~ * [IMP] python2 tests 2.0.0.3 (2022-09-30) ~~~~~~~~~~~~~~~~~~~~ * [FIX] run_traced return code 2.0.0.2 (2022-09-14) ~~~~~~~~~~~~~~~~~~~~ * [IMP] run_traced for python apps 2.0.0.1 (2022-09-06) ~~~~~~~~~~~~~~~~~~~~ * [IMP] set_pybin accept filename * [IMP] check_pythonpath removed 2.0.0 (2022-08-10) ~~~~~~~~~~~~~~~~~~ * [REF] Partial refactoring for shell scripts | | Credits ======= Copyright --------- SHS-AV s.r.l. <https://www.shs-av.com/> Contributors ------------ * Antonio Maria Vigliotti <[email protected]> | This module is part of project. Last Update / Ultimo aggiornamento: .. |Maturity| image:: https://img.shields.io/badge/maturity-Beta-yellow.png :target: https://odoo-community.org/page/development-status :alt: .. |license gpl| image:: https://img.shields.io/badge/licence-AGPL--3-blue.svg :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html :alt: License: AGPL-3 .. |license opl| image:: https://img.shields.io/badge/licence-OPL-7379c3.svg :target: https://www.odoo.com/documentation/user/9.0/legal/licenses/licenses.html :alt: License: OPL .. |Tech Doc| image:: https://www.zeroincombenze.it/wp-content/uploads/ci-ct/prd/button-docs-2.svg :target: https://wiki.zeroincombenze.org/en/Odoo/2.0/dev :alt: Technical Documentation .. |Help| image:: https://www.zeroincombenze.it/wp-content/uploads/ci-ct/prd/button-help-2.svg :target: https://wiki.zeroincombenze.org/it/Odoo/2.0/man :alt: Technical Documentation .. |Try Me| image:: https://www.zeroincombenze.it/wp-content/uploads/ci-ct/prd/button-try-it-2.svg :target: https://erp2.zeroincombenze.it :alt: Try Me .. |Zeroincombenze| image:: https://avatars0.githubusercontent.com/u/6972555?s=460&v=4 :target: https://www.zeroincombenze.it/ :alt: Zeroincombenze .. |en| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/flags/en_US.png :target: https://www.facebook.com/Zeroincombenze-Software-gestionale-online-249494305219415/ .. |it| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/flags/it_IT.png :target: https://www.facebook.com/Zeroincombenze-Software-gestionale-online-249494305219415/ .. |check| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/check.png .. |no_check| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/no_check.png .. |menu| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/menu.png .. |right_do| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/right_do.png .. |exclamation| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/exclamation.png .. |warning| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/warning.png .. |same| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/same.png .. |late| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/late.png .. |halt| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/halt.png .. |info| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/awesome/info.png .. |xml_schema| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/certificates/iso/icons/xml-schema.png :target: https://github.com/zeroincombenze/grymb/blob/master/certificates/iso/scope/xml-schema.md .. |DesktopTelematico| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/certificates/ade/icons/DesktopTelematico.png :target: https://github.com/zeroincombenze/grymb/blob/master/certificates/ade/scope/Desktoptelematico.md .. |FatturaPA| image:: https://raw.githubusercontent.com/zeroincombenze/grymb/master/certificates/ade/icons/fatturapa.png :target: https://github.com/zeroincombenze/grymb/blob/master/certificates/ade/scope/fatturapa.md .. |chat_with_us| image:: https://www.shs-av.com/wp-content/chat_with_us.gif :target: https://t.me/Assitenza_clienti_powERP
z0lib
/z0lib-2.0.6.tar.gz/z0lib-2.0.6/README.rst
README.rst
Copyright 2022 David Michael Pennington Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
z2
/z2-0.0.30-py3-none-any.whl/z2-0.0.30.dist-info/LICENSE.md
LICENSE.md
pl-z2labelmap ============= .. image:: https://badge.fury.io/py/z2labelmap.svg :target: https://badge.fury.io/py/z2labelmap .. image:: https://travis-ci.org/FNNDSC/z2labelmap.svg?branch=master :target: https://travis-ci.org/FNNDSC/z2labelmap .. image:: https://img.shields.io/badge/python-3.5%2B-blue.svg :target: https://badge.fury.io/py/pl-z2labelmap .. contents:: Table of Contents Abstract -------- ``zlabelmap.py`` generates FreeSurfer labelmaps from z-score vector files. These labelmap files are used by FreeSurfer to color-code parcellated brain regions. By calculating a z-score to labelmap transform, we are able to show a heat map and hightlight brain regions that differ from some comparative reference, as demonstrasted below .. image:: https://github.com/FNNDSC/pl-z2labelmap/wiki/images/subj1-heatmap/frame126.png where positive volume deviations of a parcellated brain region are shown in red (i.e. the subject had a larger volume in that area than the reference), and negative volume deviations are shown in blue (i.e. the subject had a smaller volume in that area than reference). *Note that these are randomly generated z-scores purely for illustrative purposes*. Essentially the script consumes an input text vector file of .. code:: <str_structureName> <float_lh_zScore> <float_rh_zScore> for example, .. code:: G_and_S_frontomargin ,1.254318450576827,-0.8663546810093861 G_and_S_occipital_inf ,1.0823728865077271,-0.7703944006354377 G_and_S_paracentral ,0.20767669866335847,2.9023126278939912 G_and_S_subcentral ,2.395503357157743,-1.4966482475891556 G_and_S_transv_frontopol ,-1.7849555258577423,-2.461419463760234 G_and_S_cingul-Ant ,-2.3831737860960382,1.1892593438667625 G_and_S_cingul-Mid-Ant ,0.03381695289572084,-0.7909116233500506 G_and_S_cingul-Mid-Post ,-2.4096082230335485,1.166457973597625 ... ... S_postcentral ,1.3277159068067768,-1.4042773812503526 S_precentral-inf-part ,-1.9467169777576718,1.7216636236995733 S_precentral-sup-part ,0.764673539853991,2.1081570332369504 S_suborbital ,0.522368665639954,-2.3593237820349007 S_subparietal ,-0.14697262729901928,-2.2116605141889094 S_temporal_inf ,-1.8442944920810271,-0.6895142771486307 S_temporal_sup ,-1.8645248463693804,2.740099589311164 S_temporal_transverse ,-2.4244451521560073,2.286596403222344 and creates a FreeSurfer labelmap where ``<str_structureName>`` colors correspond to the z-score (normalized between 0 and 255). Currently, only the ``aparc.a2009s`` FreeSurfer segmentation is fully supported, however future parcellation support is planned. Negative z-scores and positive z-scores are treated in the same manner but have sign-specific color specifications. Positive and negative z-Scores can be assigned some combination of the chars ``RGB`` to indicate which color dimension will reflect the z-Score. For example, a .. code:: --posColor R --negColor RG will assign positive z-scores shades of ``red`` and negative z-scores shades of ``yellow`` (Red + Green = Yellow). Synopsis -------- .. code:: python z2labelmap.py \ [-v <level>] [--verbosity <level>] \ [--random] [--seed <seed>] \ [-p <f_posRange>] [--posRange <f_posRange>] \ [-n <f_negRange>] [--negRange <f_negRange>] \ [-P <'RGB'>] [--posColor <'RGB'>] \ [-N <'RGB'>] [--negColor <'RGB'>] \ [--imageSet <imageSetDirectory>] \ [-s <f_scaleRange>] [--scaleRange <f_scaleRange>] \ [-l <f_lowerFilter>] [--lowerFilter <f_lowerFilter>] \ [-u <f_upperFilter>] [--upperFilter <f_upperFilter>] \ [-z <zFile>] [--zFile <zFile>] \ [--version] \ [--man] \ [--meta] \ <inputDir> \ <outputDir> Run ---- This ``plugin`` can be run in two modes: natively as a python package or as a containerized docker image. Using PyPI ~~~~~~~~~~ To run from PyPI, simply do a .. code:: bash pip install z2labelmap and run with .. code:: bash z2labelmap.py --man /tmp /tmp to get inline help. Using ``docker run`` ~~~~~~~~~~~~~~~~~~~~ To run using ``docker``, be sure to assign an "input" directory to ``/incoming`` and an output directory to ``/outgoing``. *Make sure that the* ``$(pwd)/out`` *directory is world writable!* Now, prefix all calls with .. code:: bash docker run --rm -v $(pwd)/in:/incoming -v $(pwd)/out:/outgoing \ fnndsc/pl-z2labelmap z2labelmap.py \ Thus, getting inline help is: .. code:: bash docker run --rm -v $(pwd)/in:/incoming -v $(pwd)/out:/outgoing \ fnndsc/pl-z2labelmap z2labelmap.py \ --man \ /incoming /outgoing Examples -------- Create a sample/random z-score file and analyze ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * In the absense of an actual z-score file, the script can create one. This can then be used in subsequent analysis: .. code:: mkdir in out docker run --rm -v $(pwd)/in:/incoming -v $(pwd)/out:/outgoing \ fnndsc/pl-z2labelmap z2labelmap.py \ --random --seed 1 \ --posRange 3.0 --negRange -3.0 \ /incoming /outgoing or without docker .. code:: mkdir in out z2labelmap.py \ --random --seed 1 \ --posRange 3.0 --negRange -3.0 \ /in /out In this example, z-scores range between 0.0 and (+/-) 3.0. Generate labelmap and also copy pre-calculated image set to output ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Analyze a file already located at ``in/zfile.csv`` and copy pre-calculated image data .. code:: docker run --rm -v $(pwd)/in:/incoming -v $(pwd)/out:/outgoing \ fnndsc/pl-z2labelmap z2labelmap.py \ --negColor B --posColor R \ --imageSet ../data/set1 \ /incoming /outgoing This assumes a file called 'zfile.csv' in the <inputDirectory> that ranges in z-score between 0.0 and 3.0, and uses the --scaleRange to reduce the apparent brightness of the map by 50 percent. Furthermore, the lower 80 percent of z-scores are removed (this has the effect of only showing the brightest 20 percent of zscores). Control relative brightness and lower filter low z-scores from final labelmap ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * To analyze a file already located at ``in/zfile.csv``, apply a ``scaleRange`` and also filter out the lower 80\% of z-scores: .. code:: docker run --rm -v $(pwd)/in:/incoming -v $(pwd)/out:/outgoing \ fnndsc/pl-z2labelmap z2labelmap.py \ --scaleRange 2.0 --lowerFilter 0.8 \ --negColor B --posColor R \ /incoming /outgoing This assumes a file called 'zfile.csv' in the <inputDirectory> that ranges in z-score between 0.0 and 3.0, and uses the --scaleRange to reduce the apparent brightness of the map by 50 percent. Furthermore, the lower 80 percent of z-scores are removed (this has the effect of only showing the brightest 20 percent of zscores). Using the above referenced z-score file, this results in: .. code:: 0 Unknown 0 0 0 0 11101 lh-G_and_S_frontomargin 0 0 0 0 11102 lh-G_and_S_occipital_inf 0 0 0 0 11103 lh-G_and_S_paracentral 0 0 0 0 11104 lh-G_and_S_subcentral 103 0 0 0 11105 lh-G_and_S_transv_frontopol 0 0 0 0 11106 lh-G_and_S_cingul-Ant 0 0 110 0 11107 lh-G_and_S_cingul-Mid-Ant 0 0 0 0 11108 lh-G_and_S_cingul-Mid-Post 0 0 111 0 ... ... 12167 rh-S_postcentral 0 0 0 0 12168 rh-S_precentral-inf-part 0 0 0 0 12169 rh-S_precentral-sup-part 0 0 0 0 12170 rh-S_suborbital 0 0 110 0 12171 rh-S_subparietal 0 0 103 0 12172 rh-S_temporal_inf 0 0 0 0 12173 rh-S_temporal_sup 119 0 0 0 12174 rh-S_temporal_transverse 0 0 0 0 Command line arguments ---------------------- .. code:: <inputDir> Required argument. Input directory for plugin. <outputDir> Required argument. Output directory for plugin. [-v <level>] [--verbosity <level>] Verbosity level for app. Not used currently. [--random] [--seed <seed>] If specified, generate a z-score file based on <posRange> and <negRange>. In addition, if a further optional <seed> is passed, then initialize the random generator with that seed, otherwise system time is used. [-p <f_posRange>] [--posRange <f_posRange>] Positive range for random max deviation generation. [-n <f_negRange>] [--negRange <f_negRange>] Negative range for random max deviation generation. [-P <'RGB'>] [--posColor <'RGB'>] Some combination of 'R', 'G', B' for positive heat. [-N <'RGB'> [--negColor <'RGB'>] Some combination of 'R', 'G', B' for negative heat. [--imageSet <imageSetDirectory>] If specified, will copy the (container) prepopulated image set in <imageSetDirectory> to the output directory. [-s <f_scaleRange>] [--scaleRange <f_scaleRange>] Scale range for normalization. This has the effect of controlling the brightness of the map. For example, if this 1.5 the effect is increase the apparent range by 50% which darkens all colors values. [-l <f_lowerFilter>] [--lowerFilter <f_lowerFilter>] Filter all z-scores below (normalized) <lowerFilter> to 0.0. [-u <f_upperFilter>] [--upperFilter <f_upperFilter>] Filter all z-scores above (normalized) <upperFilter> to 0.0. [-z <zFile>] [--zFile <zFile>] z-score file to read (relative to input directory). Defaults to 'zfile.csv'. [--version] If specified, print version number. [--man] If specified, print (this) man page. [--meta] If specified, print plugin meta data.
z2labelmap
/z2labelmap-2.2.0.tar.gz/z2labelmap-2.2.0/README.rst
README.rst
[![PyPI](https://img.shields.io/pypi/v/z2n-periodogram)](https://pypi.org/project/z2n-periodogram/) [![GitHub issues](https://img.shields.io/github/issues/yohanalexander/z2n-periodogram)](https://github.com/yohanalexander/z2n-periodogram/issues) [![GitHub](https://img.shields.io/github/license/yohanalexander/z2n-periodogram)](https://github.com/YohanAlexander/z2n-periodogram/blob/master/LICENSE) [![Documentation Status](https://readthedocs.org/projects/z2n-periodogram/badge/?version=latest)](https://z2n-periodogram.readthedocs.io/en/latest/?badge=latest) <br> <p align="center"> <a href="https://github.com/yohanalexander/z2n-periodogram"> <img src="https://user-images.githubusercontent.com/39287022/84617670-23675480-aea6-11ea-90ac-93a32c01bb92.png" alt="Logo" width="50%" height="50%"> </a> <h1 align="center">Z2n Periodogram</h1> <p align="center"> A package for interative periodograms analysis! <br /> <a href="https://z2n-periodogram.readthedocs.io/"><strong>Explore the docs »</strong></a> <br /> <br /> <a href="https://github.com/yohanalexander/z2n-periodogram">View Demo</a> · <a href="https://github.com/yohanalexander/z2n-periodogram/issues">Report Bug</a> · <a href="https://github.com/yohanalexander/z2n-periodogram/issues">Request Feature</a> </p> ## Table of Contents * [About the Project](#about-the-project) * [Built With](#built-with) * [Getting Started](#getting-started) * [Prerequisites](#prerequisites) * [Installation](#installation) * [Usage](#usage) * [Roadmap](#roadmap) * [Contributing](#contributing) * [License](#license) ## About The Project The Z2n Software was developed by Yohan Alexander as a research project, funded by the CNPq Institution, and it is a Open Source initiative. The program allows the user to calculate periodograms using the Z2n statistics a la Buccheri et al. 1983, which is defined as follows. ![\Large \phi_j \[0,1\] = frac(v_i\Delta t_{ij} + \dot v_i \frac{\Delta t^2_{ij}}{2} + \dot v_i \frac{\Delta t^3_{ij}}{6})](https://render.githubusercontent.com/render/math?math=%5CLarge%20%5Cphi_j%20%5B0%2C1%5D%20%3D%20frac(v_i%5CDelta%20t_%7Bij%7D%20%2B%20%5Cdot%20v_i%20%5Cfrac%7B%5CDelta%20t%5E2_%7Bij%7D%7D%7B2%7D%20%2B%20%5Cdot%20v_i%20%5Cfrac%7B%5CDelta%20t%5E3_%7Bij%7D%7D%7B6%7D)) ![\Large Z^2_n = \frac{2}{N} \cdot \sum_{k=1}^{n} \[(\sum_{j=1}^{N} cos(k\phi_j)) ^ 2 + (\sum_{j=1}^{N} sin(k\phi_j)) ^ 2\]](https://render.githubusercontent.com/render/math?math=%5CLarge%20Z%5E2_n%20%3D%20%5Cfrac%7B2%7D%7BN%7D%20%5Ccdot%20%5Csum_%7Bk%3D1%7D%5E%7Bn%7D%20%5B(%5Csum_%7Bj%3D1%7D%5E%7BN%7D%20cos(k%5Cphi_j))%20%5E%202%20%2B%20(%5Csum_%7Bj%3D1%7D%5E%7BN%7D%20sin(k%5Cphi_j))%20%5E%202%5D) The standard Z2n statistics calculates the phase of each photon and the sinusoidal functions above for each photon. Be advised that this is very computationally expensive if the number of photons is high, since the algorithm grows at a exponential rate ![\large O(n^2)](https://render.githubusercontent.com/render/math?math=%5Clarge%20O(n%5E2)). ### Built With The Z2n Software was built using the `Python` open source language. * [Python](https://python.org) ## Getting Started ### Prerequisites The version of the `Python` interpreter used during the development was the`3.7`, which can be managed in virtual environments such as `Anaconda`. Therefore, try to use the same or above versions for the best compatibility. * Python>=3.7 * PIP ### Installation The software is currently hosted at the Python central repository `PyPI`, to install the software properly use the terminal command: ```sh pip install z2n-periodogram ``` ## Usage To start the software just type `z2n` on the terminal (check if you're under the virtual environment that it is installed). ```sh z2n ``` The `CLI` of the software is very interactive and it works by triggering the commands available, for more information on the usage type `help`. ```sh Z2n Software, a package for interactive periodograms analysis. Copyright (C) 2020, and MIT License, by Yohan Alexander [UFS]. Type "help" for more information or "docs" for documentation. (z2n) >>> help Documented commands (type help <topic>): ======================================== docs gauss plot run save Undocumented commands: ====================== exit help quit (z2n) >>> ``` _For more examples, please refer to the [Documentation](https://z2n-periodogram.readthedocs.io/)_ ## Roadmap See the [open issues](https://github.com/yohanalexander/z2n-periodogram/issues) for a list of proposed features (and known issues). ## Contributing Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ## License All content © 2020 Yohan Alexander. Distributed under the MIT License. See <a href="https://github.com/YohanAlexander/z2n-periodogram/blob/master/LICENSE">LICENSE</a> for more information.
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/README.md
README.md
# Other libraries import click import numpy as np from numba import jit from tqdm import trange from scipy import optimize from scipy.stats import norm import matplotlib.pyplot as plt @jit(forceobj=True, parallel=True, fastmath=True) def exposure(series) -> None: """ Calculate the period of exposure. Parameters ---------- series : Series A time series object. Returns ------- None """ last = series.time[-1] first = series.time[0] series.exposure = last - first @jit(forceobj=True, parallel=True, fastmath=True) def sampling(series) -> None: """ Calculate the sampling rate. Parameters ---------- series : Series A time series object. Returns ------- None """ series.sampling = (1 / series.exposure) @jit(nopython=True, parallel=True, fastmath=True) def phase(times: np.array, freq: float, harm: int) -> np.array: """ Calculate the phase values. Parameters ---------- times : np.array An array that represents the times. freq : float A float that represents the frequency. harm : int A int that represents the harmonics. Returns ------- values : np.array An array that represents the phase values. """ values = times * freq values = values - np.floor(values) values = values * 2 * np.pi * harm return values @jit(nopython=True, parallel=True, fastmath=True) def sine(phases: np.array) -> np.array: """ Calculate the sine values. Parameters ---------- phases : np.array An array that represents the phase values. Returns ------- values : np.array An array that represents the sine values. """ values = np.sin(phases) return values @jit(nopython=True, parallel=True, fastmath=True) def cosine(phases: np.array) -> np.array: """ Calculate the cosine values. Parameters ---------- phases : np.array An array that represents the phase values. Returns ------- values : np.array An array that represents the cosine values. """ values = np.cos(phases) return values @jit(nopython=True, parallel=True, fastmath=True) def summation(values: np.array) -> float: """ Calculate the summation value. Parameters ---------- values : np.array An array that represents the phase values. Returns ------- value : float A float that represents the summation value. """ value = np.sum(values) return value @jit(nopython=True, parallel=False, fastmath=True) def square(value: float) -> float: """ Calculate the square values. Parameters ---------- value : float A float that represents the summation value. Returns ------- value : float A float that represents the square value. """ value = value ** 2 return value @jit(nopython=True, parallel=False, fastmath=True) def summ(sin: float, cos: float) -> float: """ Calculate the Z2n power value. Parameters ---------- sin : float A float that represents the sine value. cos : float A float that represents the cosine value. Returns ------- value : float A float that represents the Z2n power. """ value = sin + cos return value @jit(nopython=True, parallel=False, fastmath=True) def z2n(times: np.array, freq: float, harm: int) -> float: """ Calculate the Z2n power value. times : np.array An array that represents the times. freq : float A float that represents the frequency. harm : int A int that represents the harmonics. Returns ------- value : float A float that represents the Z2n power. """ phases = phase(times, freq, harm) sin = summation(sine(phases)) cos = summation(cosine(phases)) value = summ(square(sin), square(cos)) return value @jit(nopython=True, parallel=True, fastmath=True) def normalization(spectrum: np.array, normal: float) -> np.array: """ Calculate the normalization values. Parameters ---------- spectrum : np.array An array that represents the z2n values. normal : float A float that represents the normalization. Returns ------- values : np.array An array that represents the normalized values. """ values = spectrum * normal return values @jit(nopython=True, parallel=True, fastmath=True) def harmonics(time: np.array, freq: float, harm: int) -> np.array: """ Calculate the Z2n harmonics. Parameters ---------- series : Series A time series object. harm : int A int that represents the harmonics. Returns ------- None """ values = np.zeros(harm) for harmonic in range(harm): values[harmonic] = z2n(time, freq, harmonic + 1) value = summation(values) return value @jit(forceobj=True, parallel=True, fastmath=True) def periodogram(series) -> None: """ Calculate the Z2n statistics. Parameters ---------- series : Series A time series object. Returns ------- None """ if series.harmonics == 1: for freq in trange(series.bins.size, desc=click.style( 'Calculating the periodogram', fg='yellow')): series.z2n[freq] = z2n( series.time, series.bins[freq], series.harmonics) else: for freq in trange(series.bins.size, desc=click.style( 'Calculating the periodogram', fg='yellow')): series.z2n[freq] = harmonics( series.time, series.bins[freq], series.harmonics) series.z2n = normalization(series.z2n, (2 / series.time.size)) @jit(forceobj=True, parallel=True, fastmath=True) def power(series) -> None: """ Calculate the global power. Parameters ---------- series : Series A time series object. Returns ------- None """ series.power = np.max(series.z2n) @jit(forceobj=True, parallel=True, fastmath=True) def frequency(series) -> None: """ Calculate the global frequency. Parameters ---------- series : Series A time series object. Returns ------- None """ index = np.argmax(series.z2n) series.frequency = series.bins[index] @jit(forceobj=True, parallel=True, fastmath=True) def period(series) -> None: """ Calculate the global period. Parameters ---------- series : Series A time series object. Returns ------- None """ series.period = 1 / series.frequency @jit(forceobj=True, parallel=True, fastmath=True) def pfraction(series) -> None: """ Calculate the pulsed fraction. Parameters ---------- series : Series A time series object. Returns ------- None """ pfrac = (2 * series.power) / series.time.size series.pulsed = pfrac ** 0.5 @jit(nopython=True, parallel=True, fastmath=True) def gaussian(x, amplitude, mean, sigma): """Returns a Gaussian like function.""" return amplitude * np.exp(-((x - mean) ** 2) / (2 * sigma ** 2)) @jit(forceobj=True, parallel=True, fastmath=True) def fitcurve(function, bins, powerspec, guess): """Fit a input curve function to the data.""" return optimize.curve_fit(function, bins, powerspec, guess) @jit(forceobj=True, parallel=True, fastmath=True) def equal(A, B, tol=1e-05): """Compare floating point numbers with tolerance.""" S = round(1/tol) return np.in1d(np.around(A*S).astype(int), np.around(B*S).astype(int)) def error(series) -> None: """ Calculate the uncertainty. Parameters ---------- series : Series A time series object. Returns ------- None """ flag = 1 click.secho( "Select the peak region to estimate uncertainty.", fg='yellow') while flag: if click.confirm("Is the peak region selected", prompt_suffix='? '): try: axis = plt.gca().get_xlim() low = np.where(equal(series.bins, axis[0]))[0][0] up = np.where(equal(series.bins, axis[1]))[0][-1] bins = series.bins powerspec = series.z2n series.bins = series.bins[low:up] series.z2n = series.z2n[low:up] mean, sigma = norm.fit(series.bins) power(series) frequency(series) period(series) pfraction(series) guess = [series.power, mean, sigma] popt, _ = fitcurve(gaussian, series.bins, series.z2n, guess) series.gauss.power = np.absolute(popt[0]) series.gauss.frequency = np.absolute(popt[1]) series.gauss.period = 1 / series.gauss.frequency series.gauss.errorf = np.absolute(popt[2]) series.gauss.errorp = np.absolute( (1 / (series.gauss.frequency + series.gauss.errorf)) - series.gauss.period) pfrac = (2 * series.gauss.power) / series.time.size series.gauss.pulsed = pfrac ** 0.5 series.gauss.z2n = gaussian(series.bins, *popt) series.gauss.bins = series.bins series.bins = bins series.z2n = powerspec flag = 0 except IndexError: click.secho("Error on the selection.", fg='red')
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/z2n/stats.py
stats.py
# Generic/Built-in import psutil import pathlib # Other Libraries import click import numpy as np import matplotlib.pyplot as plt # Owned Libraries from z2n import stats from z2n.series import Series class Plot: """ A class to represent the plot of a time series. Attributes ---------- * `input : str` > A string that represents the input file path. * `output : str` > A string that represents the output file name. * `format : str` > A string that represents the file format. * `back : int` > A integer for the state of the background. * `data : Series` > A series object that represents the data. * `noise : Series` > A series object that represents the background. Methods ------- """ def __init__(self) -> None: self.back = 0 self.input = "" self.output = "" self.format = "" self.data = Series() self.noise = Series() self.figure, self.axes = ((), ()) def get_input(self) -> str: """Return the input image name.""" click.secho( f"Name of the file: {self.input}", self.data.input, fg='cyan') return self.input def set_input(self) -> None: """Change the input image name.""" self.input = click.prompt("\nFilename", type=click.Path(exists=True)) def get_output(self) -> str: """Return the output image name.""" click.secho(f"Name of the image: {self.output}", fg='cyan') return self.output def set_output(self) -> None: """Change the output image name.""" default = "z2n_" + pathlib.Path(self.data.input).stem flag = 1 while flag: self.output = click.prompt( "\nName of the image", default, type=click.Path()) if pathlib.Path(f"{self.output}.{self.format}").is_file(): click.secho("File already exists.", fg='red') else: flag = 0 def get_format(self) -> str: """Return the image format.""" click.secho(f"File format: {self.format}", fg='cyan') return self.format def set_format(self) -> None: """Change the image format.""" self.format = click.prompt( "\nFormat", "ps", type=click.Choice(['png', 'pdf', 'ps', 'eps'])) def add_background(self) -> None: """Add background on the plot.""" self.back = 1 click.secho("Background file added.", fg='green') def rm_background(self) -> None: """Remove background on the plot.""" self.back = 0 del self.noise self.noise = Series() click.secho("Background file removed.", fg='green') def plot_figure(self) -> None: """Create the figure on the plotting window.""" plt.close() plt.ion() if not self.back: self.figure, self.axes = plt.subplots(self.back + 1) self.axes.plot( self.data.bins, self.data.z2n, label='Z2n Power', color='tab:blue', linewidth=2) try: self.axes.plot( self.data.gauss.bins, self.data.gauss.z2n, color='tab:red', label='Gaussian Fit', linewidth=1) except AttributeError: pass self.axes.set_xlabel('Frequency (Hz)') self.axes.set_ylabel('Power') self.axes.legend(loc='best') else: self.figure, self.axes = plt.subplots( self.back + 1, sharex=True, sharey=True) self.axes[0].plot( self.data.bins, self.data.z2n, label='Z2n Power', color='tab:blue', linewidth=2) try: self.axes[0].plot( self.data.gauss.bins, self.data.gauss.z2n, color='tab:red', label='Gaussian Fit', linewidth=1) except AttributeError: pass self.axes[1].plot( self.noise.bins, self.noise.z2n, color='tab:cyan', label='Background') self.axes[0].set_xlabel('Frequency (Hz)') self.axes[0].set_ylabel('Power') self.axes[1].set_xlabel('Frequency (Hz)') self.axes[1].set_ylabel('Power') self.axes[0].legend(loc='best') self.axes[1].legend(loc='best') plt.tight_layout() def plot_background(self) -> int: """Create subplot of the background.""" flag = 0 click.secho("The background file is needed.", fg='yellow') if not self.noise.set_time(): self.noise.bins = np.array(self.data.bins) self.noise.harmonics = self.data.harmonics plt.close() self.noise.z2n = np.zeros(self.noise.bins.size) stats.periodogram(self.noise) self.add_background() self.plot_figure() else: flag = 1 return flag def plot_periodogram(self) -> int: """Create plot of the periodogram.""" flag = 0 if not self.data.z2n.size: click.secho("The event file is needed.", fg='yellow') if not self.data.set_time(): if not self.data.set_bins(): plt.close() self.data.set_periodogram() self.data.plot() self.plot_figure() self.save_image() if click.confirm("Add background file", prompt_suffix='? '): self.plot_background() else: flag = 1 else: flag = 1 else: opt = click.prompt( "Change file [1] or frequency range [2]", type=int) if opt in (1, 2): self.rm_background() if opt == 1: click.secho("The event file is needed.", fg='yellow') if not self.data.set_time(): if not self.data.set_bins(): plt.close() self.data.set_periodogram() self.data.plot() self.plot_figure() self.save_image() if click.confirm("Add background file", prompt_suffix='? '): self.plot_background() else: flag = 1 else: flag = 1 elif opt == 2: if not click.confirm( "Select region on the interactive plot"): if not self.data.set_bins(): plt.close() self.data.set_periodogram() self.data.plot() self.plot_figure() self.save_image() if click.confirm("Add background file", prompt_suffix='? '): self.plot_background() else: flag = 1 else: flag2 = 1 click.secho( "The frequency range is needed (Hz).", fg='yellow') self.plot_figure() while flag2: if click.confirm( "Is the region selected", prompt_suffix='? '): axis = plt.gca().get_xlim() self.data.fmin = axis[0] self.data.fmax = axis[1] if click.confirm( "Use oversampling factor", True, prompt_suffix='? '): self.data.set_oversample() self.data.delta = 1 / \ (self.data.oversample * self.data.exposure) else: self.data.set_delta() self.data.get_fmin() self.data.get_fmax() self.data.get_delta() self.data.set_harmonics() block = (self.data.fmax - self.data.fmin) / \ np.array(self.data.delta) nbytes = np.array( self.data.delta).dtype.itemsize * block click.secho( f"Computation memory {nbytes* 10e-6:.5f} MB", fg='yellow') if click.confirm( "Run with these values", True, prompt_suffix='? '): if nbytes < psutil.virtual_memory()[1]: self.data.bins = np.arange( self.data.fmin, self.data.fmax, self.data.delta) self.data.get_bins() plt.close() self.data.set_periodogram() self.data.plot() self.plot_figure() self.save_image() if click.confirm( "Add background file", prompt_suffix='? '): self.plot_background() flag = 0 flag2 = 0 else: flag2 = 1 flag = 1 click.secho( "Not enough memory available.", fg='red') else: flag2 = 1 flag = 1 click.secho( "The frequency range is needed (Hz).", fg='yellow') self.plot_figure() else: flag = 1 click.secho("Select '1' or '2'.", fg='red') return flag def save_image(self) -> None: """Save the image on a file.""" plt.tight_layout() click.secho("Save the periodogram on a image.", fg='yellow') self.set_format() if self.format == 'png': self.set_output() plt.savefig(f'{self.output}.{self.format}', format=self.format) click.secho( f"Image saved at {self.output}.{self.format}", fg='green') elif self.format == 'pdf': self.set_output() plt.savefig(f'{self.output}.{self.format}', format=self.format) click.secho( f"Image saved at {self.output}.{self.format}", fg='green') elif self.format == 'ps': self.set_output() plt.savefig(f'{self.output}.{self.format}', format=self.format) click.secho( f"Image saved at {self.output}.{self.format}", fg='green') elif self.format == 'eps': self.set_output() plt.savefig(f'{self.output}.{self.format}', format=self.format) click.secho( f"Image saved at {self.output}.{self.format}", fg='green') else: click.secho(f"{self.format} format not supported.", fg='red') def change_title(self) -> None: """Change the title on the figure.""" if self.back: self.figure.suptitle(click.prompt( "Which title", "Z2n Periodogram")) click.secho("Changed title.", fg='green') else: self.axes.set_title(click.prompt("Which title", "Z2n Periodogram")) click.secho("Changed title.", fg='green') def change_xlabel(self) -> None: """Change the label on the x axis.""" if self.back: xlabel = click.prompt("Which label", "Frequency (Hz)") self.axes[0].set_xlabel(xlabel) self.axes[1].set_xlabel(xlabel) click.secho("Changed X axis label.", fg='green') else: self.axes.set_xlabel(click.prompt("Which label", "Frequency (Hz)")) click.secho("Changed X axis label.", fg='green') def change_xscale(self) -> None: """Change the scale on the x axis.""" if self.back: self.axes[0].set_xscale(click.prompt( "Which scale [linear, log]", "linear")) click.secho("Changed X axis scale.", fg='green') else: self.axes.set_xscale(click.prompt( "Which scale [linear, log]", "linear")) click.secho("Changed X axis scale.", fg='green') def change_xlim(self) -> None: """Change the limites on the x axis.""" if self.back: low = click.prompt("Which lower limit", type=float) up = click.prompt("Which upper limit", type=float) self.axes[0].set_xlim([low, up]) click.secho("Changed X axis limits.", fg='green') else: low = click.prompt("Which lower limit", type=float) up = click.prompt("Which upper limit", type=float) self.axes.set_xlim([low, up]) click.secho("Changed X axis limits.", fg='green') def change_ylabel(self) -> None: """Change the label on the y axis.""" if self.back: ylabel = click.prompt("Which label", "Power") self.axes[0].set_ylabel(ylabel) self.axes[1].set_ylabel(ylabel) click.secho("Changed y axis label.", fg='green') else: self.axes.set_ylabel(click.prompt("Which label", "Power")) click.secho("Changed y axis label.", fg='green') def change_yscale(self) -> None: """Change the scale on the y axis.""" if self.back: self.axes[0].set_yscale(click.prompt( "Which scale [linear, log]", "linear")) click.secho("Changed y axis scale.", fg='green') else: self.axes.set_yscale(click.prompt( "Which scale [linear, log]", "linear")) click.secho("Changed y axis scale.", fg='green') def change_ylim(self) -> None: """Change the limites on the y axis.""" if self.back: low = click.prompt("Which lower limit", type=float) up = click.prompt("Which upper limit", type=float) self.axes[0].set_ylim([low, up]) click.secho("Changed y axis limits.", fg='green') else: low = click.prompt("Which lower limit", type=float) up = click.prompt("Which upper limit", type=float) self.axes.set_ylim([low, up]) click.secho("Changed y axis limits.", fg='green')
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/z2n/plot.py
plot.py
# Generic/Built-in import psutil import shelve import pathlib import threading # Other Libraries import click import numpy as np from click_shell import shell import matplotlib.pyplot as mplt # Owned Libraries from z2n import file from z2n import stats from z2n import __docs__ from z2n import __version__ from z2n.plot import Plot from z2n.series import Series data = Series() figure = Plot() __z2n__ = f''' Z2n Software ({__version__}), a python package for periodograms analysis. Copyright (C) 2020, and MIT License, by Yohan Alexander [UFS]. Type "help" for more information or "docs" for documentation. ''' __plt__ = f''' Interactive plotting window of the Z2n Software ({__version__}). Type "help" for more information. ''' @click.version_option(prog_name='Z2n Software', version=__version__) @click.option('--docs', 'docs_', is_flag=True, help='Open the documentation and exit.') @click.option('--title', 'title_', type=str, help='Title of the image file.') @click.option( '--ylabel', 'ylabel_', type=str, show_default=True, help='Y label of the image file.', default='Power') @click.option( '--xlabel', 'xlabel_', type=str, show_default=True, help='X label of the image file.', default='Frequency (Hz)') @click.option( '--image', type=click.Choice(['png', 'pdf', 'ps', 'eps']), help='Format of the image file.', default='ps', show_default=True) @click.option( '--format', 'format_', type=click.Choice(['ascii', 'csv', 'fits', 'hdf5']), help='Format of the output file.', default='fits', show_default=True) @click.option( '--ext', type=int, help='FITS extension number.', default=1, show_default=True) @click.option( '--harm', type=int, help='Number of harmonics.', default=1, show_default=True) @click.option( '--over', type=int, help='Oversample factor instead of steps.') @click.option( '--delta', type=float, help='Frequency steps on the spectrum (Hz).') @click.option( '--fmax', type=float, help='Maximum frequency on the spectrum (Hz).') @click.option( '--fmin', type=float, help='Minimum frequency on the spectrum (Hz).') @click.option('--output', 'output_', type=click.Path(), help='Name of the output file.') @click.option( '--input', 'input_', type=click.Path(exists=True), help='Name of the input file.') @shell(prompt=click.style('(z2n) >>> ', fg='blue', bold=True), intro=__z2n__) def z2n(input_, output_, format_, fmin, fmax, delta, over, harm, ext, image, title_, xlabel_, ylabel_, docs_): """ This program allows the user to calculate periodograms, given a time series, using the Z2n statistics a la Buccheri et al. 1983. The standard Z2n statistics calculates the phase of each arrival time and the corresponding sinusoidal functions for each time. Be advised that this is very computationally expensive if the number of frequency bins is high. """ mutex = threading.Lock() mutex.acquire() with shelve.open(f'{pathlib.Path.home()}/.z2n') as database: if docs_: click.launch(__docs__) click.echo(f"To read the documentation go to {__docs__}") exit() if input_: data.harmonics = harm data.input = input_ default = "z2n_" + pathlib.Path(data.input).stem if output_: data.output = output_ else: data.output = default data.format = format_ if not file.load_file(data, ext): click.secho('Event file loaded.', fg='green') data.set_exposure() data.set_sampling() data.set_nyquist() data.get_time() data.get_exposure() data.get_sampling() data.get_nyquist() if not fmin: data.fmin = data.nyquist else: data.fmin = fmin if not fmax: data.set_fmax() else: data.fmax = fmax if not delta and not over: if click.confirm( "Use oversampling factor", True, prompt_suffix='? '): data.set_oversample() data.delta = 1 / (data.oversample * data.exposure) else: data.set_delta() else: if delta: data.delta = delta if over: data.oversample = over data.delta = 1 / (data.oversample * data.exposure) data.get_fmin() data.get_fmax() data.get_delta() data.get_harmonics() block = (data.fmax - data.fmin) / np.array(data.delta) nbytes = np.array(data.delta).dtype.itemsize * block click.secho( f"Computation memory {nbytes* 10e-6:.5f} MB", fg='yellow') if nbytes < psutil.virtual_memory()[1]: data.bins = np.arange(data.fmin, data.fmax, data.delta) data.get_bins() data.time = np.array(data.time) data.bins = np.array(data.bins) data.z2n = np.zeros(data.bins.size) stats.periodogram(data) click.secho('Periodogram calculated.', fg='green') click.secho( "Values based on the global maximum.", fg='yellow') data.set_power() data.set_frequency() data.set_period() data.set_pfraction() data.get_power() data.get_frequency() data.get_period() data.get_pfraction() flag = 1 while flag: if pathlib.Path(f"{data.output}.{data.format}").is_file(): click.secho("File already exists.", fg='red') data.output = click.prompt( "Name of the file", default, type=click.Path()) else: flag = 0 if data.format == 'ascii': file.save_ascii(data) elif data.format == 'csv': file.save_csv(data) elif data.format == 'fits': file.save_fits(data) elif data.format == 'hdf5': file.save_hdf5(data) click.secho( f"File saved at {data.output}.{data.format}", fg='green') flag = 1 while flag: if pathlib.Path(f"{data.output}.{image}").is_file(): click.secho("Image already exists.", fg='red') data.output = click.prompt( "Name of the image", default, type=click.Path()) else: flag = 0 mplt.plot( data.bins, data.z2n, label='Z2n Power', linewidth=2) mplt.title(title_) mplt.xlabel(xlabel_) mplt.ylabel(ylabel_) mplt.legend(loc='best') mplt.tight_layout() if image == 'png': mplt.savefig(f'{data.output}.{image}', format=image) elif image == 'pdf': mplt.savefig(f'{data.output}.{image}', format=image) elif image == 'ps': mplt.savefig(f'{data.output}.{image}', format=image) elif image == 'eps': mplt.savefig(f'{data.output}.{image}', format=image) click.secho( f"Image saved at {data.output}.{image}", fg='green') else: click.secho("Not enough memory available.", fg='red') exit() else: try: figure.data.input = database['input'] figure.data.fmin = database['fmin'] figure.data.fmax = database['fmax'] figure.data.delta = database['delta'] figure.data.oversample = database['oversample'] except KeyError: pass click.echo(__z2n__) if figure.plot_periodogram(): figure.plot_figure() database['input'] = figure.data.input database['fmin'] = figure.data.fmin database['fmax'] = figure.data.fmax database['delta'] = figure.data.delta database['oversample'] = figure.data.oversample mutex.release() @z2n.command() def docs() -> None: """Open the documentation on the software.""" click.launch(__docs__) click.echo(f"To read the documentation go to {__docs__}") @z2n.command() def plot() -> None: """Open the interactive plotting window.""" if figure.data.z2n.size == 0: click.secho("The periodogram was not calculated yet.", fg='yellow') else: figure.plot_figure() plt() @z2n.command() def run() -> None: """Calculate the Z2n Statistics.""" if figure.plot_periodogram(): figure.plot_figure() @z2n.command() def gauss() -> None: """Select the fit of a gaussian curve.""" if figure.data.z2n.size == 0: click.secho("The periodogram was not calculated yet.", fg='yellow') else: figure.data.plot() @z2n.command() def save() -> None: """Save the periodogram on a file.""" if figure.data.z2n.size == 0: click.secho("The periodogram was not calculated yet.", fg='yellow') else: figure.data.save_file() @shell(prompt=click.style('(plt) >>> ', fg='magenta', bold=True), intro=__plt__) def plt() -> None: """Open the interactive periodogram plotting window.""" @plt.command() def title() -> None: """Change the title on the figure.""" figure.change_title() @plt.command() def xlabel() -> None: """Change the label on the x axis.""" figure.change_xlabel() @plt.command() def xscale() -> None: """Change the scale on the x axis.""" figure.change_xscale() @plt.command() def xlim() -> None: """Change the limites on the x axis.""" figure.change_xlim() @plt.command() def ylabel() -> None: """Change the label on the y axis.""" figure.change_ylabel() @plt.command() def yscale() -> None: """Change the scale on the y axis.""" figure.change_yscale() @plt.command() def ylim() -> None: """Change the limites on the y axis.""" figure.change_ylim() @plt.command() def save() -> None: """Save the image on a file.""" figure.save_image()
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/z2n/prompt.py
prompt.py
# Generic/Built-in import pathlib # Other Libraries import click import numpy as np from astropy.io import fits from astropy.table import Table def load_file(series, ext) -> int: """ Open file and store time series. Parameters ---------- series : Series A time series object. Returns ------- None """ flag = 0 suffix = pathlib.Path(series.input).suffix if suffix in ("", ".txt"): flag = load_ascii(series) elif suffix in (".csv", ".ecsv"): flag = load_csv(series) elif suffix in (".hdf", ".h5", ".hdf5", ".he5"): flag = load_hdf5(series) else: with fits.open(series.input) as events: try: events['Z2N'] click.secho('Z2N extension already found', fg='yellow') if click.confirm('Use the periodogram', prompt_suffix='? '): series.bins = events['Z2N'].data['FREQUENCY'] series.bins = series.bins.astype(series.bins.dtype.name) series.z2n = events['Z2N'].data['POWER'] series.z2n = series.z2n.astype(series.z2n.dtype.name) hdr = events['Z2N'].header series.exposure = float(hdr['exposure']) series.sampling = float(hdr['sampling']) series.nyquist = float(hdr['nyquist']) series.harmonics = int(hdr['harmonic']) series.fmin = float(hdr['fmin']) series.fmax = float(hdr['fmax']) series.delta = float(hdr['delta']) series.frequency = float(hdr['peak']) series.period = float(hdr['period']) series.power = float(hdr['power']) series.pulsed = float(hdr['pulsed']) click.secho(f"{hdr['events']} events.", fg='cyan') series.get_exposure() series.get_sampling() series.get_nyquist() series.get_fmin() series.get_fmax() series.get_delta() series.get_bins() series.get_harmonics() series.get_frequency() series.get_period() series.get_power() series.get_pfraction() series.set_gauss() series.set_bak() load_fits(series, ext) flag = 1 else: flag = load_fits(series, ext) except KeyError: flag = load_fits(series, ext) return flag def load_ascii(series) -> int: """ Open ascii file and store time series. Parameters ---------- series : Series A time series object. Returns ------- None """ flag = 1 table = Table.read(series.input, format='ascii') try: series.time = table['TIME'].data series.time = series.time.astype(series.time.dtype.name) flag = 0 except (KeyError, TypeError, IndexError): click.clear() column = 'TIME' flag = 1 while flag: try: table.pprint() click.secho(f"Column {column} not found.", fg='red') column = click.prompt( "Which column name", type=str, prompt_suffix='? ') series.time = table[column].data series.time = series.time.astype(series.time.dtype.name) if click.confirm(f"Use column {column}", prompt_suffix='? '): flag = 0 else: click.clear() except (KeyError, TypeError, IndexError): click.clear() return flag def load_csv(series) -> int: """ Open csv file and store time series. Parameters ---------- series : Series A time series object. Returns ------- None """ flag = 1 table = Table.read(series.input, format='csv') try: series.time = table['TIME'].data series.time = series.time.astype(series.time.dtype.name) flag = 0 except (KeyError, TypeError, IndexError): click.clear() column = 'TIME' flag = 1 while flag: try: table.pprint() click.secho(f"Column {column} not found.", fg='red') column = click.prompt( "Which column name", type=str, prompt_suffix='? ') series.time = table[column].data series.time = series.time.astype(series.time.dtype.name) if click.confirm(f"Use column {column}", prompt_suffix='? '): flag = 0 else: click.clear() except (KeyError, TypeError, IndexError): click.clear() return flag def load_fits(series, ext) -> None: """ Open fits file and store time series. Parameters ---------- series : Series A time series object. Returns ------- None """ flag = 0 times = 0 columns = ['TIME', 'time'] extensions = [] with fits.open(series.input) as events: if ext: try: series.time = events[ext].data['TIME'] series.time = series.time.astype(series.time.dtype.name) click.secho( f"Column TIME in {events[ext].name}.", fg='yellow') flag = 0 except (KeyError, TypeError): flag = 1 click.secho( f"Column TIME not found in {events[ext].name}.", fg='red') except IndexError: flag = 1 click.secho( f"Extension number {ext} not found.", fg='red') else: for hdu in range(1, len(events)): try: if any(column in events[hdu].columns.names for column in columns): extensions.append(hdu) times += 1 except AttributeError: pass if times == 1: click.secho( f"Column TIME in {events[extensions[0]].name}.", fg='yellow') series.time = events[extensions[0]].data['TIME'] series.time = series.time.astype(series.time.dtype.name) flag = 0 elif times > 1: click.secho("Multiple columns TIME found.", fg='yellow') flag = 1 while flag: table = Table( names=('Number', 'Extension', 'Length (Rows)'), dtype=('int64', 'str', 'int64')) for value in extensions: table.add_row([ value, events[value].name, events[value].data['TIME'].size]) table.pprint() number = click.prompt( "Which extension number", type=int, prompt_suffix='? ') try: if click.confirm(f"Use column in {events[number].name}"): series.time = events[number].data['TIME'] series.time = series.time.astype( series.time.dtype.name) flag = 0 break else: flag = 1 click.clear() except (KeyError, TypeError): flag = 1 click.clear() click.secho( f"Column TIME not found in {events[number].name}.", fg='red') except IndexError: flag = 1 click.clear() click.secho( f"Extension number {number} not found.", fg='red') else: click.clear() column = 'TIME' flag = 1 while flag: hdu = 1 while hdu < len(events): table = Table(events[hdu].data) table.pprint() click.secho( f"Column {column} not found in extension.", fg='red') click.secho( f"Extension {events[hdu].name}.", fg='yellow') if click.confirm("Use extension [y] or go to next [n]"): try: column = click.prompt( "Which column name", type=str, prompt_suffix='? ') series.time = events[hdu].data[column] series.time = series.time.astype( series.time.dtype.name) if click.confirm( f"Use column {column}", prompt_suffix='? '): flag = 0 break else: flag = 1 click.clear() except (KeyError, TypeError): flag = 1 click.clear() except IndexError: flag = 1 click.clear() click.secho( f"Extension number {hdu} not found.", fg='red') else: flag = 1 hdu += 1 click.clear() return flag def load_hdf5(series) -> int: """ Open hdf5 file and store time series. Parameters ---------- series : Series A time series object. Returns ------- None """ flag = 1 table = Table.read(series.input, format='hdf5') try: series.time = table['TIME'].data series.time = series.time.astype(series.time.dtype.name) flag = 0 except (KeyError, TypeError, IndexError): click.clear() column = 'TIME' flag = 1 while flag: try: table.pprint() click.secho(f"Column {column} not found.", fg='red') column = click.prompt( "Which column name", type=str, prompt_suffix='? ') series.time = table[column].data series.time = series.time.astype(series.time.dtype.name) if click.confirm(f"Use column {column}", prompt_suffix='? '): flag = 0 else: click.clear() except (KeyError, TypeError, IndexError): click.clear() return flag def save_ascii(series) -> None: """ Save the periodogram to ascii file. Parameters ---------- series : Series A time series object. Returns ------- None """ array = np.column_stack((series.bins, series.z2n)) table = Table(array, names=('FREQUENCY', 'POWER')) table.write(f'{series.output}.txt', format='ascii') def save_csv(series) -> None: """ Save the periodogram to csv file. Parameters ---------- series : Series A time series object. Returns ------- None """ array = np.column_stack((series.bins, series.z2n)) table = Table(array, names=('FREQUENCY', 'POWER')) table.write(f'{series.output}.csv', format='csv') def save_fits(series) -> None: """ Save the periodogram to fits file. Parameters ---------- series : Series A time series object. Returns ------- None """ suffix = pathlib.Path(series.input).suffix if suffix in ("", ".txt", ".csv", ".ecsv", ".hdf", ".h5", ".hdf5", ".he5"): primary_hdu = fits.PrimaryHDU() bins = fits.Column( name='FREQUENCY', array=series.bins, format='D', unit='Hz') z2n = fits.Column(name='POWER', array=series.z2n, format='D') hdr = fits.Header() hdr['EXTNAME'] = 'Z2N' hdr.comments['EXTNAME'] = 'Name of this extension' hdr['HDUNAME'] = 'Z2N' hdr.comments['HDUNAME'] = 'Name of the hdu' hdr['events'] = f'{series.time.size}' hdr.comments['events'] = 'Number of events' hdr['exposure'] = f'{series.exposure}' hdr.comments['exposure'] = 'Exposure time (Texp)' hdr['sampling'] = f'{series.sampling}' hdr.comments['sampling'] = 'Sampling rate (1/Texp)' hdr['nyquist'] = f'{series.nyquist}' hdr.comments['nyquist'] = 'Nyquist 2*(1/Texp)' hdr['harmonic'] = f'{series.harmonics}' hdr.comments['harmonic'] = 'Number of harmonics' hdr['steps'] = f'{series.z2n.size}' hdr.comments['steps'] = 'Number of steps' hdr['fmin'] = f'{series.fmin}' hdr.comments['fmin'] = 'Minimum frequency' hdr['fmax'] = f'{series.fmax}' hdr.comments['fmax'] = 'Maximum frequency' hdr['delta'] = f'{series.delta}' hdr.comments['delta'] = 'Frequency steps' hdr['peak'] = f'{series.frequency}' hdr.comments['peak'] = 'Global peak frequency' hdr['period'] = f'{series.period}' hdr.comments['period'] = 'Global peak period' hdr['power'] = f'{series.power}' hdr.comments['power'] = 'Global peak power' hdr['pulsed'] = f'{series.pulsed}' hdr.comments['pulsed'] = 'Global pulsed fraction' try: hdr['gpeak'] = f'{series.gauss.frequency}' hdr.comments['gpeak'] = 'Gauss peak frequency' hdr['gperiod'] = f'{series.gauss.period}' hdr.comments['gperiod'] = 'Gauss peak period' hdr['gpower'] = f'{series.gauss.power}' hdr.comments['gpower'] = 'Gauss peak power' hdr['gpulsed'] = f'{series.gauss.pulsed}' hdr.comments['gpulsed'] = 'Gauss pulsed fraction' except AttributeError: pass table_hdu = fits.BinTableHDU.from_columns([bins, z2n], header=hdr) hdul = fits.HDUList([primary_hdu, table_hdu]) hdul.writeto(f'{series.output}.fits') else: with fits.open(series.input) as events: bins = fits.Column( name='FREQUENCY', array=series.bins, format='D', unit='Hz') z2n = fits.Column(name='POWER', array=series.z2n, format='D') hdr = fits.Header() hdr['EXTNAME'] = 'Z2N' hdr.comments['EXTNAME'] = 'Name of this extension' hdr['HDUNAME'] = 'Z2N' hdr.comments['HDUNAME'] = 'Name of the hdu' hdr['events'] = f'{series.time.size}' hdr.comments['events'] = 'Number of events' hdr['exposure'] = f'{series.exposure}' hdr.comments['exposure'] = 'Exposure time (Texp)' hdr['sampling'] = f'{series.sampling}' hdr.comments['sampling'] = 'Sampling rate (1/Texp)' hdr['nyquist'] = f'{series.nyquist}' hdr.comments['nyquist'] = 'Nyquist 2*(1/Texp)' hdr['harmonic'] = f'{series.harmonics}' hdr.comments['harmonic'] = 'Number of harmonics' hdr['steps'] = f'{series.z2n.size}' hdr.comments['steps'] = 'Number of steps' hdr['fmin'] = f'{series.fmin}' hdr.comments['fmin'] = 'Minimum frequency' hdr['fmax'] = f'{series.fmax}' hdr.comments['fmax'] = 'Maximum frequency' hdr['delta'] = f'{series.delta}' hdr.comments['delta'] = 'Frequency steps' hdr['peak'] = f'{series.frequency}' hdr.comments['peak'] = 'Global peak frequency' hdr['period'] = f'{series.period}' hdr.comments['period'] = 'Global peak period' hdr['power'] = f'{series.power}' hdr.comments['power'] = 'Global peak power' hdr['pulsed'] = f'{series.pulsed}' hdr.comments['pulsed'] = 'Global pulsed fraction' try: hdr['gpeak'] = f'{series.gauss.frequency}' hdr.comments['gpeak'] = 'Gauss peak frequency' hdr['gperiod'] = f'{series.gauss.period}' hdr.comments['gperiod'] = 'Gauss peak period' hdr['gpower'] = f'{series.gauss.power}' hdr.comments['gpower'] = 'Gauss peak power' hdr['gpulsed'] = f'{series.gauss.pulsed}' hdr.comments['gpulsed'] = 'Gauss pulsed fraction' except AttributeError: pass hdu = fits.BinTableHDU.from_columns([bins, z2n], header=hdr) events.append(hdu) events.writeto(f'{series.output}.fits') def save_hdf5(series) -> None: """ Save the periodogram to hdf5 file. Parameters ---------- series : Series A time series object. Returns ------- None """ array = np.column_stack((series.bins, series.z2n)) table = Table(array, names=('FREQUENCY', 'POWER')) table.write(f'{series.output}.hdf5', path='z2n', format='hdf5', compression=True)
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/z2n/file.py
file.py
# Generic/Built-in import sys import copy import psutil import pathlib import tempfile # Other Libraries import h5py import click import termtables import numpy as np import matplotlib.pyplot as plt # Owned Libraries from z2n import file from z2n import stats class Series: """ A class to represent a time series object. Attributes ---------- * `bak : str` > A string that represents the backup file path. * `gauss : str` > A series object that represents the gaussian fit. * `input : str` > A string that represents the input file path. * `output : str` > A string that represents the output file name. * `format : str` > A string that represents the file format. * `time : np.array` > An arrray that represents the time series. * `bins : np.array` > An arrray that represents the frequency bins. * `z2n : np.array` > An arrray that represents the periodogram. * `harmonics : int` > An integer that represents the number of harmonics. * `oversample : int` > An integer that represents the oversample factor. * `fmin : float` > A float that represents the minimum frequency. * `fmax : float` > A float that represents the maximum frequency. * `delta : float` > A float that represents the frequency steps. * `nyquist : float` > A float that represents the nyquist frequency. * `exposure : float` > A float that represents the exposure period. * `sampling : float` > A float that represents the sampling rate. * `power : float` > A float that represents the peak power. * `frequency : float` > A float that represents the peak frequency. * `period : float` > A float that represents the peak period. * `errorf : float` > A float that represents the frequency uncertainty. * `errorp : float` > A float that represents the period uncertainty. * `pulsed : float` > A float that represents the pulsed fraction. Methods ------- """ def __init__(self) -> None: self.bak = "" self.gauss = "" self.input = "" self.output = "" self.format = "" self.time = np.array([]) self.bins = np.array([]) self.z2n = np.array([]) self.fmin = 0 self.fmax = 0 self.delta = 0 self.nyquist = 0 self.harmonics = 0 self.oversample = 0 self.exposure = 0 self.sampling = 0 self.power = 0 self.frequency = 0 self.errorf = 0 self.period = 0 self.errorp = 0 self.pulsed = 0 def get_gauss(self) -> str: """Return the gaussian series object.""" return self.gauss def set_gauss(self) -> None: """Copy the gaussian series object.""" self.gauss = copy.deepcopy(self) def get_bak(self) -> str: """Return the backup file path.""" click.secho(f"Path of the backup: {self.bak}", fg='cyan') return self.bak def set_bak(self) -> None: """Change the backup file path.""" self.bak = tempfile.NamedTemporaryFile( suffix='.z2n', delete=False).name self.bak = h5py.File(self.bak, 'a') self.bak.create_dataset('TIME', data=self.time, compression='lzf') self.bak.create_dataset('BINS', data=self.bins, compression='lzf') self.bak.create_dataset('Z2N', data=self.z2n, compression='lzf') del self.time del self.bins del self.z2n self.time = self.bak['TIME'] self.bins = self.bak['BINS'] self.z2n = self.bak['Z2N'] def get_input(self) -> str: """Return the input file path.""" click.secho(f"Event file: {self.input}", fg='cyan') return self.input def set_input(self) -> None: """Change the input file path.""" self.input = click.prompt( "\nFilename", self.input, type=click.Path(exists=True)) def get_output(self) -> str: """Return the output file name.""" click.secho(f"Output file: {self.output}", fg='cyan') return self.output def set_output(self) -> None: """Change the output file name.""" default = "z2n_" + pathlib.Path(self.input).stem flag = 1 while flag: self.output = click.prompt( "\nName of the file", default, type=click.Path()) if pathlib.Path(f"{self.output}.{self.format}").is_file(): click.secho("File already exists.", fg='red') else: flag = 0 def get_format(self) -> str: """Return the file format.""" click.secho(f"File format: {self.format}", fg='cyan') return self.format def set_format(self) -> None: """Change the file format.""" self.format = click.prompt( "\nFormat", "fits", type=click.Choice(['ascii', 'csv', 'fits', 'hdf5'])) def get_time(self) -> np.array: """Return the time series.""" click.secho(f"{self.time.size} events.", fg='cyan') return self.time def set_time(self) -> int: """Change the time series.""" flag = 0 self.set_input() if not file.load_file(self, 0): click.secho('Event file loaded.', fg='green') self.set_exposure() self.set_sampling() self.set_nyquist() self.get_time() self.get_exposure() self.get_sampling() self.get_nyquist() else: flag = 1 return flag def get_bins(self) -> np.array: """Return the frequency steps.""" click.secho(f"{self.bins.size} steps.", fg='cyan') return self.bins def set_bins(self) -> int: """Change the frequency steps.""" flag = 1 while flag: click.secho("The frequency range is needed (Hz).", fg='yellow') if click.confirm( "\nNyquist as the minimum frequency", True, prompt_suffix='? '): self.fmin = self.nyquist else: self.set_fmin() self.set_fmax() if click.confirm( "\nUse oversampling factor", True, prompt_suffix='? '): self.set_oversample() self.delta = 1 / (self.oversample * self.exposure) else: self.set_delta() self.get_fmin() self.get_fmax() self.get_delta() self.set_harmonics() block = (self.fmax - self.fmin) / np.array(self.delta) nbytes = np.array(self.delta).dtype.itemsize * block click.secho( f"Computation memory {nbytes* 10e-6:.5f} MB", fg='yellow') if click.confirm("\nRun with these values", True, prompt_suffix='? '): if nbytes < psutil.virtual_memory()[1]: self.bins = np.arange(self.fmin, self.fmax, self.delta) self.get_bins() flag = 0 else: click.secho("Not enough memory available.", fg='red') return flag def get_periodogram(self) -> np.array: """Return the periodogram.""" click.secho(f"{self.z2n.size} steps.", fg='cyan') return self.z2n def set_periodogram(self) -> None: """Change the periodogram.""" self.bak = "" self.time = np.array(self.time) self.bins = np.array(self.bins) self.z2n = np.zeros(self.bins.size) stats.periodogram(self) click.secho('Periodogram calculated.', fg='green') self.set_gauss() def get_nyquist(self) -> float: """Return the nyquist frequency.""" click.secho( f"Nyquist 2*(1/Texp): {self.nyquist:.1e} Hz", fg='cyan') return self.nyquist def set_nyquist(self) -> None: """Change the nyquist frequency.""" self.nyquist = 2 * self.sampling def get_fmin(self) -> float: """Return the minimum frequency.""" click.secho(f"\nMinimum frequency: {self.fmin:.1e} Hz", fg='cyan') return self.fmin def set_fmin(self) -> None: """Change the minimum frequency.""" self.fmin = click.prompt( "\nMinimum frequency (Hz)", self.fmin, type=float) def get_fmax(self) -> float: """Return the maximum frequency.""" click.secho(f"Maximum frequency: {self.fmax:.1e} Hz", fg='cyan') return self.fmax def set_fmax(self) -> None: """Change the maximum frequency.""" self.fmax = click.prompt( "\nMaximum frequency (Hz)", self.fmax, type=float) def get_delta(self) -> float: """Return the frequency steps.""" click.secho(f"Frequency steps: {self.delta:.1e} Hz\n", fg='cyan') return self.delta def set_delta(self) -> None: """Change the frequency steps.""" self.delta = click.prompt( "\nFrequency steps (Hz)", self.delta, type=float) def get_oversample(self) -> int: """Return the oversample factor.""" click.secho(f"Oversampling factor: {self.oversample}", fg='cyan') return self.oversample def set_oversample(self) -> None: """Change the oversample factor.""" self.oversample = click.prompt( "\nOversampling factor", self.oversample, type=int) def get_harmonics(self) -> int: """Return the number of harmonics.""" click.secho(f"Number of harmonics: {self.harmonics}", fg='cyan') return self.harmonics def set_harmonics(self) -> None: """Change the number of harmonics.""" self.harmonics = click.prompt("\nNumber of harmonics", 1, type=int) def get_exposure(self) -> float: """Return the period of exposure.""" click.secho(f"Exposure time (Texp): {self.exposure:.1f} s", fg='cyan') return self.exposure def set_exposure(self) -> None: """Change the period of exposure.""" stats.exposure(self) def get_sampling(self) -> float: """Return the sampling rate.""" click.secho( f"Sampling rate (1/Texp): {self.sampling:.1e} Hz", fg='cyan') return self.sampling def set_sampling(self) -> None: """Change the sampling rate.""" stats.sampling(self) def get_power(self) -> float: """Return the peak power.""" click.secho(f"Peak power: {self.power}", fg='cyan') return self.power def set_power(self) -> None: """Change the peak power.""" stats.power(self) def get_frequency(self) -> float: """Return the peak frequency.""" click.secho(f"Peak frequency: {self.frequency} Hz", fg='cyan') return self.frequency def set_frequency(self) -> None: """Change the peak frequency.""" stats.frequency(self) def get_period(self) -> float: """Return the peak period.""" click.secho(f"Peak period: {self.period} s", fg='cyan') return self.period def set_period(self) -> None: """Change the peak period.""" stats.period(self) def get_pfraction(self) -> float: """Return the pulsed fraction.""" click.secho(f"Pulsed fraction: {self.pulsed * 100} %", fg='cyan') return self.pulsed def set_pfraction(self) -> None: """Change the pulsed fraction.""" stats.pfraction(self) def get_errorf(self) -> float: """Return the uncertainty of the frequency.""" click.secho(f"Frequency Uncertainty: +/- {self.errorf} Hz", fg='cyan') return self.errorf def set_errorf(self) -> None: """Return the uncertainty of the frequency.""" stats.error(self) def get_errorp(self) -> float: """Return the uncertainty of the period.""" click.secho(f"Period Uncertainty: +/- {self.errorp} s", fg='cyan') return self.errorp def set_errorp(self) -> None: """Return the uncertainty of the period.""" stats.error(self) def load_file(self) -> int: """Load a input file.""" flag = 0 self.set_format() if self.format == 'ascii': self.set_input() file.load_ascii(self) elif self.format == 'csv': self.set_input() file.load_csv(self) elif self.format == 'fits': self.set_input() file.load_fits(self, 0) elif self.format == 'hdf5': self.set_input() file.load_hdf5(self) else: click.secho(f"{self.format} format not supported.", fg='red') flag = 1 return flag def save_file(self) -> None: """Save a output file.""" click.secho("Save the periodogram on a file.", fg='yellow') self.set_format() if self.format == 'ascii': self.set_output() file.save_ascii(self) click.secho(f"File saved at {self.output}.txt", fg='green') elif self.format == 'csv': self.set_output() file.save_csv(self) click.secho( f"File saved at {self.output}.{self.format}", fg='green') elif self.format == 'fits': self.set_output() file.save_fits(self) click.secho( f"File saved at {self.output}.{self.format}", fg='green') elif self.format == 'hdf5': self.set_output() file.save_hdf5(self) click.secho( f"File saved at {self.output}.{self.format}", fg='green') else: click.secho(f"{self.format} format not supported.", fg='red') def plot(self) -> None: """Plot the series and the parameters.""" flag = 1 while flag: plt.close() plt.ion() plt.plot(self.bins, self.z2n, label='Z2n Power', linewidth=2) plt.xlabel('Frequency (Hz)') plt.ylabel('Power') plt.legend(loc='best') plt.tight_layout() try: stats.error(self) header = ["", "Z2N POWER", "GAUSSIAN FIT"] data = [ ["Power", f"{self.power}", f"{self.gauss.power}"], ["Frequency", f"{self.frequency} Hz", f"{self.gauss.frequency} Hz"], ["Frequency error", "_", f"+/- {self.gauss.errorf} Hz"], ["Period", f"{self.period} s", f"{self.gauss.period} s"], ["Period error", "_", f"+/- {self.gauss.errorp} s"], ["Pulsed Fraction", f"{self.pulsed* 100} %", f"{self.gauss.pulsed* 100} %"], ] termtables.print(data, header) plt.close() plt.ion() plt.plot(self.bins, self.z2n, label='Z2n Power', linewidth=2) plt.plot( self.gauss.bins, self.gauss.z2n, color='tab:red', label='Gaussian Fit', linewidth=1) plt.xlabel('Frequency (Hz)') plt.ylabel('Power') plt.legend(loc='best') plt.tight_layout() except IndexError: click.secho("Error on the selection.", fg='red') else: if not click.confirm("Select another region for the fit"): self.save_file() flag = 0 click.secho("Save the results on a log file.", fg='yellow') default = "z2n_" + pathlib.Path(self.input).stem flag2 = 1 while flag2: log = click.prompt( "\nName of the file", default, type=click.Path()) if pathlib.Path(f"{log}.log").is_file(): click.secho("File already exists.", fg='red') else: flag2 = 0 with open(f"{log}.log", "w+") as logfile: sys.stdout = logfile self.get_input() self.get_output() self.get_format() self.get_time() self.get_exposure() self.get_sampling() self.get_nyquist() self.get_fmin() self.get_fmax() self.get_delta() self.get_bins() self.get_harmonics() click.secho("Periodogram values.", fg='yellow') self.get_power() self.get_frequency() self.get_period() self.get_pfraction() click.secho("Gaussian values.", fg='yellow') self.gauss.get_power() self.gauss.get_frequency() self.gauss.get_errorf() self.gauss.get_period() self.gauss.get_errorp() self.gauss.get_pfraction() sys.stdout = sys.__stdout__ click.secho( f"Saved the results at {log}.log", fg='green')
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/z2n/series.py
series.py
# The Core computation on the software The $`Z^2_n`$ Software was designed to the be both simple to use by the available command line interface, and yet very fast on perfoming the power spectrum computation. The speed is achieved by the union of 3 methods: * [Vectorizing operations](https://en.wikipedia.org/wiki/Array_programming) * [Parallel threads](https://en.wikipedia.org/wiki/Parallel_computing) * [Compilation to assembly code](https://numba.pydata.org/) Keep in mind the pseudocode for the algorithm of the $`Z^2_N`$ power computation: ```bash function PERIODOGRAM(T[N], F[M]) Input: T[N]: array with photon arrival times Input: F[M]: array with frequency spectrum for i = 0 to M − 1 do - compute Z2n power for each frequency for j = 0 to N − 1 do - compute phase for each photon arrival time ϕj = T[j] * F[i] ϕj = ϕj - ⌊ϕj⌋ sines[j] = SIN(2π * ϕj) cosines[j] = COS(2π * ϕj) end for sin = SUM(sines) cos = SUM(cosines) Z2n[j] = sin**2 + cos**2 end for Z2n[j] = Z2n * (2/LEN(T)) return Z2n end function ``` ```math Z^2_n = \frac{2}{N} \cdot \sum_{k=1}^{n} [(\sum_{j=1}^{N} cos(k\phi_j)) ^ 2 + (\sum_{j=1}^{N} sin(k\phi_j)) ^ 2] ``` Each result on the power spectrum will be obtained by the computation of the following graph. There are two different subtrees on the computation graph, both can be executed in parallel on different threads. ![vector](https://user-images.githubusercontent.com/39287022/86088759-52242400-ba7d-11ea-9e34-f7cd0d45071f.png) # Vectorization Besides the parallel threads, the operations on each blue node encapsulate the full range of the photon arrival times, therefore can be vectorized as shown on the following graph. ![array](https://user-images.githubusercontent.com/39287022/86088427-b5fa1d00-ba7c-11ea-9693-6352b81c1f66.png) # Parallel Loops The resulting power spectrum will be the blue node on the following graph, that is the product of the parallel computation of many threads (according to the processor CPU) each of a different frequency graph. ![paralelo](https://user-images.githubusercontent.com/39287022/86088434-ba263a80-ba7c-11ea-8c73-6bc8fb7853eb.png) # Compilation The process of compiling the `Python` source code into machine code (assembly x86) optimized for each function is achieved by the `Numba` JIT (just-in-time) compiler, with the available decorators for wrapping functions. Taking advantage of this process makes it easy to avoid the GIL (global interpreter lock) of the `Python` language.
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/performance.md
performance.md
# Welcome to the Z2n Periodogram Documentation [![PyPI](https://img.shields.io/pypi/v/z2n-periodogram)](https://pypi.org/project/z2n-periodogram/) [![GitHub issues](https://img.shields.io/github/issues/yohanalexander/z2n-periodogram)](https://github.com/yohanalexander/z2n-periodogram/issues) [![GitHub](https://img.shields.io/github/license/yohanalexander/z2n-periodogram)](https://github.com/YohanAlexander/z2n-periodogram/blob/master/LICENSE) [![Documentation Status](https://readthedocs.org/projects/z2n-periodogram/badge/?version=latest)](https://z2n-periodogram.readthedocs.io/en/latest/?badge=latest) <br> <p align="center"> <a href="https://github.com/yohanalexander/z2n-periodogram"> <img src="https://user-images.githubusercontent.com/39287022/84617670-23675480-aea6-11ea-90ac-93a32c01bb92.png" alt="Logo" width="50%" height="50%"> </a> <h1 align="center">Z2n Periodogram</h1> <p align="center"> A package for interative periodograms analysis! ## Table of Contents * [About the Project](/about) * [Built with](/about/#built-with) * [The core computation](/performance) * [Getting Started](/install) * [Prerequesites](/install/#prerequesites) * [Installation](/install/#installation) * [Known Issues](/install/#known-issues) * [Usage](/input) * [Importing datasets](/input) * [Using from the terminal](/usage) * [Plotting the periodogram](/plotting) * [Determining uncertainty](/statistics) * [API](/series) * [The Time Series Object](/series) * [The Plot Figure Object](/plot) * [Contributing](/contribute) * [Roadmap](/contribute#roadmap) * [License](/copyright)
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/index.md
index.md
# Copyright All content © 2020 Yohan Alexander. Distributed under the MIT License. See <a href="https://github.com/YohanAlexander/z2n-periodogram/blob/master/LICENSE">LICENSE</a> for more information. !!! Note MIT License Copyright (c) 2020 Yohan Alexander Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/copyright.md
copyright.md
# Command Line Interface Currently there are 2 alternatives provided to interact with the core of the $`Z^2_n`$ Software: * Passing the desired parameters directly on the terminal as [arguments](#passing-arguments-on-the-terminal). * Or by a command line interface `CLI`. To start the interface just type `z2n` on the terminal (check if you're under the virtual environment that it is installed). The `CLI` of the software is very interactive and it works by triggering the commands available, for more information on the usage type `help`. ```bash z2n Z2n Software, a package for interactive periodograms analysis. Copyright (C) 2020, and MIT License, by Yohan Alexander [UFS]. Type "help" for more information or "docs" for documentation. (z2n) >>> help Documented commands (type help <topic>): ======================================== docs gauss plot run save Undocumented commands: ====================== exit help quit (z2n) >>> ``` # Passing arguments on the terminal To get all available arguments and their correct use, just type `z2n --help` on the terminal (check if you're under the virtual environment that it is installed). ```bash z2n --help Usage: z2n [OPTIONS] COMMAND [ARGS]... This program allows the user to calculate periodograms, given a time series, using the Z2n statistics a la Buccheri et al. 1983. The standard Z2n statistics calculates the phase of each arrival time and the corresponding sinusoidal functions for each time. Be advised that this is very computationally expensive if the number of frequency bins is high. Options: --input PATH Name of the input file. --output PATH Name of the output file. --fmin FLOAT Minimum frequency on the spectrum (Hz). --fmax FLOAT Maximum frequency on the spectrum (Hz). --delta FLOAT Frequency steps on the spectrum (Hz). --over INTEGER Oversample factor instead of steps. --harm INTEGER Number of harmonics. [default: 1] --ext INTEGER FITS extension number. [default: 1] --format [ascii|csv|fits|hdf5] Format of the output file. [default: fits] --image [png|pdf|ps|eps] Format of the image file. [default: ps] --xlabel TEXT X label of the image file. [default: Frequency (Hz)] --ylabel TEXT Y label of the image file. [default: Power] --title TEXT Title of the image file. --docs Open the documentation and exit. --version Show the version and exit. --help Show this message and exit. Commands: docs Open the documentation on the software. gauss Select the fit of a gaussian curve. plot Open the interactive plotting window. run Calculate the Z2n Statistics. save Save the periodogram on a file. ``` # Colors on the terminal If available on your terminal emulator, the $`Z^2_n`$ software uses colors for providing better insight on the current status of the program execution. !!! Important * **Sucess** Any time the program sucessfully executes a task, it will indicate with the color <strong style="color:green">green.</strong> !!! Warning * **Warnings** Any time the program is waiting to execute a task, it will indicate with the color <strong style="color:yellow">yellow.</strong> !!! Error * **Errors** Any time the program encouters errors during a task, it will indicate with the color <strong style="color:red">red.</strong> !!! Note * **Output** Any time the program outputs a important value, it will indicate with the color <strong style="color:cyan">cyan.</strong>
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/usage.md
usage.md
# Importing data to the program The $`Z^2_n`$ a la Buccheri et al. 1983 takes as input the arrival times of photons detected by telescopes. Therefore the program uses as input an event file with a dataset representing these values, stored on a collum named `TIME`. | TIME | |:----:| | 1 | | 2 | | 3 | | 4 | | 5 | | ... | The software currently supports the following file formats: * ascii * csv * [fits](https://fits.gsfc.nasa.gov/) * [hdf5](https://www.hdfgroup.org/solutions/hdf5/)
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/input.md
input.md
# Determining uncertainty The $`Z^2_n`$ Software provides an estimative of uncertainty on the selected peak region, based on the $`\sigma`$ of a gaussian like $`g(x)`$, function that is fitted with the least-squares method. The best fit in the least-squares sense minimizes the sum of squared residuals (a residual being: the difference between an observed value, and the fitted value provided by a model). ```math \LARGE g(x) = {\mathrm{e}^{-\frac{(x - \overline{x}) ^ 2}{2 \cdot \sigma ^ 2}}} ``` The complete process can be visualized on the next figure: ![rxjfit](https://user-images.githubusercontent.com/39287022/86081335-81319a00-ba6b-11ea-9328-b5cd245256af.png) The bandwith limited by the estimated uncertainty would look like this: ![rxjband](https://user-images.githubusercontent.com/39287022/86081541-00bf6900-ba6c-11ea-9951-3be8dd34d4be.png) # Pulsed Fraction The $`Z^2_n`$ Software also provides the estimative of the pulsed fraction on the selected peak region, given by the equation wich is defined as follows. ```math \Large f_p (\%) = (2 \cdot \frac{Z^2_n}{N}) ^ \frac{1}{2} ```
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/statistics.md
statistics.md
# How to contribute? Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ## Roadmap See the [open issues](https://github.com/yohanalexander/z2n-periodogram/issues) for a list of proposed features (and known issues).
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/contribute.md
contribute.md
# Prerequisites The version of the `Python` interpreter used during the development was the `3.7`, which can be managed in virtual environments such as [Anaconda](https://docs.conda.io/en/latest/index.html). Therefore, try to use the same or above versions for the best compatibility. * Python>=3.7 * PIP ## Installation The software is currently hosted at the `Python` central repository [PyPI](https://pypi.org/project/z2n-periodogram/), to install the software properly use the command on the terminal: ```bash pip install -U z2n-periodogram ``` ## Known Issues !!! Warning To create an interactive plotting window (where the user is able to select regions on the power spectrum) this package requires the bult-in python module [Tkinter](https://docs.python.org/3/library/tkinter.html). Although the module should arrive with any **Python** installation, it may be missing. In that case, a manual installation of the module will be required. The module is available on the package managers of the major **linux** distributions. For **debian** based distros: ``` $ sudo apt install python3-tk ``` For **fedora** based distros: ``` $ sudo dnf install python3-tkinter ``` For **arch** based distros: ``` $ sudo pacman -S tk ``` For other systems consult the avaible [docs on the module](https://tkdocs.com/tutorial/ install.html).
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/install.md
install.md
# About The Project The $`Z^2_n`$ Software was developed by Yohan Alexander as a research project, funded by the CNPq Institution, and it is a Open Source initiative. The program allows the user to calculate periodograms using the $`Z^2_n`$ statistics a la Buccheri et al. 1983. The $`Z^2_n`$ is a periodogram based on the Rayleigh method, which applies the time samples in a signal to a Fourier analysis. This method has been shown to be useful in detecting periodic signals at high frequencies associated with the rotation of compact objects. First, each event is reduced to a phase value $`\phi_j`$, in the range of 0 to 1, where $`frac (x) = x - \lfloor x \rfloor`$ such that for the $`j`$-th event we have the following equation, where $`\Delta t_{ij}`$ is the time of the event under analysis $`t_j`$ minus the time of the first detected event $`T_0`$. ```math \phi_j [0,1] = frac(v_i\Delta t_{ij} + \dot v_i \frac{\Delta t^2_{ij}}{2} + \dot v_i \frac{\Delta t^3_{ij}}{6}) ``` The $`Z^2_n`$ power spectrum, where $`n`$ is the number of harmonics included in the power, and $`N`$ is the number of events, is calculated from the equation which is defined as follows. ```math {\color{red}Z^2_n =} {\color{blue}\frac{2}{N}} {\color{black}\cdot} {\color{green}\sum_{k=1}^{n}} [({\color{green}\sum_{j=1}^{N}} {\color{magenta}cos}({\color{red}k}{\color{blue}\phi_j})) ^ 2 + ({\color{green}\sum_{j=1}^{N}} {\color{magenta}sin}({\color{red}k}{\color{blue}\phi_j})) ^ 2] ``` Note that this is potentially very computationally expensive, as there are two variables by which we are doing a loop, $`\color{red}k`$ which represents the frequencies, and $`\color{blue}j`$ which are the indices of the event. Think of the loop $`\color{blue}j`$ as being within the loop $`\color{red}k`$. For each new $`\color{red}k`$, we get the full range of $`\color{blue}j`$, which is why the periodogram can sometimes be very slow, since the execution time of the algorithm grows at a exponential rate $`O(n^2)`$. ## Built With The Z2n Software was built using the `Python` open source language, and optimized with the `Numba` JIT (just-in-time) compiler. * [Python](https://python.org) * [Numba](https://numba.pydata.org/)
z2n-periodogram
/z2n-periodogram-2.0.6.tar.gz/z2n-periodogram-2.0.6/docs/about.md
about.md
Z2Pack is a tool that computes topological invariants and illustrates non-trivial features of Berry curvature. It works as a post-processing tool with all major first-principles codes (z2pack.fp), as well as with tight-binding models (z2pack.tb) and explicit Hamiltonian matrices -- such as the ones obtained from a k.p model (z2pack.hm). It tracks the charge centers of hybrid Wannier functions - as described `here <http://journals.aps.org/prb/abstract/10.1103/PhysRevB.83.235401>`_ - to calculate these topological invariants. The Wannier charge centers are computed from overlap matrices that are obtained either directly (for tb) or via the Wannier90 code package (fp). - `Documentation <http://z2pack.ethz.ch/doc>`_ - `Online interface <http://z2pack.ethz.ch/online>`_ (tight-binding only)
z2pack
/z2pack-2.1.1-py3-none-any.whl/z2pack-2.1.1.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
On Windows, to build Z3, you should executed the following command in the Z3 root directory at the Visual Studio Command Prompt msbuild /p:configuration=external If you are using a 64-bit Python interpreter, you should use msbuild /p:configuration=external /p:platform=x64 On Linux and macOS, you must install python bindings, before trying example.py. To install python on Linux and macOS, you should execute the following command in the Z3 root directory sudo make install-z3py
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/README.txt
README.txt
from .z3 import * from .z3core import * from .z3printer import * from fractions import Fraction def _to_rcfnum(num, ctx=None): if isinstance(num, RCFNum): return num else: return RCFNum(num, ctx) def Pi(ctx=None): ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_pi(ctx.ref()), ctx) def E(ctx=None): ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_e(ctx.ref()), ctx) def MkInfinitesimal(name="eps", ctx=None): # Todo: remove parameter name. # For now, we keep it for backward compatibility. ctx = z3.get_ctx(ctx) return RCFNum(Z3_rcf_mk_infinitesimal(ctx.ref()), ctx) def MkRoots(p, ctx=None): ctx = z3.get_ctx(ctx) num = len(p) _tmp = [] _as = (RCFNumObj * num)() _rs = (RCFNumObj * num)() for i in range(num): _a = _to_rcfnum(p[i], ctx) _tmp.append(_a) # prevent GC _as[i] = _a.num nr = Z3_rcf_mk_roots(ctx.ref(), num, _as, _rs) r = [] for i in range(nr): r.append(RCFNum(_rs[i], ctx)) return r class RCFNum: def __init__(self, num, ctx=None): # TODO: add support for converting AST numeral values into RCFNum if isinstance(num, RCFNumObj): self.num = num self.ctx = z3.get_ctx(ctx) else: self.ctx = z3.get_ctx(ctx) self.num = Z3_rcf_mk_rational(self.ctx_ref(), str(num)) def __del__(self): Z3_rcf_del(self.ctx_ref(), self.num) def ctx_ref(self): return self.ctx.ref() def __repr__(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, False, in_html_mode()) def compact_str(self): return Z3_rcf_num_to_string(self.ctx_ref(), self.num, True, in_html_mode()) def __add__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), self.num, v.num), self.ctx) def __radd__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_add(self.ctx_ref(), v.num, self.num), self.ctx) def __mul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), self.num, v.num), self.ctx) def __rmul__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_mul(self.ctx_ref(), v.num, self.num), self.ctx) def __sub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), self.num, v.num), self.ctx) def __rsub__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_sub(self.ctx_ref(), v.num, self.num), self.ctx) def __div__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), self.num, v.num), self.ctx) def __rdiv__(self, other): v = _to_rcfnum(other, self.ctx) return RCFNum(Z3_rcf_div(self.ctx_ref(), v.num, self.num), self.ctx) def __neg__(self): return self.__rsub__(0) def power(self, k): return RCFNum(Z3_rcf_power(self.ctx_ref(), self.num, k), self.ctx) def __pow__(self, k): return self.power(k) def decimal(self, prec=5): return Z3_rcf_num_to_decimal_string(self.ctx_ref(), self.num, prec) def __lt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), self.num, v.num) def __rlt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_lt(self.ctx_ref(), v.num, self.num) def __gt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), self.num, v.num) def __rgt__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_gt(self.ctx_ref(), v.num, self.num) def __le__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), self.num, v.num) def __rle__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_le(self.ctx_ref(), v.num, self.num) def __ge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), self.num, v.num) def __rge__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_ge(self.ctx_ref(), v.num, self.num) def __eq__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_eq(self.ctx_ref(), self.num, v.num) def __ne__(self, other): v = _to_rcfnum(other, self.ctx) return Z3_rcf_neq(self.ctx_ref(), self.num, v.num) def split(self): n = (RCFNumObj * 1)() d = (RCFNumObj * 1)() Z3_rcf_get_numerator_denominator(self.ctx_ref(), self.num, n, d) return (RCFNum(n[0], self.ctx), RCFNum(d[0], self.ctx))
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3rcf.py
z3rcf.py
# enum Z3_lbool Z3_L_FALSE = -1 Z3_L_UNDEF = 0 Z3_L_TRUE = 1 # enum Z3_symbol_kind Z3_INT_SYMBOL = 0 Z3_STRING_SYMBOL = 1 # enum Z3_parameter_kind Z3_PARAMETER_INT = 0 Z3_PARAMETER_DOUBLE = 1 Z3_PARAMETER_RATIONAL = 2 Z3_PARAMETER_SYMBOL = 3 Z3_PARAMETER_SORT = 4 Z3_PARAMETER_AST = 5 Z3_PARAMETER_FUNC_DECL = 6 # enum Z3_sort_kind Z3_UNINTERPRETED_SORT = 0 Z3_BOOL_SORT = 1 Z3_INT_SORT = 2 Z3_REAL_SORT = 3 Z3_BV_SORT = 4 Z3_ARRAY_SORT = 5 Z3_DATATYPE_SORT = 6 Z3_RELATION_SORT = 7 Z3_FINITE_DOMAIN_SORT = 8 Z3_FLOATING_POINT_SORT = 9 Z3_ROUNDING_MODE_SORT = 10 Z3_SEQ_SORT = 11 Z3_RE_SORT = 12 Z3_UNKNOWN_SORT = 1000 # enum Z3_ast_kind Z3_NUMERAL_AST = 0 Z3_APP_AST = 1 Z3_VAR_AST = 2 Z3_QUANTIFIER_AST = 3 Z3_SORT_AST = 4 Z3_FUNC_DECL_AST = 5 Z3_UNKNOWN_AST = 1000 # enum Z3_decl_kind Z3_OP_TRUE = 256 Z3_OP_FALSE = 257 Z3_OP_EQ = 258 Z3_OP_DISTINCT = 259 Z3_OP_ITE = 260 Z3_OP_AND = 261 Z3_OP_OR = 262 Z3_OP_IFF = 263 Z3_OP_XOR = 264 Z3_OP_NOT = 265 Z3_OP_IMPLIES = 266 Z3_OP_OEQ = 267 Z3_OP_ANUM = 512 Z3_OP_AGNUM = 513 Z3_OP_LE = 514 Z3_OP_GE = 515 Z3_OP_LT = 516 Z3_OP_GT = 517 Z3_OP_ADD = 518 Z3_OP_SUB = 519 Z3_OP_UMINUS = 520 Z3_OP_MUL = 521 Z3_OP_DIV = 522 Z3_OP_IDIV = 523 Z3_OP_REM = 524 Z3_OP_MOD = 525 Z3_OP_TO_REAL = 526 Z3_OP_TO_INT = 527 Z3_OP_IS_INT = 528 Z3_OP_POWER = 529 Z3_OP_STORE = 768 Z3_OP_SELECT = 769 Z3_OP_CONST_ARRAY = 770 Z3_OP_ARRAY_MAP = 771 Z3_OP_ARRAY_DEFAULT = 772 Z3_OP_SET_UNION = 773 Z3_OP_SET_INTERSECT = 774 Z3_OP_SET_DIFFERENCE = 775 Z3_OP_SET_COMPLEMENT = 776 Z3_OP_SET_SUBSET = 777 Z3_OP_AS_ARRAY = 778 Z3_OP_ARRAY_EXT = 779 Z3_OP_SET_HAS_SIZE = 780 Z3_OP_SET_CARD = 781 Z3_OP_BNUM = 1024 Z3_OP_BIT1 = 1025 Z3_OP_BIT0 = 1026 Z3_OP_BNEG = 1027 Z3_OP_BADD = 1028 Z3_OP_BSUB = 1029 Z3_OP_BMUL = 1030 Z3_OP_BSDIV = 1031 Z3_OP_BUDIV = 1032 Z3_OP_BSREM = 1033 Z3_OP_BUREM = 1034 Z3_OP_BSMOD = 1035 Z3_OP_BSDIV0 = 1036 Z3_OP_BUDIV0 = 1037 Z3_OP_BSREM0 = 1038 Z3_OP_BUREM0 = 1039 Z3_OP_BSMOD0 = 1040 Z3_OP_ULEQ = 1041 Z3_OP_SLEQ = 1042 Z3_OP_UGEQ = 1043 Z3_OP_SGEQ = 1044 Z3_OP_ULT = 1045 Z3_OP_SLT = 1046 Z3_OP_UGT = 1047 Z3_OP_SGT = 1048 Z3_OP_BAND = 1049 Z3_OP_BOR = 1050 Z3_OP_BNOT = 1051 Z3_OP_BXOR = 1052 Z3_OP_BNAND = 1053 Z3_OP_BNOR = 1054 Z3_OP_BXNOR = 1055 Z3_OP_CONCAT = 1056 Z3_OP_SIGN_EXT = 1057 Z3_OP_ZERO_EXT = 1058 Z3_OP_EXTRACT = 1059 Z3_OP_REPEAT = 1060 Z3_OP_BREDOR = 1061 Z3_OP_BREDAND = 1062 Z3_OP_BCOMP = 1063 Z3_OP_BSHL = 1064 Z3_OP_BLSHR = 1065 Z3_OP_BASHR = 1066 Z3_OP_ROTATE_LEFT = 1067 Z3_OP_ROTATE_RIGHT = 1068 Z3_OP_EXT_ROTATE_LEFT = 1069 Z3_OP_EXT_ROTATE_RIGHT = 1070 Z3_OP_BIT2BOOL = 1071 Z3_OP_INT2BV = 1072 Z3_OP_BV2INT = 1073 Z3_OP_CARRY = 1074 Z3_OP_XOR3 = 1075 Z3_OP_BSMUL_NO_OVFL = 1076 Z3_OP_BUMUL_NO_OVFL = 1077 Z3_OP_BSMUL_NO_UDFL = 1078 Z3_OP_BSDIV_I = 1079 Z3_OP_BUDIV_I = 1080 Z3_OP_BSREM_I = 1081 Z3_OP_BUREM_I = 1082 Z3_OP_BSMOD_I = 1083 Z3_OP_PR_UNDEF = 1280 Z3_OP_PR_TRUE = 1281 Z3_OP_PR_ASSERTED = 1282 Z3_OP_PR_GOAL = 1283 Z3_OP_PR_MODUS_PONENS = 1284 Z3_OP_PR_REFLEXIVITY = 1285 Z3_OP_PR_SYMMETRY = 1286 Z3_OP_PR_TRANSITIVITY = 1287 Z3_OP_PR_TRANSITIVITY_STAR = 1288 Z3_OP_PR_MONOTONICITY = 1289 Z3_OP_PR_QUANT_INTRO = 1290 Z3_OP_PR_BIND = 1291 Z3_OP_PR_DISTRIBUTIVITY = 1292 Z3_OP_PR_AND_ELIM = 1293 Z3_OP_PR_NOT_OR_ELIM = 1294 Z3_OP_PR_REWRITE = 1295 Z3_OP_PR_REWRITE_STAR = 1296 Z3_OP_PR_PULL_QUANT = 1297 Z3_OP_PR_PUSH_QUANT = 1298 Z3_OP_PR_ELIM_UNUSED_VARS = 1299 Z3_OP_PR_DER = 1300 Z3_OP_PR_QUANT_INST = 1301 Z3_OP_PR_HYPOTHESIS = 1302 Z3_OP_PR_LEMMA = 1303 Z3_OP_PR_UNIT_RESOLUTION = 1304 Z3_OP_PR_IFF_TRUE = 1305 Z3_OP_PR_IFF_FALSE = 1306 Z3_OP_PR_COMMUTATIVITY = 1307 Z3_OP_PR_DEF_AXIOM = 1308 Z3_OP_PR_ASSUMPTION_ADD = 1309 Z3_OP_PR_LEMMA_ADD = 1310 Z3_OP_PR_REDUNDANT_DEL = 1311 Z3_OP_PR_CLAUSE_TRAIL = 1312 Z3_OP_PR_DEF_INTRO = 1313 Z3_OP_PR_APPLY_DEF = 1314 Z3_OP_PR_IFF_OEQ = 1315 Z3_OP_PR_NNF_POS = 1316 Z3_OP_PR_NNF_NEG = 1317 Z3_OP_PR_SKOLEMIZE = 1318 Z3_OP_PR_MODUS_PONENS_OEQ = 1319 Z3_OP_PR_TH_LEMMA = 1320 Z3_OP_PR_HYPER_RESOLVE = 1321 Z3_OP_RA_STORE = 1536 Z3_OP_RA_EMPTY = 1537 Z3_OP_RA_IS_EMPTY = 1538 Z3_OP_RA_JOIN = 1539 Z3_OP_RA_UNION = 1540 Z3_OP_RA_WIDEN = 1541 Z3_OP_RA_PROJECT = 1542 Z3_OP_RA_FILTER = 1543 Z3_OP_RA_NEGATION_FILTER = 1544 Z3_OP_RA_RENAME = 1545 Z3_OP_RA_COMPLEMENT = 1546 Z3_OP_RA_SELECT = 1547 Z3_OP_RA_CLONE = 1548 Z3_OP_FD_CONSTANT = 1549 Z3_OP_FD_LT = 1550 Z3_OP_SEQ_UNIT = 1551 Z3_OP_SEQ_EMPTY = 1552 Z3_OP_SEQ_CONCAT = 1553 Z3_OP_SEQ_PREFIX = 1554 Z3_OP_SEQ_SUFFIX = 1555 Z3_OP_SEQ_CONTAINS = 1556 Z3_OP_SEQ_EXTRACT = 1557 Z3_OP_SEQ_REPLACE = 1558 Z3_OP_SEQ_AT = 1559 Z3_OP_SEQ_NTH = 1560 Z3_OP_SEQ_LENGTH = 1561 Z3_OP_SEQ_INDEX = 1562 Z3_OP_SEQ_LAST_INDEX = 1563 Z3_OP_SEQ_TO_RE = 1564 Z3_OP_SEQ_IN_RE = 1565 Z3_OP_STR_TO_INT = 1566 Z3_OP_INT_TO_STR = 1567 Z3_OP_RE_PLUS = 1568 Z3_OP_RE_STAR = 1569 Z3_OP_RE_OPTION = 1570 Z3_OP_RE_CONCAT = 1571 Z3_OP_RE_UNION = 1572 Z3_OP_RE_RANGE = 1573 Z3_OP_RE_LOOP = 1574 Z3_OP_RE_INTERSECT = 1575 Z3_OP_RE_EMPTY_SET = 1576 Z3_OP_RE_FULL_SET = 1577 Z3_OP_RE_COMPLEMENT = 1578 Z3_OP_LABEL = 1792 Z3_OP_LABEL_LIT = 1793 Z3_OP_DT_CONSTRUCTOR = 2048 Z3_OP_DT_RECOGNISER = 2049 Z3_OP_DT_IS = 2050 Z3_OP_DT_ACCESSOR = 2051 Z3_OP_DT_UPDATE_FIELD = 2052 Z3_OP_PB_AT_MOST = 2304 Z3_OP_PB_AT_LEAST = 2305 Z3_OP_PB_LE = 2306 Z3_OP_PB_GE = 2307 Z3_OP_PB_EQ = 2308 Z3_OP_SPECIAL_RELATION_LO = 40960 Z3_OP_SPECIAL_RELATION_PO = 40961 Z3_OP_SPECIAL_RELATION_PLO = 40962 Z3_OP_SPECIAL_RELATION_TO = 40963 Z3_OP_SPECIAL_RELATION_TC = 40964 Z3_OP_SPECIAL_RELATION_TRC = 40965 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN = 45056 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY = 45057 Z3_OP_FPA_RM_TOWARD_POSITIVE = 45058 Z3_OP_FPA_RM_TOWARD_NEGATIVE = 45059 Z3_OP_FPA_RM_TOWARD_ZERO = 45060 Z3_OP_FPA_NUM = 45061 Z3_OP_FPA_PLUS_INF = 45062 Z3_OP_FPA_MINUS_INF = 45063 Z3_OP_FPA_NAN = 45064 Z3_OP_FPA_PLUS_ZERO = 45065 Z3_OP_FPA_MINUS_ZERO = 45066 Z3_OP_FPA_ADD = 45067 Z3_OP_FPA_SUB = 45068 Z3_OP_FPA_NEG = 45069 Z3_OP_FPA_MUL = 45070 Z3_OP_FPA_DIV = 45071 Z3_OP_FPA_REM = 45072 Z3_OP_FPA_ABS = 45073 Z3_OP_FPA_MIN = 45074 Z3_OP_FPA_MAX = 45075 Z3_OP_FPA_FMA = 45076 Z3_OP_FPA_SQRT = 45077 Z3_OP_FPA_ROUND_TO_INTEGRAL = 45078 Z3_OP_FPA_EQ = 45079 Z3_OP_FPA_LT = 45080 Z3_OP_FPA_GT = 45081 Z3_OP_FPA_LE = 45082 Z3_OP_FPA_GE = 45083 Z3_OP_FPA_IS_NAN = 45084 Z3_OP_FPA_IS_INF = 45085 Z3_OP_FPA_IS_ZERO = 45086 Z3_OP_FPA_IS_NORMAL = 45087 Z3_OP_FPA_IS_SUBNORMAL = 45088 Z3_OP_FPA_IS_NEGATIVE = 45089 Z3_OP_FPA_IS_POSITIVE = 45090 Z3_OP_FPA_FP = 45091 Z3_OP_FPA_TO_FP = 45092 Z3_OP_FPA_TO_FP_UNSIGNED = 45093 Z3_OP_FPA_TO_UBV = 45094 Z3_OP_FPA_TO_SBV = 45095 Z3_OP_FPA_TO_REAL = 45096 Z3_OP_FPA_TO_IEEE_BV = 45097 Z3_OP_FPA_BVWRAP = 45098 Z3_OP_FPA_BV2RM = 45099 Z3_OP_INTERNAL = 45100 Z3_OP_UNINTERPRETED = 45101 # enum Z3_param_kind Z3_PK_UINT = 0 Z3_PK_BOOL = 1 Z3_PK_DOUBLE = 2 Z3_PK_SYMBOL = 3 Z3_PK_STRING = 4 Z3_PK_OTHER = 5 Z3_PK_INVALID = 6 # enum Z3_ast_print_mode Z3_PRINT_SMTLIB_FULL = 0 Z3_PRINT_LOW_LEVEL = 1 Z3_PRINT_SMTLIB2_COMPLIANT = 2 # enum Z3_error_code Z3_OK = 0 Z3_SORT_ERROR = 1 Z3_IOB = 2 Z3_INVALID_ARG = 3 Z3_PARSER_ERROR = 4 Z3_NO_PARSER = 5 Z3_INVALID_PATTERN = 6 Z3_MEMOUT_FAIL = 7 Z3_FILE_ACCESS_ERROR = 8 Z3_INTERNAL_FATAL = 9 Z3_INVALID_USAGE = 10 Z3_DEC_REF_ERROR = 11 Z3_EXCEPTION = 12 # enum Z3_goal_prec Z3_GOAL_PRECISE = 0 Z3_GOAL_UNDER = 1 Z3_GOAL_OVER = 2 Z3_GOAL_UNDER_OVER = 3
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3consts.py
z3consts.py
import sys, os import ctypes import pkg_resources from .z3types import * from .z3consts import * _ext = 'dll' if sys.platform in ('win32', 'cygwin') else 'dylib' if sys.platform == 'darwin' else 'so' _lib = None _default_dirs = ['.', os.path.dirname(os.path.abspath(__file__)), pkg_resources.resource_filename('z3', 'lib'), os.path.join(sys.prefix, 'lib'), None] _all_dirs = [] # search the default dirs first _all_dirs.extend(_default_dirs) if sys.version < '3': import __builtin__ if hasattr(__builtin__, "Z3_LIB_DIRS"): _all_dirs = __builtin__.Z3_LIB_DIRS else: import builtins if hasattr(builtins, "Z3_LIB_DIRS"): _all_dirs = builtins.Z3_LIB_DIRS for v in ('Z3_LIBRARY_PATH', 'PATH', 'PYTHONPATH'): if v in os.environ: lp = os.environ[v]; lds = lp.split(';') if sys.platform in ('win32') else lp.split(':') _all_dirs.extend(lds) _failures = [] for d in _all_dirs: try: d = os.path.realpath(d) if os.path.isdir(d): d = os.path.join(d, 'libz3.%s' % _ext) if os.path.isfile(d): _lib = ctypes.CDLL(d) break except Exception as e: _failures += [e] pass if _lib is None: # If all else failed, ask the system to find it. try: _lib = ctypes.CDLL('libz3.%s' % _ext) except Exception as e: _failures += [e] pass if _lib is None: print("Could not find libz3.%s; consider adding the directory containing it to" % _ext) print(" - your system's PATH environment variable,") print(" - the Z3_LIBRARY_PATH environment variable, or ") print(" - to the custom Z3_LIBRARY_DIRS Python-builtin before importing the z3 module, e.g. via") if sys.version < '3': print(" import __builtin__") print(" __builtin__.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) else: print(" import builtins") print(" builtins.Z3_LIB_DIRS = [ '/path/to/libz3.%s' ] " % _ext) raise Z3Exception("libz3.%s not found." % _ext) def _str_to_bytes(s): if isinstance(s, str): try: return s.encode('latin-1') except: # kick the bucket down the road. :-J return s else: return s if sys.version < '3': def _to_pystr(s): return s else: def _to_pystr(s): if s != None: enc = sys.stdout.encoding if enc != None: return s.decode(enc) else: return s.decode('latin-1') else: return "" _error_handler_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint) _lib.Z3_set_error_handler.restype = None _lib.Z3_set_error_handler.argtypes = [ContextObj, _error_handler_type] _lib.Z3_global_param_set.argtypes = [ctypes.c_char_p, ctypes.c_char_p] _lib.Z3_global_param_reset_all.argtypes = [] _lib.Z3_global_param_get.restype = ctypes.c_bool _lib.Z3_global_param_get.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p)] _lib.Z3_mk_config.restype = Config _lib.Z3_mk_config.argtypes = [] _lib.Z3_del_config.argtypes = [Config] _lib.Z3_set_param_value.argtypes = [Config, ctypes.c_char_p, ctypes.c_char_p] _lib.Z3_mk_context.restype = ContextObj _lib.Z3_mk_context.argtypes = [Config] _lib.Z3_mk_context_rc.restype = ContextObj _lib.Z3_mk_context_rc.argtypes = [Config] _lib.Z3_del_context.argtypes = [ContextObj] _lib.Z3_inc_ref.argtypes = [ContextObj, Ast] _lib.Z3_dec_ref.argtypes = [ContextObj, Ast] _lib.Z3_update_param_value.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_char_p] _lib.Z3_interrupt.argtypes = [ContextObj] _lib.Z3_mk_params.restype = Params _lib.Z3_mk_params.argtypes = [ContextObj] _lib.Z3_params_inc_ref.argtypes = [ContextObj, Params] _lib.Z3_params_dec_ref.argtypes = [ContextObj, Params] _lib.Z3_params_set_bool.argtypes = [ContextObj, Params, Symbol, ctypes.c_bool] _lib.Z3_params_set_uint.argtypes = [ContextObj, Params, Symbol, ctypes.c_uint] _lib.Z3_params_set_double.argtypes = [ContextObj, Params, Symbol, ctypes.c_double] _lib.Z3_params_set_symbol.argtypes = [ContextObj, Params, Symbol, Symbol] _lib.Z3_params_to_string.restype = ctypes.c_char_p _lib.Z3_params_to_string.argtypes = [ContextObj, Params] _lib.Z3_params_validate.argtypes = [ContextObj, Params, ParamDescrs] _lib.Z3_param_descrs_inc_ref.argtypes = [ContextObj, ParamDescrs] _lib.Z3_param_descrs_dec_ref.argtypes = [ContextObj, ParamDescrs] _lib.Z3_param_descrs_get_kind.restype = ctypes.c_uint _lib.Z3_param_descrs_get_kind.argtypes = [ContextObj, ParamDescrs, Symbol] _lib.Z3_param_descrs_size.restype = ctypes.c_uint _lib.Z3_param_descrs_size.argtypes = [ContextObj, ParamDescrs] _lib.Z3_param_descrs_get_name.restype = Symbol _lib.Z3_param_descrs_get_name.argtypes = [ContextObj, ParamDescrs, ctypes.c_uint] _lib.Z3_param_descrs_get_documentation.restype = ctypes.c_char_p _lib.Z3_param_descrs_get_documentation.argtypes = [ContextObj, ParamDescrs, Symbol] _lib.Z3_param_descrs_to_string.restype = ctypes.c_char_p _lib.Z3_param_descrs_to_string.argtypes = [ContextObj, ParamDescrs] _lib.Z3_mk_int_symbol.restype = Symbol _lib.Z3_mk_int_symbol.argtypes = [ContextObj, ctypes.c_int] _lib.Z3_mk_string_symbol.restype = Symbol _lib.Z3_mk_string_symbol.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_mk_uninterpreted_sort.restype = Sort _lib.Z3_mk_uninterpreted_sort.argtypes = [ContextObj, Symbol] _lib.Z3_mk_bool_sort.restype = Sort _lib.Z3_mk_bool_sort.argtypes = [ContextObj] _lib.Z3_mk_int_sort.restype = Sort _lib.Z3_mk_int_sort.argtypes = [ContextObj] _lib.Z3_mk_real_sort.restype = Sort _lib.Z3_mk_real_sort.argtypes = [ContextObj] _lib.Z3_mk_bv_sort.restype = Sort _lib.Z3_mk_bv_sort.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_mk_finite_domain_sort.restype = Sort _lib.Z3_mk_finite_domain_sort.argtypes = [ContextObj, Symbol, ctypes.c_ulonglong] _lib.Z3_mk_array_sort.restype = Sort _lib.Z3_mk_array_sort.argtypes = [ContextObj, Sort, Sort] _lib.Z3_mk_array_sort_n.restype = Sort _lib.Z3_mk_array_sort_n.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_mk_tuple_sort.restype = Sort _lib.Z3_mk_tuple_sort.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_enumeration_sort.restype = Sort _lib.Z3_mk_enumeration_sort.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_list_sort.restype = Sort _lib.Z3_mk_list_sort.argtypes = [ContextObj, Symbol, Sort, ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_constructor.restype = Constructor _lib.Z3_mk_constructor.argtypes = [ContextObj, Symbol, Symbol, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.POINTER(ctypes.c_uint)] _lib.Z3_del_constructor.argtypes = [ContextObj, Constructor] _lib.Z3_mk_datatype.restype = Sort _lib.Z3_mk_datatype.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Constructor)] _lib.Z3_mk_constructor_list.restype = ConstructorList _lib.Z3_mk_constructor_list.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Constructor)] _lib.Z3_del_constructor_list.argtypes = [ContextObj, ConstructorList] _lib.Z3_mk_datatypes.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.POINTER(ConstructorList)] _lib.Z3_query_constructor.argtypes = [ContextObj, Constructor, ctypes.c_uint, ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl), ctypes.POINTER(FuncDecl)] _lib.Z3_mk_func_decl.restype = FuncDecl _lib.Z3_mk_func_decl.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_mk_app.restype = Ast _lib.Z3_mk_app.argtypes = [ContextObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_const.restype = Ast _lib.Z3_mk_const.argtypes = [ContextObj, Symbol, Sort] _lib.Z3_mk_fresh_func_decl.restype = FuncDecl _lib.Z3_mk_fresh_func_decl.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_mk_fresh_const.restype = Ast _lib.Z3_mk_fresh_const.argtypes = [ContextObj, ctypes.c_char_p, Sort] _lib.Z3_mk_rec_func_decl.restype = FuncDecl _lib.Z3_mk_rec_func_decl.argtypes = [ContextObj, Symbol, ctypes.c_uint, ctypes.POINTER(Sort), Sort] _lib.Z3_add_rec_def.argtypes = [ContextObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_mk_true.restype = Ast _lib.Z3_mk_true.argtypes = [ContextObj] _lib.Z3_mk_false.restype = Ast _lib.Z3_mk_false.argtypes = [ContextObj] _lib.Z3_mk_eq.restype = Ast _lib.Z3_mk_eq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_distinct.restype = Ast _lib.Z3_mk_distinct.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_not.restype = Ast _lib.Z3_mk_not.argtypes = [ContextObj, Ast] _lib.Z3_mk_ite.restype = Ast _lib.Z3_mk_ite.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_iff.restype = Ast _lib.Z3_mk_iff.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_implies.restype = Ast _lib.Z3_mk_implies.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_xor.restype = Ast _lib.Z3_mk_xor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_and.restype = Ast _lib.Z3_mk_and.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_or.restype = Ast _lib.Z3_mk_or.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_add.restype = Ast _lib.Z3_mk_add.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_mul.restype = Ast _lib.Z3_mk_mul.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_sub.restype = Ast _lib.Z3_mk_sub.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_unary_minus.restype = Ast _lib.Z3_mk_unary_minus.argtypes = [ContextObj, Ast] _lib.Z3_mk_div.restype = Ast _lib.Z3_mk_div.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_mod.restype = Ast _lib.Z3_mk_mod.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_rem.restype = Ast _lib.Z3_mk_rem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_power.restype = Ast _lib.Z3_mk_power.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_lt.restype = Ast _lib.Z3_mk_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_le.restype = Ast _lib.Z3_mk_le.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_gt.restype = Ast _lib.Z3_mk_gt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_ge.restype = Ast _lib.Z3_mk_ge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_divides.restype = Ast _lib.Z3_mk_divides.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_int2real.restype = Ast _lib.Z3_mk_int2real.argtypes = [ContextObj, Ast] _lib.Z3_mk_real2int.restype = Ast _lib.Z3_mk_real2int.argtypes = [ContextObj, Ast] _lib.Z3_mk_is_int.restype = Ast _lib.Z3_mk_is_int.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvnot.restype = Ast _lib.Z3_mk_bvnot.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvredand.restype = Ast _lib.Z3_mk_bvredand.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvredor.restype = Ast _lib.Z3_mk_bvredor.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvand.restype = Ast _lib.Z3_mk_bvand.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvor.restype = Ast _lib.Z3_mk_bvor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvxor.restype = Ast _lib.Z3_mk_bvxor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvnand.restype = Ast _lib.Z3_mk_bvnand.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvnor.restype = Ast _lib.Z3_mk_bvnor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvxnor.restype = Ast _lib.Z3_mk_bvxnor.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvneg.restype = Ast _lib.Z3_mk_bvneg.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvadd.restype = Ast _lib.Z3_mk_bvadd.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsub.restype = Ast _lib.Z3_mk_bvsub.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvmul.restype = Ast _lib.Z3_mk_bvmul.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvudiv.restype = Ast _lib.Z3_mk_bvudiv.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsdiv.restype = Ast _lib.Z3_mk_bvsdiv.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvurem.restype = Ast _lib.Z3_mk_bvurem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsrem.restype = Ast _lib.Z3_mk_bvsrem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsmod.restype = Ast _lib.Z3_mk_bvsmod.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvult.restype = Ast _lib.Z3_mk_bvult.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvslt.restype = Ast _lib.Z3_mk_bvslt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvule.restype = Ast _lib.Z3_mk_bvule.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsle.restype = Ast _lib.Z3_mk_bvsle.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvuge.restype = Ast _lib.Z3_mk_bvuge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsge.restype = Ast _lib.Z3_mk_bvsge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvugt.restype = Ast _lib.Z3_mk_bvugt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsgt.restype = Ast _lib.Z3_mk_bvsgt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_concat.restype = Ast _lib.Z3_mk_concat.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_extract.restype = Ast _lib.Z3_mk_extract.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, Ast] _lib.Z3_mk_sign_ext.restype = Ast _lib.Z3_mk_sign_ext.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_zero_ext.restype = Ast _lib.Z3_mk_zero_ext.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_repeat.restype = Ast _lib.Z3_mk_repeat.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_bvshl.restype = Ast _lib.Z3_mk_bvshl.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvlshr.restype = Ast _lib.Z3_mk_bvlshr.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvashr.restype = Ast _lib.Z3_mk_bvashr.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_rotate_left.restype = Ast _lib.Z3_mk_rotate_left.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_rotate_right.restype = Ast _lib.Z3_mk_rotate_right.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_ext_rotate_left.restype = Ast _lib.Z3_mk_ext_rotate_left.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_ext_rotate_right.restype = Ast _lib.Z3_mk_ext_rotate_right.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_int2bv.restype = Ast _lib.Z3_mk_int2bv.argtypes = [ContextObj, ctypes.c_uint, Ast] _lib.Z3_mk_bv2int.restype = Ast _lib.Z3_mk_bv2int.argtypes = [ContextObj, Ast, ctypes.c_bool] _lib.Z3_mk_bvadd_no_overflow.restype = Ast _lib.Z3_mk_bvadd_no_overflow.argtypes = [ContextObj, Ast, Ast, ctypes.c_bool] _lib.Z3_mk_bvadd_no_underflow.restype = Ast _lib.Z3_mk_bvadd_no_underflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsub_no_overflow.restype = Ast _lib.Z3_mk_bvsub_no_overflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvsub_no_underflow.restype = Ast _lib.Z3_mk_bvsub_no_underflow.argtypes = [ContextObj, Ast, Ast, ctypes.c_bool] _lib.Z3_mk_bvsdiv_no_overflow.restype = Ast _lib.Z3_mk_bvsdiv_no_overflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_bvneg_no_overflow.restype = Ast _lib.Z3_mk_bvneg_no_overflow.argtypes = [ContextObj, Ast] _lib.Z3_mk_bvmul_no_overflow.restype = Ast _lib.Z3_mk_bvmul_no_overflow.argtypes = [ContextObj, Ast, Ast, ctypes.c_bool] _lib.Z3_mk_bvmul_no_underflow.restype = Ast _lib.Z3_mk_bvmul_no_underflow.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_select.restype = Ast _lib.Z3_mk_select.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_select_n.restype = Ast _lib.Z3_mk_select_n.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_store.restype = Ast _lib.Z3_mk_store.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_store_n.restype = Ast _lib.Z3_mk_store_n.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_mk_const_array.restype = Ast _lib.Z3_mk_const_array.argtypes = [ContextObj, Sort, Ast] _lib.Z3_mk_map.restype = Ast _lib.Z3_mk_map.argtypes = [ContextObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_array_default.restype = Ast _lib.Z3_mk_array_default.argtypes = [ContextObj, Ast] _lib.Z3_mk_as_array.restype = Ast _lib.Z3_mk_as_array.argtypes = [ContextObj, FuncDecl] _lib.Z3_mk_set_has_size.restype = Ast _lib.Z3_mk_set_has_size.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_sort.restype = Sort _lib.Z3_mk_set_sort.argtypes = [ContextObj, Sort] _lib.Z3_mk_empty_set.restype = Ast _lib.Z3_mk_empty_set.argtypes = [ContextObj, Sort] _lib.Z3_mk_full_set.restype = Ast _lib.Z3_mk_full_set.argtypes = [ContextObj, Sort] _lib.Z3_mk_set_add.restype = Ast _lib.Z3_mk_set_add.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_del.restype = Ast _lib.Z3_mk_set_del.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_union.restype = Ast _lib.Z3_mk_set_union.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_set_intersect.restype = Ast _lib.Z3_mk_set_intersect.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_set_difference.restype = Ast _lib.Z3_mk_set_difference.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_complement.restype = Ast _lib.Z3_mk_set_complement.argtypes = [ContextObj, Ast] _lib.Z3_mk_set_member.restype = Ast _lib.Z3_mk_set_member.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_set_subset.restype = Ast _lib.Z3_mk_set_subset.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_array_ext.restype = Ast _lib.Z3_mk_array_ext.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_numeral.restype = Ast _lib.Z3_mk_numeral.argtypes = [ContextObj, ctypes.c_char_p, Sort] _lib.Z3_mk_real.restype = Ast _lib.Z3_mk_real.argtypes = [ContextObj, ctypes.c_int, ctypes.c_int] _lib.Z3_mk_int.restype = Ast _lib.Z3_mk_int.argtypes = [ContextObj, ctypes.c_int, Sort] _lib.Z3_mk_unsigned_int.restype = Ast _lib.Z3_mk_unsigned_int.argtypes = [ContextObj, ctypes.c_uint, Sort] _lib.Z3_mk_int64.restype = Ast _lib.Z3_mk_int64.argtypes = [ContextObj, ctypes.c_longlong, Sort] _lib.Z3_mk_unsigned_int64.restype = Ast _lib.Z3_mk_unsigned_int64.argtypes = [ContextObj, ctypes.c_ulonglong, Sort] _lib.Z3_mk_bv_numeral.restype = Ast _lib.Z3_mk_bv_numeral.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(ctypes.c_bool)] _lib.Z3_mk_seq_sort.restype = Sort _lib.Z3_mk_seq_sort.argtypes = [ContextObj, Sort] _lib.Z3_is_seq_sort.restype = ctypes.c_bool _lib.Z3_is_seq_sort.argtypes = [ContextObj, Sort] _lib.Z3_get_seq_sort_basis.restype = Sort _lib.Z3_get_seq_sort_basis.argtypes = [ContextObj, Sort] _lib.Z3_mk_re_sort.restype = Sort _lib.Z3_mk_re_sort.argtypes = [ContextObj, Sort] _lib.Z3_is_re_sort.restype = ctypes.c_bool _lib.Z3_is_re_sort.argtypes = [ContextObj, Sort] _lib.Z3_get_re_sort_basis.restype = Sort _lib.Z3_get_re_sort_basis.argtypes = [ContextObj, Sort] _lib.Z3_mk_string_sort.restype = Sort _lib.Z3_mk_string_sort.argtypes = [ContextObj] _lib.Z3_is_string_sort.restype = ctypes.c_bool _lib.Z3_is_string_sort.argtypes = [ContextObj, Sort] _lib.Z3_mk_string.restype = Ast _lib.Z3_mk_string.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_mk_lstring.restype = Ast _lib.Z3_mk_lstring.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_char_p] _lib.Z3_is_string.restype = ctypes.c_bool _lib.Z3_is_string.argtypes = [ContextObj, Ast] _lib.Z3_get_string.restype = ctypes.c_char_p _lib.Z3_get_string.argtypes = [ContextObj, Ast] _lib.Z3_get_lstring.restype = ctypes.POINTER(ctypes.c_char) _lib.Z3_get_lstring.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_uint)] _lib.Z3_mk_seq_empty.restype = Ast _lib.Z3_mk_seq_empty.argtypes = [ContextObj, Sort] _lib.Z3_mk_seq_unit.restype = Ast _lib.Z3_mk_seq_unit.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_concat.restype = Ast _lib.Z3_mk_seq_concat.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_seq_prefix.restype = Ast _lib.Z3_mk_seq_prefix.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_suffix.restype = Ast _lib.Z3_mk_seq_suffix.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_contains.restype = Ast _lib.Z3_mk_seq_contains.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_str_lt.restype = Ast _lib.Z3_mk_str_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_str_le.restype = Ast _lib.Z3_mk_str_le.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_extract.restype = Ast _lib.Z3_mk_seq_extract.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_seq_replace.restype = Ast _lib.Z3_mk_seq_replace.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_seq_at.restype = Ast _lib.Z3_mk_seq_at.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_nth.restype = Ast _lib.Z3_mk_seq_nth.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_seq_length.restype = Ast _lib.Z3_mk_seq_length.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_index.restype = Ast _lib.Z3_mk_seq_index.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_seq_last_index.restype = Ast _lib.Z3_mk_seq_last_index.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_str_to_int.restype = Ast _lib.Z3_mk_str_to_int.argtypes = [ContextObj, Ast] _lib.Z3_mk_int_to_str.restype = Ast _lib.Z3_mk_int_to_str.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_to_re.restype = Ast _lib.Z3_mk_seq_to_re.argtypes = [ContextObj, Ast] _lib.Z3_mk_seq_in_re.restype = Ast _lib.Z3_mk_seq_in_re.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_re_plus.restype = Ast _lib.Z3_mk_re_plus.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_star.restype = Ast _lib.Z3_mk_re_star.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_option.restype = Ast _lib.Z3_mk_re_option.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_union.restype = Ast _lib.Z3_mk_re_union.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_re_concat.restype = Ast _lib.Z3_mk_re_concat.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_re_range.restype = Ast _lib.Z3_mk_re_range.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_re_loop.restype = Ast _lib.Z3_mk_re_loop.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.c_uint] _lib.Z3_mk_re_intersect.restype = Ast _lib.Z3_mk_re_intersect.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_re_complement.restype = Ast _lib.Z3_mk_re_complement.argtypes = [ContextObj, Ast] _lib.Z3_mk_re_empty.restype = Ast _lib.Z3_mk_re_empty.argtypes = [ContextObj, Sort] _lib.Z3_mk_re_full.restype = Ast _lib.Z3_mk_re_full.argtypes = [ContextObj, Sort] _lib.Z3_mk_linear_order.restype = FuncDecl _lib.Z3_mk_linear_order.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_mk_partial_order.restype = FuncDecl _lib.Z3_mk_partial_order.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_mk_piecewise_linear_order.restype = FuncDecl _lib.Z3_mk_piecewise_linear_order.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_mk_tree_order.restype = FuncDecl _lib.Z3_mk_tree_order.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_mk_transitive_closure.restype = FuncDecl _lib.Z3_mk_transitive_closure.argtypes = [ContextObj, FuncDecl] _lib.Z3_mk_pattern.restype = Pattern _lib.Z3_mk_pattern.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_mk_bound.restype = Ast _lib.Z3_mk_bound.argtypes = [ContextObj, ctypes.c_uint, Sort] _lib.Z3_mk_forall.restype = Ast _lib.Z3_mk_forall.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_exists.restype = Ast _lib.Z3_mk_exists.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_quantifier.restype = Ast _lib.Z3_mk_quantifier.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_quantifier_ex.restype = Ast _lib.Z3_mk_quantifier_ex.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, Symbol, Symbol, ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_forall_const.restype = Ast _lib.Z3_mk_forall_const.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), Ast] _lib.Z3_mk_exists_const.restype = Ast _lib.Z3_mk_exists_const.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), Ast] _lib.Z3_mk_quantifier_const.restype = Ast _lib.Z3_mk_quantifier_const.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), Ast] _lib.Z3_mk_quantifier_const_ex.restype = Ast _lib.Z3_mk_quantifier_const_ex.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_uint, Symbol, Symbol, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint, ctypes.POINTER(Pattern), ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_mk_lambda.restype = Ast _lib.Z3_mk_lambda.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Sort), ctypes.POINTER(Symbol), Ast] _lib.Z3_mk_lambda_const.restype = Ast _lib.Z3_mk_lambda_const.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_get_symbol_kind.restype = ctypes.c_uint _lib.Z3_get_symbol_kind.argtypes = [ContextObj, Symbol] _lib.Z3_get_symbol_int.restype = ctypes.c_int _lib.Z3_get_symbol_int.argtypes = [ContextObj, Symbol] _lib.Z3_get_symbol_string.restype = ctypes.c_char_p _lib.Z3_get_symbol_string.argtypes = [ContextObj, Symbol] _lib.Z3_get_sort_name.restype = Symbol _lib.Z3_get_sort_name.argtypes = [ContextObj, Sort] _lib.Z3_get_sort_id.restype = ctypes.c_uint _lib.Z3_get_sort_id.argtypes = [ContextObj, Sort] _lib.Z3_sort_to_ast.restype = Ast _lib.Z3_sort_to_ast.argtypes = [ContextObj, Sort] _lib.Z3_is_eq_sort.restype = ctypes.c_bool _lib.Z3_is_eq_sort.argtypes = [ContextObj, Sort, Sort] _lib.Z3_get_sort_kind.restype = ctypes.c_uint _lib.Z3_get_sort_kind.argtypes = [ContextObj, Sort] _lib.Z3_get_bv_sort_size.restype = ctypes.c_uint _lib.Z3_get_bv_sort_size.argtypes = [ContextObj, Sort] _lib.Z3_get_finite_domain_sort_size.restype = ctypes.c_bool _lib.Z3_get_finite_domain_sort_size.argtypes = [ContextObj, Sort, ctypes.POINTER(ctypes.c_ulonglong)] _lib.Z3_get_array_sort_domain.restype = Sort _lib.Z3_get_array_sort_domain.argtypes = [ContextObj, Sort] _lib.Z3_get_array_sort_range.restype = Sort _lib.Z3_get_array_sort_range.argtypes = [ContextObj, Sort] _lib.Z3_get_tuple_sort_mk_decl.restype = FuncDecl _lib.Z3_get_tuple_sort_mk_decl.argtypes = [ContextObj, Sort] _lib.Z3_get_tuple_sort_num_fields.restype = ctypes.c_uint _lib.Z3_get_tuple_sort_num_fields.argtypes = [ContextObj, Sort] _lib.Z3_get_tuple_sort_field_decl.restype = FuncDecl _lib.Z3_get_tuple_sort_field_decl.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_get_datatype_sort_num_constructors.restype = ctypes.c_uint _lib.Z3_get_datatype_sort_num_constructors.argtypes = [ContextObj, Sort] _lib.Z3_get_datatype_sort_constructor.restype = FuncDecl _lib.Z3_get_datatype_sort_constructor.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_get_datatype_sort_recognizer.restype = FuncDecl _lib.Z3_get_datatype_sort_recognizer.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_get_datatype_sort_constructor_accessor.restype = FuncDecl _lib.Z3_get_datatype_sort_constructor_accessor.argtypes = [ContextObj, Sort, ctypes.c_uint, ctypes.c_uint] _lib.Z3_datatype_update_field.restype = Ast _lib.Z3_datatype_update_field.argtypes = [ContextObj, FuncDecl, Ast, Ast] _lib.Z3_get_relation_arity.restype = ctypes.c_uint _lib.Z3_get_relation_arity.argtypes = [ContextObj, Sort] _lib.Z3_get_relation_column.restype = Sort _lib.Z3_get_relation_column.argtypes = [ContextObj, Sort, ctypes.c_uint] _lib.Z3_mk_atmost.restype = Ast _lib.Z3_mk_atmost.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint] _lib.Z3_mk_atleast.restype = Ast _lib.Z3_mk_atleast.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.c_uint] _lib.Z3_mk_pble.restype = Ast _lib.Z3_mk_pble.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_int), ctypes.c_int] _lib.Z3_mk_pbge.restype = Ast _lib.Z3_mk_pbge.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_int), ctypes.c_int] _lib.Z3_mk_pbeq.restype = Ast _lib.Z3_mk_pbeq.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_int), ctypes.c_int] _lib.Z3_func_decl_to_ast.restype = Ast _lib.Z3_func_decl_to_ast.argtypes = [ContextObj, FuncDecl] _lib.Z3_is_eq_func_decl.restype = ctypes.c_bool _lib.Z3_is_eq_func_decl.argtypes = [ContextObj, FuncDecl, FuncDecl] _lib.Z3_get_func_decl_id.restype = ctypes.c_uint _lib.Z3_get_func_decl_id.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_name.restype = Symbol _lib.Z3_get_decl_name.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_kind.restype = ctypes.c_uint _lib.Z3_get_decl_kind.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_domain_size.restype = ctypes.c_uint _lib.Z3_get_domain_size.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_arity.restype = ctypes.c_uint _lib.Z3_get_arity.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_domain.restype = Sort _lib.Z3_get_domain.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_range.restype = Sort _lib.Z3_get_range.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_num_parameters.restype = ctypes.c_uint _lib.Z3_get_decl_num_parameters.argtypes = [ContextObj, FuncDecl] _lib.Z3_get_decl_parameter_kind.restype = ctypes.c_uint _lib.Z3_get_decl_parameter_kind.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_int_parameter.restype = ctypes.c_int _lib.Z3_get_decl_int_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_double_parameter.restype = ctypes.c_double _lib.Z3_get_decl_double_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_symbol_parameter.restype = Symbol _lib.Z3_get_decl_symbol_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_sort_parameter.restype = Sort _lib.Z3_get_decl_sort_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_ast_parameter.restype = Ast _lib.Z3_get_decl_ast_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_func_decl_parameter.restype = FuncDecl _lib.Z3_get_decl_func_decl_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_get_decl_rational_parameter.restype = ctypes.c_char_p _lib.Z3_get_decl_rational_parameter.argtypes = [ContextObj, FuncDecl, ctypes.c_uint] _lib.Z3_app_to_ast.restype = Ast _lib.Z3_app_to_ast.argtypes = [ContextObj, Ast] _lib.Z3_get_app_decl.restype = FuncDecl _lib.Z3_get_app_decl.argtypes = [ContextObj, Ast] _lib.Z3_get_app_num_args.restype = ctypes.c_uint _lib.Z3_get_app_num_args.argtypes = [ContextObj, Ast] _lib.Z3_get_app_arg.restype = Ast _lib.Z3_get_app_arg.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_is_eq_ast.restype = ctypes.c_bool _lib.Z3_is_eq_ast.argtypes = [ContextObj, Ast, Ast] _lib.Z3_get_ast_id.restype = ctypes.c_uint _lib.Z3_get_ast_id.argtypes = [ContextObj, Ast] _lib.Z3_get_ast_hash.restype = ctypes.c_uint _lib.Z3_get_ast_hash.argtypes = [ContextObj, Ast] _lib.Z3_get_sort.restype = Sort _lib.Z3_get_sort.argtypes = [ContextObj, Ast] _lib.Z3_is_well_sorted.restype = ctypes.c_bool _lib.Z3_is_well_sorted.argtypes = [ContextObj, Ast] _lib.Z3_get_bool_value.restype = ctypes.c_int _lib.Z3_get_bool_value.argtypes = [ContextObj, Ast] _lib.Z3_get_ast_kind.restype = ctypes.c_uint _lib.Z3_get_ast_kind.argtypes = [ContextObj, Ast] _lib.Z3_is_app.restype = ctypes.c_bool _lib.Z3_is_app.argtypes = [ContextObj, Ast] _lib.Z3_is_numeral_ast.restype = ctypes.c_bool _lib.Z3_is_numeral_ast.argtypes = [ContextObj, Ast] _lib.Z3_is_algebraic_number.restype = ctypes.c_bool _lib.Z3_is_algebraic_number.argtypes = [ContextObj, Ast] _lib.Z3_to_app.restype = Ast _lib.Z3_to_app.argtypes = [ContextObj, Ast] _lib.Z3_to_func_decl.restype = FuncDecl _lib.Z3_to_func_decl.argtypes = [ContextObj, Ast] _lib.Z3_get_numeral_string.restype = ctypes.c_char_p _lib.Z3_get_numeral_string.argtypes = [ContextObj, Ast] _lib.Z3_get_numeral_decimal_string.restype = ctypes.c_char_p _lib.Z3_get_numeral_decimal_string.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_numeral_double.restype = ctypes.c_double _lib.Z3_get_numeral_double.argtypes = [ContextObj, Ast] _lib.Z3_get_numerator.restype = Ast _lib.Z3_get_numerator.argtypes = [ContextObj, Ast] _lib.Z3_get_denominator.restype = Ast _lib.Z3_get_denominator.argtypes = [ContextObj, Ast] _lib.Z3_get_numeral_small.restype = ctypes.c_bool _lib.Z3_get_numeral_small.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong), ctypes.POINTER(ctypes.c_longlong)] _lib.Z3_get_numeral_int.restype = ctypes.c_bool _lib.Z3_get_numeral_int.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_int)] _lib.Z3_get_numeral_uint.restype = ctypes.c_bool _lib.Z3_get_numeral_uint.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_uint)] _lib.Z3_get_numeral_uint64.restype = ctypes.c_bool _lib.Z3_get_numeral_uint64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_ulonglong)] _lib.Z3_get_numeral_int64.restype = ctypes.c_bool _lib.Z3_get_numeral_int64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong)] _lib.Z3_get_numeral_rational_int64.restype = ctypes.c_bool _lib.Z3_get_numeral_rational_int64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong), ctypes.POINTER(ctypes.c_longlong)] _lib.Z3_get_algebraic_number_lower.restype = Ast _lib.Z3_get_algebraic_number_lower.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_algebraic_number_upper.restype = Ast _lib.Z3_get_algebraic_number_upper.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_pattern_to_ast.restype = Ast _lib.Z3_pattern_to_ast.argtypes = [ContextObj, Pattern] _lib.Z3_get_pattern_num_terms.restype = ctypes.c_uint _lib.Z3_get_pattern_num_terms.argtypes = [ContextObj, Pattern] _lib.Z3_get_pattern.restype = Ast _lib.Z3_get_pattern.argtypes = [ContextObj, Pattern, ctypes.c_uint] _lib.Z3_get_index_value.restype = ctypes.c_uint _lib.Z3_get_index_value.argtypes = [ContextObj, Ast] _lib.Z3_is_quantifier_forall.restype = ctypes.c_bool _lib.Z3_is_quantifier_forall.argtypes = [ContextObj, Ast] _lib.Z3_is_quantifier_exists.restype = ctypes.c_bool _lib.Z3_is_quantifier_exists.argtypes = [ContextObj, Ast] _lib.Z3_is_lambda.restype = ctypes.c_bool _lib.Z3_is_lambda.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_weight.restype = ctypes.c_uint _lib.Z3_get_quantifier_weight.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_num_patterns.restype = ctypes.c_uint _lib.Z3_get_quantifier_num_patterns.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_pattern_ast.restype = Pattern _lib.Z3_get_quantifier_pattern_ast.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_num_no_patterns.restype = ctypes.c_uint _lib.Z3_get_quantifier_num_no_patterns.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_no_pattern_ast.restype = Ast _lib.Z3_get_quantifier_no_pattern_ast.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_num_bound.restype = ctypes.c_uint _lib.Z3_get_quantifier_num_bound.argtypes = [ContextObj, Ast] _lib.Z3_get_quantifier_bound_name.restype = Symbol _lib.Z3_get_quantifier_bound_name.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_bound_sort.restype = Sort _lib.Z3_get_quantifier_bound_sort.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_get_quantifier_body.restype = Ast _lib.Z3_get_quantifier_body.argtypes = [ContextObj, Ast] _lib.Z3_simplify.restype = Ast _lib.Z3_simplify.argtypes = [ContextObj, Ast] _lib.Z3_simplify_ex.restype = Ast _lib.Z3_simplify_ex.argtypes = [ContextObj, Ast, Params] _lib.Z3_simplify_get_help.restype = ctypes.c_char_p _lib.Z3_simplify_get_help.argtypes = [ContextObj] _lib.Z3_simplify_get_param_descrs.restype = ParamDescrs _lib.Z3_simplify_get_param_descrs.argtypes = [ContextObj] _lib.Z3_update_term.restype = Ast _lib.Z3_update_term.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_substitute.restype = Ast _lib.Z3_substitute.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(Ast)] _lib.Z3_substitute_vars.restype = Ast _lib.Z3_substitute_vars.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_translate.restype = Ast _lib.Z3_translate.argtypes = [ContextObj, Ast, ContextObj] _lib.Z3_mk_model.restype = Model _lib.Z3_mk_model.argtypes = [ContextObj] _lib.Z3_model_inc_ref.argtypes = [ContextObj, Model] _lib.Z3_model_dec_ref.argtypes = [ContextObj, Model] _lib.Z3_model_eval.restype = ctypes.c_bool _lib.Z3_model_eval.argtypes = [ContextObj, Model, Ast, ctypes.c_bool, ctypes.POINTER(Ast)] _lib.Z3_model_get_const_interp.restype = Ast _lib.Z3_model_get_const_interp.argtypes = [ContextObj, Model, FuncDecl] _lib.Z3_model_has_interp.restype = ctypes.c_bool _lib.Z3_model_has_interp.argtypes = [ContextObj, Model, FuncDecl] _lib.Z3_model_get_func_interp.restype = FuncInterpObj _lib.Z3_model_get_func_interp.argtypes = [ContextObj, Model, FuncDecl] _lib.Z3_model_get_num_consts.restype = ctypes.c_uint _lib.Z3_model_get_num_consts.argtypes = [ContextObj, Model] _lib.Z3_model_get_const_decl.restype = FuncDecl _lib.Z3_model_get_const_decl.argtypes = [ContextObj, Model, ctypes.c_uint] _lib.Z3_model_get_num_funcs.restype = ctypes.c_uint _lib.Z3_model_get_num_funcs.argtypes = [ContextObj, Model] _lib.Z3_model_get_func_decl.restype = FuncDecl _lib.Z3_model_get_func_decl.argtypes = [ContextObj, Model, ctypes.c_uint] _lib.Z3_model_get_num_sorts.restype = ctypes.c_uint _lib.Z3_model_get_num_sorts.argtypes = [ContextObj, Model] _lib.Z3_model_get_sort.restype = Sort _lib.Z3_model_get_sort.argtypes = [ContextObj, Model, ctypes.c_uint] _lib.Z3_model_get_sort_universe.restype = AstVectorObj _lib.Z3_model_get_sort_universe.argtypes = [ContextObj, Model, Sort] _lib.Z3_model_translate.restype = Model _lib.Z3_model_translate.argtypes = [ContextObj, Model, ContextObj] _lib.Z3_is_as_array.restype = ctypes.c_bool _lib.Z3_is_as_array.argtypes = [ContextObj, Ast] _lib.Z3_get_as_array_func_decl.restype = FuncDecl _lib.Z3_get_as_array_func_decl.argtypes = [ContextObj, Ast] _lib.Z3_add_func_interp.restype = FuncInterpObj _lib.Z3_add_func_interp.argtypes = [ContextObj, Model, FuncDecl, Ast] _lib.Z3_add_const_interp.argtypes = [ContextObj, Model, FuncDecl, Ast] _lib.Z3_func_interp_inc_ref.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_dec_ref.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_get_num_entries.restype = ctypes.c_uint _lib.Z3_func_interp_get_num_entries.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_get_entry.restype = FuncEntryObj _lib.Z3_func_interp_get_entry.argtypes = [ContextObj, FuncInterpObj, ctypes.c_uint] _lib.Z3_func_interp_get_else.restype = Ast _lib.Z3_func_interp_get_else.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_set_else.argtypes = [ContextObj, FuncInterpObj, Ast] _lib.Z3_func_interp_get_arity.restype = ctypes.c_uint _lib.Z3_func_interp_get_arity.argtypes = [ContextObj, FuncInterpObj] _lib.Z3_func_interp_add_entry.argtypes = [ContextObj, FuncInterpObj, AstVectorObj, Ast] _lib.Z3_func_entry_inc_ref.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_dec_ref.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_get_value.restype = Ast _lib.Z3_func_entry_get_value.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_get_num_args.restype = ctypes.c_uint _lib.Z3_func_entry_get_num_args.argtypes = [ContextObj, FuncEntryObj] _lib.Z3_func_entry_get_arg.restype = Ast _lib.Z3_func_entry_get_arg.argtypes = [ContextObj, FuncEntryObj, ctypes.c_uint] _lib.Z3_open_log.restype = ctypes.c_int _lib.Z3_open_log.argtypes = [ctypes.c_char_p] _lib.Z3_append_log.argtypes = [ctypes.c_char_p] _lib.Z3_close_log.argtypes = [] _lib.Z3_toggle_warning_messages.argtypes = [ctypes.c_bool] _lib.Z3_set_ast_print_mode.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_ast_to_string.restype = ctypes.c_char_p _lib.Z3_ast_to_string.argtypes = [ContextObj, Ast] _lib.Z3_pattern_to_string.restype = ctypes.c_char_p _lib.Z3_pattern_to_string.argtypes = [ContextObj, Pattern] _lib.Z3_sort_to_string.restype = ctypes.c_char_p _lib.Z3_sort_to_string.argtypes = [ContextObj, Sort] _lib.Z3_func_decl_to_string.restype = ctypes.c_char_p _lib.Z3_func_decl_to_string.argtypes = [ContextObj, FuncDecl] _lib.Z3_model_to_string.restype = ctypes.c_char_p _lib.Z3_model_to_string.argtypes = [ContextObj, Model] _lib.Z3_benchmark_to_smtlib_string.restype = ctypes.c_char_p _lib.Z3_benchmark_to_smtlib_string.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_parse_smtlib2_string.restype = AstVectorObj _lib.Z3_parse_smtlib2_string.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(FuncDecl)] _lib.Z3_parse_smtlib2_file.restype = AstVectorObj _lib.Z3_parse_smtlib2_file.argtypes = [ContextObj, ctypes.c_char_p, ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(Sort), ctypes.c_uint, ctypes.POINTER(Symbol), ctypes.POINTER(FuncDecl)] _lib.Z3_eval_smtlib2_string.restype = ctypes.c_char_p _lib.Z3_eval_smtlib2_string.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_get_error_code.restype = ctypes.c_uint _lib.Z3_get_error_code.argtypes = [ContextObj] _lib.Z3_set_error.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_get_error_msg.restype = ctypes.c_char_p _lib.Z3_get_error_msg.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_get_version.argtypes = [ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)] _lib.Z3_get_full_version.restype = ctypes.c_char_p _lib.Z3_get_full_version.argtypes = [] _lib.Z3_enable_trace.argtypes = [ctypes.c_char_p] _lib.Z3_disable_trace.argtypes = [ctypes.c_char_p] _lib.Z3_reset_memory.argtypes = [] _lib.Z3_finalize_memory.argtypes = [] _lib.Z3_mk_goal.restype = GoalObj _lib.Z3_mk_goal.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_bool, ctypes.c_bool] _lib.Z3_goal_inc_ref.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_dec_ref.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_precision.restype = ctypes.c_uint _lib.Z3_goal_precision.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_assert.argtypes = [ContextObj, GoalObj, Ast] _lib.Z3_goal_inconsistent.restype = ctypes.c_bool _lib.Z3_goal_inconsistent.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_depth.restype = ctypes.c_uint _lib.Z3_goal_depth.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_reset.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_size.restype = ctypes.c_uint _lib.Z3_goal_size.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_formula.restype = Ast _lib.Z3_goal_formula.argtypes = [ContextObj, GoalObj, ctypes.c_uint] _lib.Z3_goal_num_exprs.restype = ctypes.c_uint _lib.Z3_goal_num_exprs.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_is_decided_sat.restype = ctypes.c_bool _lib.Z3_goal_is_decided_sat.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_is_decided_unsat.restype = ctypes.c_bool _lib.Z3_goal_is_decided_unsat.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_translate.restype = GoalObj _lib.Z3_goal_translate.argtypes = [ContextObj, GoalObj, ContextObj] _lib.Z3_goal_convert_model.restype = Model _lib.Z3_goal_convert_model.argtypes = [ContextObj, GoalObj, Model] _lib.Z3_goal_to_string.restype = ctypes.c_char_p _lib.Z3_goal_to_string.argtypes = [ContextObj, GoalObj] _lib.Z3_goal_to_dimacs_string.restype = ctypes.c_char_p _lib.Z3_goal_to_dimacs_string.argtypes = [ContextObj, GoalObj] _lib.Z3_mk_tactic.restype = TacticObj _lib.Z3_mk_tactic.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_tactic_inc_ref.argtypes = [ContextObj, TacticObj] _lib.Z3_tactic_dec_ref.argtypes = [ContextObj, TacticObj] _lib.Z3_mk_probe.restype = ProbeObj _lib.Z3_mk_probe.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_probe_inc_ref.argtypes = [ContextObj, ProbeObj] _lib.Z3_probe_dec_ref.argtypes = [ContextObj, ProbeObj] _lib.Z3_tactic_and_then.restype = TacticObj _lib.Z3_tactic_and_then.argtypes = [ContextObj, TacticObj, TacticObj] _lib.Z3_tactic_or_else.restype = TacticObj _lib.Z3_tactic_or_else.argtypes = [ContextObj, TacticObj, TacticObj] _lib.Z3_tactic_par_or.restype = TacticObj _lib.Z3_tactic_par_or.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(TacticObj)] _lib.Z3_tactic_par_and_then.restype = TacticObj _lib.Z3_tactic_par_and_then.argtypes = [ContextObj, TacticObj, TacticObj] _lib.Z3_tactic_try_for.restype = TacticObj _lib.Z3_tactic_try_for.argtypes = [ContextObj, TacticObj, ctypes.c_uint] _lib.Z3_tactic_when.restype = TacticObj _lib.Z3_tactic_when.argtypes = [ContextObj, ProbeObj, TacticObj] _lib.Z3_tactic_cond.restype = TacticObj _lib.Z3_tactic_cond.argtypes = [ContextObj, ProbeObj, TacticObj, TacticObj] _lib.Z3_tactic_repeat.restype = TacticObj _lib.Z3_tactic_repeat.argtypes = [ContextObj, TacticObj, ctypes.c_uint] _lib.Z3_tactic_skip.restype = TacticObj _lib.Z3_tactic_skip.argtypes = [ContextObj] _lib.Z3_tactic_fail.restype = TacticObj _lib.Z3_tactic_fail.argtypes = [ContextObj] _lib.Z3_tactic_fail_if.restype = TacticObj _lib.Z3_tactic_fail_if.argtypes = [ContextObj, ProbeObj] _lib.Z3_tactic_fail_if_not_decided.restype = TacticObj _lib.Z3_tactic_fail_if_not_decided.argtypes = [ContextObj] _lib.Z3_tactic_using_params.restype = TacticObj _lib.Z3_tactic_using_params.argtypes = [ContextObj, TacticObj, Params] _lib.Z3_probe_const.restype = ProbeObj _lib.Z3_probe_const.argtypes = [ContextObj, ctypes.c_double] _lib.Z3_probe_lt.restype = ProbeObj _lib.Z3_probe_lt.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_gt.restype = ProbeObj _lib.Z3_probe_gt.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_le.restype = ProbeObj _lib.Z3_probe_le.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_ge.restype = ProbeObj _lib.Z3_probe_ge.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_eq.restype = ProbeObj _lib.Z3_probe_eq.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_and.restype = ProbeObj _lib.Z3_probe_and.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_or.restype = ProbeObj _lib.Z3_probe_or.argtypes = [ContextObj, ProbeObj, ProbeObj] _lib.Z3_probe_not.restype = ProbeObj _lib.Z3_probe_not.argtypes = [ContextObj, ProbeObj] _lib.Z3_get_num_tactics.restype = ctypes.c_uint _lib.Z3_get_num_tactics.argtypes = [ContextObj] _lib.Z3_get_tactic_name.restype = ctypes.c_char_p _lib.Z3_get_tactic_name.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_get_num_probes.restype = ctypes.c_uint _lib.Z3_get_num_probes.argtypes = [ContextObj] _lib.Z3_get_probe_name.restype = ctypes.c_char_p _lib.Z3_get_probe_name.argtypes = [ContextObj, ctypes.c_uint] _lib.Z3_tactic_get_help.restype = ctypes.c_char_p _lib.Z3_tactic_get_help.argtypes = [ContextObj, TacticObj] _lib.Z3_tactic_get_param_descrs.restype = ParamDescrs _lib.Z3_tactic_get_param_descrs.argtypes = [ContextObj, TacticObj] _lib.Z3_tactic_get_descr.restype = ctypes.c_char_p _lib.Z3_tactic_get_descr.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_probe_get_descr.restype = ctypes.c_char_p _lib.Z3_probe_get_descr.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_probe_apply.restype = ctypes.c_double _lib.Z3_probe_apply.argtypes = [ContextObj, ProbeObj, GoalObj] _lib.Z3_tactic_apply.restype = ApplyResultObj _lib.Z3_tactic_apply.argtypes = [ContextObj, TacticObj, GoalObj] _lib.Z3_tactic_apply_ex.restype = ApplyResultObj _lib.Z3_tactic_apply_ex.argtypes = [ContextObj, TacticObj, GoalObj, Params] _lib.Z3_apply_result_inc_ref.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_dec_ref.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_to_string.restype = ctypes.c_char_p _lib.Z3_apply_result_to_string.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_get_num_subgoals.restype = ctypes.c_uint _lib.Z3_apply_result_get_num_subgoals.argtypes = [ContextObj, ApplyResultObj] _lib.Z3_apply_result_get_subgoal.restype = GoalObj _lib.Z3_apply_result_get_subgoal.argtypes = [ContextObj, ApplyResultObj, ctypes.c_uint] _lib.Z3_mk_solver.restype = SolverObj _lib.Z3_mk_solver.argtypes = [ContextObj] _lib.Z3_mk_simple_solver.restype = SolverObj _lib.Z3_mk_simple_solver.argtypes = [ContextObj] _lib.Z3_mk_solver_for_logic.restype = SolverObj _lib.Z3_mk_solver_for_logic.argtypes = [ContextObj, Symbol] _lib.Z3_mk_solver_from_tactic.restype = SolverObj _lib.Z3_mk_solver_from_tactic.argtypes = [ContextObj, TacticObj] _lib.Z3_solver_translate.restype = SolverObj _lib.Z3_solver_translate.argtypes = [ContextObj, SolverObj, ContextObj] _lib.Z3_solver_import_model_converter.argtypes = [ContextObj, SolverObj, SolverObj] _lib.Z3_solver_get_help.restype = ctypes.c_char_p _lib.Z3_solver_get_help.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_param_descrs.restype = ParamDescrs _lib.Z3_solver_get_param_descrs.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_set_params.argtypes = [ContextObj, SolverObj, Params] _lib.Z3_solver_inc_ref.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_dec_ref.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_interrupt.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_push.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_pop.argtypes = [ContextObj, SolverObj, ctypes.c_uint] _lib.Z3_solver_reset.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_num_scopes.restype = ctypes.c_uint _lib.Z3_solver_get_num_scopes.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_assert.argtypes = [ContextObj, SolverObj, Ast] _lib.Z3_solver_assert_and_track.argtypes = [ContextObj, SolverObj, Ast, Ast] _lib.Z3_solver_from_file.argtypes = [ContextObj, SolverObj, ctypes.c_char_p] _lib.Z3_solver_from_string.argtypes = [ContextObj, SolverObj, ctypes.c_char_p] _lib.Z3_solver_get_assertions.restype = AstVectorObj _lib.Z3_solver_get_assertions.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_units.restype = AstVectorObj _lib.Z3_solver_get_units.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_trail.restype = AstVectorObj _lib.Z3_solver_get_trail.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_non_units.restype = AstVectorObj _lib.Z3_solver_get_non_units.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_levels.argtypes = [ContextObj, SolverObj, AstVectorObj, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint)] _lib.Z3_solver_check.restype = ctypes.c_int _lib.Z3_solver_check.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_check_assumptions.restype = ctypes.c_int _lib.Z3_solver_check_assumptions.argtypes = [ContextObj, SolverObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_get_implied_equalities.restype = ctypes.c_int _lib.Z3_get_implied_equalities.argtypes = [ContextObj, SolverObj, ctypes.c_uint, ctypes.POINTER(Ast), ctypes.POINTER(ctypes.c_uint)] _lib.Z3_solver_get_consequences.restype = ctypes.c_int _lib.Z3_solver_get_consequences.argtypes = [ContextObj, SolverObj, AstVectorObj, AstVectorObj, AstVectorObj] _lib.Z3_solver_cube.restype = AstVectorObj _lib.Z3_solver_cube.argtypes = [ContextObj, SolverObj, AstVectorObj, ctypes.c_uint] _lib.Z3_solver_get_model.restype = Model _lib.Z3_solver_get_model.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_proof.restype = Ast _lib.Z3_solver_get_proof.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_unsat_core.restype = AstVectorObj _lib.Z3_solver_get_unsat_core.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_reason_unknown.restype = ctypes.c_char_p _lib.Z3_solver_get_reason_unknown.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_get_statistics.restype = StatsObj _lib.Z3_solver_get_statistics.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_to_string.restype = ctypes.c_char_p _lib.Z3_solver_to_string.argtypes = [ContextObj, SolverObj] _lib.Z3_solver_to_dimacs_string.restype = ctypes.c_char_p _lib.Z3_solver_to_dimacs_string.argtypes = [ContextObj, SolverObj, ctypes.c_bool] _lib.Z3_stats_to_string.restype = ctypes.c_char_p _lib.Z3_stats_to_string.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_inc_ref.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_dec_ref.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_size.restype = ctypes.c_uint _lib.Z3_stats_size.argtypes = [ContextObj, StatsObj] _lib.Z3_stats_get_key.restype = ctypes.c_char_p _lib.Z3_stats_get_key.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_is_uint.restype = ctypes.c_bool _lib.Z3_stats_is_uint.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_is_double.restype = ctypes.c_bool _lib.Z3_stats_is_double.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_get_uint_value.restype = ctypes.c_uint _lib.Z3_stats_get_uint_value.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_stats_get_double_value.restype = ctypes.c_double _lib.Z3_stats_get_double_value.argtypes = [ContextObj, StatsObj, ctypes.c_uint] _lib.Z3_get_estimated_alloc_size.restype = ctypes.c_ulonglong _lib.Z3_get_estimated_alloc_size.argtypes = [] _lib.Z3_mk_ast_vector.restype = AstVectorObj _lib.Z3_mk_ast_vector.argtypes = [ContextObj] _lib.Z3_ast_vector_inc_ref.argtypes = [ContextObj, AstVectorObj] _lib.Z3_ast_vector_dec_ref.argtypes = [ContextObj, AstVectorObj] _lib.Z3_ast_vector_size.restype = ctypes.c_uint _lib.Z3_ast_vector_size.argtypes = [ContextObj, AstVectorObj] _lib.Z3_ast_vector_get.restype = Ast _lib.Z3_ast_vector_get.argtypes = [ContextObj, AstVectorObj, ctypes.c_uint] _lib.Z3_ast_vector_set.argtypes = [ContextObj, AstVectorObj, ctypes.c_uint, Ast] _lib.Z3_ast_vector_resize.argtypes = [ContextObj, AstVectorObj, ctypes.c_uint] _lib.Z3_ast_vector_push.argtypes = [ContextObj, AstVectorObj, Ast] _lib.Z3_ast_vector_translate.restype = AstVectorObj _lib.Z3_ast_vector_translate.argtypes = [ContextObj, AstVectorObj, ContextObj] _lib.Z3_ast_vector_to_string.restype = ctypes.c_char_p _lib.Z3_ast_vector_to_string.argtypes = [ContextObj, AstVectorObj] _lib.Z3_mk_ast_map.restype = AstMapObj _lib.Z3_mk_ast_map.argtypes = [ContextObj] _lib.Z3_ast_map_inc_ref.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_dec_ref.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_contains.restype = ctypes.c_bool _lib.Z3_ast_map_contains.argtypes = [ContextObj, AstMapObj, Ast] _lib.Z3_ast_map_find.restype = Ast _lib.Z3_ast_map_find.argtypes = [ContextObj, AstMapObj, Ast] _lib.Z3_ast_map_insert.argtypes = [ContextObj, AstMapObj, Ast, Ast] _lib.Z3_ast_map_erase.argtypes = [ContextObj, AstMapObj, Ast] _lib.Z3_ast_map_reset.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_size.restype = ctypes.c_uint _lib.Z3_ast_map_size.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_keys.restype = AstVectorObj _lib.Z3_ast_map_keys.argtypes = [ContextObj, AstMapObj] _lib.Z3_ast_map_to_string.restype = ctypes.c_char_p _lib.Z3_ast_map_to_string.argtypes = [ContextObj, AstMapObj] _lib.Z3_algebraic_is_value.restype = ctypes.c_bool _lib.Z3_algebraic_is_value.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_is_pos.restype = ctypes.c_bool _lib.Z3_algebraic_is_pos.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_is_neg.restype = ctypes.c_bool _lib.Z3_algebraic_is_neg.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_is_zero.restype = ctypes.c_bool _lib.Z3_algebraic_is_zero.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_sign.restype = ctypes.c_int _lib.Z3_algebraic_sign.argtypes = [ContextObj, Ast] _lib.Z3_algebraic_add.restype = Ast _lib.Z3_algebraic_add.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_sub.restype = Ast _lib.Z3_algebraic_sub.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_mul.restype = Ast _lib.Z3_algebraic_mul.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_div.restype = Ast _lib.Z3_algebraic_div.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_root.restype = Ast _lib.Z3_algebraic_root.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_algebraic_power.restype = Ast _lib.Z3_algebraic_power.argtypes = [ContextObj, Ast, ctypes.c_uint] _lib.Z3_algebraic_lt.restype = ctypes.c_bool _lib.Z3_algebraic_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_gt.restype = ctypes.c_bool _lib.Z3_algebraic_gt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_le.restype = ctypes.c_bool _lib.Z3_algebraic_le.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_ge.restype = ctypes.c_bool _lib.Z3_algebraic_ge.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_eq.restype = ctypes.c_bool _lib.Z3_algebraic_eq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_neq.restype = ctypes.c_bool _lib.Z3_algebraic_neq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_algebraic_roots.restype = AstVectorObj _lib.Z3_algebraic_roots.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_algebraic_eval.restype = ctypes.c_int _lib.Z3_algebraic_eval.argtypes = [ContextObj, Ast, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_polynomial_subresultants.restype = AstVectorObj _lib.Z3_polynomial_subresultants.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_rcf_del.argtypes = [ContextObj, RCFNumObj] _lib.Z3_rcf_mk_rational.restype = RCFNumObj _lib.Z3_rcf_mk_rational.argtypes = [ContextObj, ctypes.c_char_p] _lib.Z3_rcf_mk_small_int.restype = RCFNumObj _lib.Z3_rcf_mk_small_int.argtypes = [ContextObj, ctypes.c_int] _lib.Z3_rcf_mk_pi.restype = RCFNumObj _lib.Z3_rcf_mk_pi.argtypes = [ContextObj] _lib.Z3_rcf_mk_e.restype = RCFNumObj _lib.Z3_rcf_mk_e.argtypes = [ContextObj] _lib.Z3_rcf_mk_infinitesimal.restype = RCFNumObj _lib.Z3_rcf_mk_infinitesimal.argtypes = [ContextObj] _lib.Z3_rcf_mk_roots.restype = ctypes.c_uint _lib.Z3_rcf_mk_roots.argtypes = [ContextObj, ctypes.c_uint, ctypes.POINTER(RCFNumObj), ctypes.POINTER(RCFNumObj)] _lib.Z3_rcf_add.restype = RCFNumObj _lib.Z3_rcf_add.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_sub.restype = RCFNumObj _lib.Z3_rcf_sub.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_mul.restype = RCFNumObj _lib.Z3_rcf_mul.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_div.restype = RCFNumObj _lib.Z3_rcf_div.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_neg.restype = RCFNumObj _lib.Z3_rcf_neg.argtypes = [ContextObj, RCFNumObj] _lib.Z3_rcf_inv.restype = RCFNumObj _lib.Z3_rcf_inv.argtypes = [ContextObj, RCFNumObj] _lib.Z3_rcf_power.restype = RCFNumObj _lib.Z3_rcf_power.argtypes = [ContextObj, RCFNumObj, ctypes.c_uint] _lib.Z3_rcf_lt.restype = ctypes.c_bool _lib.Z3_rcf_lt.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_gt.restype = ctypes.c_bool _lib.Z3_rcf_gt.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_le.restype = ctypes.c_bool _lib.Z3_rcf_le.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_ge.restype = ctypes.c_bool _lib.Z3_rcf_ge.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_eq.restype = ctypes.c_bool _lib.Z3_rcf_eq.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_neq.restype = ctypes.c_bool _lib.Z3_rcf_neq.argtypes = [ContextObj, RCFNumObj, RCFNumObj] _lib.Z3_rcf_num_to_string.restype = ctypes.c_char_p _lib.Z3_rcf_num_to_string.argtypes = [ContextObj, RCFNumObj, ctypes.c_bool, ctypes.c_bool] _lib.Z3_rcf_num_to_decimal_string.restype = ctypes.c_char_p _lib.Z3_rcf_num_to_decimal_string.argtypes = [ContextObj, RCFNumObj, ctypes.c_uint] _lib.Z3_rcf_get_numerator_denominator.argtypes = [ContextObj, RCFNumObj, ctypes.POINTER(RCFNumObj), ctypes.POINTER(RCFNumObj)] _lib.Z3_mk_fixedpoint.restype = FixedpointObj _lib.Z3_mk_fixedpoint.argtypes = [ContextObj] _lib.Z3_fixedpoint_inc_ref.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_dec_ref.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_add_rule.argtypes = [ContextObj, FixedpointObj, Ast, Symbol] _lib.Z3_fixedpoint_add_fact.argtypes = [ContextObj, FixedpointObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint)] _lib.Z3_fixedpoint_assert.argtypes = [ContextObj, FixedpointObj, Ast] _lib.Z3_fixedpoint_query.restype = ctypes.c_int _lib.Z3_fixedpoint_query.argtypes = [ContextObj, FixedpointObj, Ast] _lib.Z3_fixedpoint_query_relations.restype = ctypes.c_int _lib.Z3_fixedpoint_query_relations.argtypes = [ContextObj, FixedpointObj, ctypes.c_uint, ctypes.POINTER(FuncDecl)] _lib.Z3_fixedpoint_get_answer.restype = Ast _lib.Z3_fixedpoint_get_answer.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_reason_unknown.restype = ctypes.c_char_p _lib.Z3_fixedpoint_get_reason_unknown.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_update_rule.argtypes = [ContextObj, FixedpointObj, Ast, Symbol] _lib.Z3_fixedpoint_get_num_levels.restype = ctypes.c_uint _lib.Z3_fixedpoint_get_num_levels.argtypes = [ContextObj, FixedpointObj, FuncDecl] _lib.Z3_fixedpoint_get_cover_delta.restype = Ast _lib.Z3_fixedpoint_get_cover_delta.argtypes = [ContextObj, FixedpointObj, ctypes.c_int, FuncDecl] _lib.Z3_fixedpoint_add_cover.argtypes = [ContextObj, FixedpointObj, ctypes.c_int, FuncDecl, Ast] _lib.Z3_fixedpoint_get_statistics.restype = StatsObj _lib.Z3_fixedpoint_get_statistics.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_register_relation.argtypes = [ContextObj, FixedpointObj, FuncDecl] _lib.Z3_fixedpoint_set_predicate_representation.argtypes = [ContextObj, FixedpointObj, FuncDecl, ctypes.c_uint, ctypes.POINTER(Symbol)] _lib.Z3_fixedpoint_get_rules.restype = AstVectorObj _lib.Z3_fixedpoint_get_rules.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_assertions.restype = AstVectorObj _lib.Z3_fixedpoint_get_assertions.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_set_params.argtypes = [ContextObj, FixedpointObj, Params] _lib.Z3_fixedpoint_get_help.restype = ctypes.c_char_p _lib.Z3_fixedpoint_get_help.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_param_descrs.restype = ParamDescrs _lib.Z3_fixedpoint_get_param_descrs.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_to_string.restype = ctypes.c_char_p _lib.Z3_fixedpoint_to_string.argtypes = [ContextObj, FixedpointObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_fixedpoint_from_string.restype = AstVectorObj _lib.Z3_fixedpoint_from_string.argtypes = [ContextObj, FixedpointObj, ctypes.c_char_p] _lib.Z3_fixedpoint_from_file.restype = AstVectorObj _lib.Z3_fixedpoint_from_file.argtypes = [ContextObj, FixedpointObj, ctypes.c_char_p] _lib.Z3_mk_optimize.restype = OptimizeObj _lib.Z3_mk_optimize.argtypes = [ContextObj] _lib.Z3_optimize_inc_ref.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_dec_ref.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_assert.argtypes = [ContextObj, OptimizeObj, Ast] _lib.Z3_optimize_assert_and_track.argtypes = [ContextObj, OptimizeObj, Ast, Ast] _lib.Z3_optimize_assert_soft.restype = ctypes.c_uint _lib.Z3_optimize_assert_soft.argtypes = [ContextObj, OptimizeObj, Ast, ctypes.c_char_p, Symbol] _lib.Z3_optimize_maximize.restype = ctypes.c_uint _lib.Z3_optimize_maximize.argtypes = [ContextObj, OptimizeObj, Ast] _lib.Z3_optimize_minimize.restype = ctypes.c_uint _lib.Z3_optimize_minimize.argtypes = [ContextObj, OptimizeObj, Ast] _lib.Z3_optimize_push.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_pop.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_check.restype = ctypes.c_int _lib.Z3_optimize_check.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint, ctypes.POINTER(Ast)] _lib.Z3_optimize_get_reason_unknown.restype = ctypes.c_char_p _lib.Z3_optimize_get_reason_unknown.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_model.restype = Model _lib.Z3_optimize_get_model.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_unsat_core.restype = AstVectorObj _lib.Z3_optimize_get_unsat_core.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_set_params.argtypes = [ContextObj, OptimizeObj, Params] _lib.Z3_optimize_get_param_descrs.restype = ParamDescrs _lib.Z3_optimize_get_param_descrs.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_lower.restype = Ast _lib.Z3_optimize_get_lower.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_get_upper.restype = Ast _lib.Z3_optimize_get_upper.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_get_lower_as_vector.restype = AstVectorObj _lib.Z3_optimize_get_lower_as_vector.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_get_upper_as_vector.restype = AstVectorObj _lib.Z3_optimize_get_upper_as_vector.argtypes = [ContextObj, OptimizeObj, ctypes.c_uint] _lib.Z3_optimize_to_string.restype = ctypes.c_char_p _lib.Z3_optimize_to_string.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_from_string.argtypes = [ContextObj, OptimizeObj, ctypes.c_char_p] _lib.Z3_optimize_from_file.argtypes = [ContextObj, OptimizeObj, ctypes.c_char_p] _lib.Z3_optimize_get_help.restype = ctypes.c_char_p _lib.Z3_optimize_get_help.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_statistics.restype = StatsObj _lib.Z3_optimize_get_statistics.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_assertions.restype = AstVectorObj _lib.Z3_optimize_get_assertions.argtypes = [ContextObj, OptimizeObj] _lib.Z3_optimize_get_objectives.restype = AstVectorObj _lib.Z3_optimize_get_objectives.argtypes = [ContextObj, OptimizeObj] _lib.Z3_mk_fpa_rounding_mode_sort.restype = Sort _lib.Z3_mk_fpa_rounding_mode_sort.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_nearest_ties_to_even.restype = Ast _lib.Z3_mk_fpa_round_nearest_ties_to_even.argtypes = [ContextObj] _lib.Z3_mk_fpa_rne.restype = Ast _lib.Z3_mk_fpa_rne.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_nearest_ties_to_away.restype = Ast _lib.Z3_mk_fpa_round_nearest_ties_to_away.argtypes = [ContextObj] _lib.Z3_mk_fpa_rna.restype = Ast _lib.Z3_mk_fpa_rna.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_toward_positive.restype = Ast _lib.Z3_mk_fpa_round_toward_positive.argtypes = [ContextObj] _lib.Z3_mk_fpa_rtp.restype = Ast _lib.Z3_mk_fpa_rtp.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_toward_negative.restype = Ast _lib.Z3_mk_fpa_round_toward_negative.argtypes = [ContextObj] _lib.Z3_mk_fpa_rtn.restype = Ast _lib.Z3_mk_fpa_rtn.argtypes = [ContextObj] _lib.Z3_mk_fpa_round_toward_zero.restype = Ast _lib.Z3_mk_fpa_round_toward_zero.argtypes = [ContextObj] _lib.Z3_mk_fpa_rtz.restype = Ast _lib.Z3_mk_fpa_rtz.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort.restype = Sort _lib.Z3_mk_fpa_sort.argtypes = [ContextObj, ctypes.c_uint, ctypes.c_uint] _lib.Z3_mk_fpa_sort_half.restype = Sort _lib.Z3_mk_fpa_sort_half.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_16.restype = Sort _lib.Z3_mk_fpa_sort_16.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_single.restype = Sort _lib.Z3_mk_fpa_sort_single.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_32.restype = Sort _lib.Z3_mk_fpa_sort_32.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_double.restype = Sort _lib.Z3_mk_fpa_sort_double.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_64.restype = Sort _lib.Z3_mk_fpa_sort_64.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_quadruple.restype = Sort _lib.Z3_mk_fpa_sort_quadruple.argtypes = [ContextObj] _lib.Z3_mk_fpa_sort_128.restype = Sort _lib.Z3_mk_fpa_sort_128.argtypes = [ContextObj] _lib.Z3_mk_fpa_nan.restype = Ast _lib.Z3_mk_fpa_nan.argtypes = [ContextObj, Sort] _lib.Z3_mk_fpa_inf.restype = Ast _lib.Z3_mk_fpa_inf.argtypes = [ContextObj, Sort, ctypes.c_bool] _lib.Z3_mk_fpa_zero.restype = Ast _lib.Z3_mk_fpa_zero.argtypes = [ContextObj, Sort, ctypes.c_bool] _lib.Z3_mk_fpa_fp.restype = Ast _lib.Z3_mk_fpa_fp.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_numeral_float.restype = Ast _lib.Z3_mk_fpa_numeral_float.argtypes = [ContextObj, ctypes.c_float, Sort] _lib.Z3_mk_fpa_numeral_double.restype = Ast _lib.Z3_mk_fpa_numeral_double.argtypes = [ContextObj, ctypes.c_double, Sort] _lib.Z3_mk_fpa_numeral_int.restype = Ast _lib.Z3_mk_fpa_numeral_int.argtypes = [ContextObj, ctypes.c_int, Sort] _lib.Z3_mk_fpa_numeral_int_uint.restype = Ast _lib.Z3_mk_fpa_numeral_int_uint.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_int, ctypes.c_uint, Sort] _lib.Z3_mk_fpa_numeral_int64_uint64.restype = Ast _lib.Z3_mk_fpa_numeral_int64_uint64.argtypes = [ContextObj, ctypes.c_bool, ctypes.c_longlong, ctypes.c_ulonglong, Sort] _lib.Z3_mk_fpa_abs.restype = Ast _lib.Z3_mk_fpa_abs.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_neg.restype = Ast _lib.Z3_mk_fpa_neg.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_add.restype = Ast _lib.Z3_mk_fpa_add.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_sub.restype = Ast _lib.Z3_mk_fpa_sub.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_mul.restype = Ast _lib.Z3_mk_fpa_mul.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_div.restype = Ast _lib.Z3_mk_fpa_div.argtypes = [ContextObj, Ast, Ast, Ast] _lib.Z3_mk_fpa_fma.restype = Ast _lib.Z3_mk_fpa_fma.argtypes = [ContextObj, Ast, Ast, Ast, Ast] _lib.Z3_mk_fpa_sqrt.restype = Ast _lib.Z3_mk_fpa_sqrt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_rem.restype = Ast _lib.Z3_mk_fpa_rem.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_round_to_integral.restype = Ast _lib.Z3_mk_fpa_round_to_integral.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_min.restype = Ast _lib.Z3_mk_fpa_min.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_max.restype = Ast _lib.Z3_mk_fpa_max.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_leq.restype = Ast _lib.Z3_mk_fpa_leq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_lt.restype = Ast _lib.Z3_mk_fpa_lt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_geq.restype = Ast _lib.Z3_mk_fpa_geq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_gt.restype = Ast _lib.Z3_mk_fpa_gt.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_eq.restype = Ast _lib.Z3_mk_fpa_eq.argtypes = [ContextObj, Ast, Ast] _lib.Z3_mk_fpa_is_normal.restype = Ast _lib.Z3_mk_fpa_is_normal.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_subnormal.restype = Ast _lib.Z3_mk_fpa_is_subnormal.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_zero.restype = Ast _lib.Z3_mk_fpa_is_zero.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_infinite.restype = Ast _lib.Z3_mk_fpa_is_infinite.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_nan.restype = Ast _lib.Z3_mk_fpa_is_nan.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_negative.restype = Ast _lib.Z3_mk_fpa_is_negative.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_is_positive.restype = Ast _lib.Z3_mk_fpa_is_positive.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_to_fp_bv.restype = Ast _lib.Z3_mk_fpa_to_fp_bv.argtypes = [ContextObj, Ast, Sort] _lib.Z3_mk_fpa_to_fp_float.restype = Ast _lib.Z3_mk_fpa_to_fp_float.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_fp_real.restype = Ast _lib.Z3_mk_fpa_to_fp_real.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_fp_signed.restype = Ast _lib.Z3_mk_fpa_to_fp_signed.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_fp_unsigned.restype = Ast _lib.Z3_mk_fpa_to_fp_unsigned.argtypes = [ContextObj, Ast, Ast, Sort] _lib.Z3_mk_fpa_to_ubv.restype = Ast _lib.Z3_mk_fpa_to_ubv.argtypes = [ContextObj, Ast, Ast, ctypes.c_uint] _lib.Z3_mk_fpa_to_sbv.restype = Ast _lib.Z3_mk_fpa_to_sbv.argtypes = [ContextObj, Ast, Ast, ctypes.c_uint] _lib.Z3_mk_fpa_to_real.restype = Ast _lib.Z3_mk_fpa_to_real.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_ebits.restype = ctypes.c_uint _lib.Z3_fpa_get_ebits.argtypes = [ContextObj, Sort] _lib.Z3_fpa_get_sbits.restype = ctypes.c_uint _lib.Z3_fpa_get_sbits.argtypes = [ContextObj, Sort] _lib.Z3_fpa_is_numeral_nan.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_nan.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_inf.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_inf.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_zero.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_zero.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_normal.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_normal.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_subnormal.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_subnormal.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_positive.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_positive.argtypes = [ContextObj, Ast] _lib.Z3_fpa_is_numeral_negative.restype = ctypes.c_bool _lib.Z3_fpa_is_numeral_negative.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_sign_bv.restype = Ast _lib.Z3_fpa_get_numeral_sign_bv.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_significand_bv.restype = Ast _lib.Z3_fpa_get_numeral_significand_bv.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_sign.restype = ctypes.c_bool _lib.Z3_fpa_get_numeral_sign.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_int)] _lib.Z3_fpa_get_numeral_significand_string.restype = ctypes.c_char_p _lib.Z3_fpa_get_numeral_significand_string.argtypes = [ContextObj, Ast] _lib.Z3_fpa_get_numeral_significand_uint64.restype = ctypes.c_bool _lib.Z3_fpa_get_numeral_significand_uint64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_ulonglong)] _lib.Z3_fpa_get_numeral_exponent_string.restype = ctypes.c_char_p _lib.Z3_fpa_get_numeral_exponent_string.argtypes = [ContextObj, Ast, ctypes.c_bool] _lib.Z3_fpa_get_numeral_exponent_int64.restype = ctypes.c_bool _lib.Z3_fpa_get_numeral_exponent_int64.argtypes = [ContextObj, Ast, ctypes.POINTER(ctypes.c_longlong), ctypes.c_bool] _lib.Z3_fpa_get_numeral_exponent_bv.restype = Ast _lib.Z3_fpa_get_numeral_exponent_bv.argtypes = [ContextObj, Ast, ctypes.c_bool] _lib.Z3_mk_fpa_to_ieee_bv.restype = Ast _lib.Z3_mk_fpa_to_ieee_bv.argtypes = [ContextObj, Ast] _lib.Z3_mk_fpa_to_fp_int_real.restype = Ast _lib.Z3_mk_fpa_to_fp_int_real.argtypes = [ContextObj, Ast, Ast, Ast, Sort] _lib.Z3_fixedpoint_query_from_lvl.restype = ctypes.c_int _lib.Z3_fixedpoint_query_from_lvl.argtypes = [ContextObj, FixedpointObj, Ast, ctypes.c_uint] _lib.Z3_fixedpoint_get_ground_sat_answer.restype = Ast _lib.Z3_fixedpoint_get_ground_sat_answer.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_rules_along_trace.restype = AstVectorObj _lib.Z3_fixedpoint_get_rules_along_trace.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_get_rule_names_along_trace.restype = Symbol _lib.Z3_fixedpoint_get_rule_names_along_trace.argtypes = [ContextObj, FixedpointObj] _lib.Z3_fixedpoint_add_invariant.argtypes = [ContextObj, FixedpointObj, FuncDecl, Ast] _lib.Z3_fixedpoint_get_reachable.restype = Ast _lib.Z3_fixedpoint_get_reachable.argtypes = [ContextObj, FixedpointObj, FuncDecl] _lib.Z3_qe_model_project.restype = Ast _lib.Z3_qe_model_project.argtypes = [ContextObj, Model, ctypes.c_uint, ctypes.POINTER(Ast), Ast] _lib.Z3_qe_model_project_skolem.restype = Ast _lib.Z3_qe_model_project_skolem.argtypes = [ContextObj, Model, ctypes.c_uint, ctypes.POINTER(Ast), Ast, AstMapObj] _lib.Z3_model_extrapolate.restype = Ast _lib.Z3_model_extrapolate.argtypes = [ContextObj, Model, Ast] _lib.Z3_qe_lite.restype = Ast _lib.Z3_qe_lite.argtypes = [ContextObj, AstVectorObj, Ast] class Elementaries: def __init__(self, f): self.f = f self.get_error_code = _lib.Z3_get_error_code self.get_error_message = _lib.Z3_get_error_msg self.OK = Z3_OK self.Exception = Z3Exception def Check(self, ctx): err = self.get_error_code(ctx) if err != self.OK: raise self.Exception(self.get_error_message(ctx, err)) def Z3_set_error_handler(ctx, hndlr, _elems=Elementaries(_lib.Z3_set_error_handler)): ceh = _error_handler_type(hndlr) _elems.f(ctx, ceh) _elems.Check(ctx) return ceh def Z3_global_param_set(a0, a1, _elems=Elementaries(_lib.Z3_global_param_set)): _elems.f(_str_to_bytes(a0), _str_to_bytes(a1)) def Z3_global_param_reset_all(_elems=Elementaries(_lib.Z3_global_param_reset_all)): _elems.f() def Z3_global_param_get(a0, a1, _elems=Elementaries(_lib.Z3_global_param_get)): r = _elems.f(_str_to_bytes(a0), _str_to_bytes(a1)) return r def Z3_mk_config(_elems=Elementaries(_lib.Z3_mk_config)): r = _elems.f() return r def Z3_del_config(a0, _elems=Elementaries(_lib.Z3_del_config)): _elems.f(a0) def Z3_set_param_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_set_param_value)): _elems.f(a0, _str_to_bytes(a1), _str_to_bytes(a2)) def Z3_mk_context(a0, _elems=Elementaries(_lib.Z3_mk_context)): r = _elems.f(a0) return r def Z3_mk_context_rc(a0, _elems=Elementaries(_lib.Z3_mk_context_rc)): r = _elems.f(a0) return r def Z3_del_context(a0, _elems=Elementaries(_lib.Z3_del_context)): _elems.f(a0) def Z3_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_update_param_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_update_param_value)): _elems.f(a0, _str_to_bytes(a1), _str_to_bytes(a2)) _elems.Check(a0) def Z3_interrupt(a0, _elems=Elementaries(_lib.Z3_interrupt)): _elems.f(a0) _elems.Check(a0) def Z3_mk_params(a0, _elems=Elementaries(_lib.Z3_mk_params)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_params_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_params_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_params_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_params_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_params_set_bool(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_bool)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_set_uint(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_uint)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_set_double(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_double)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_set_symbol(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_params_set_symbol)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_params_to_string(a0, a1, _elems=Elementaries(_lib.Z3_params_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_params_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_params_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_params_validate(a0, a1, a2, _elems=Elementaries(_lib.Z3_params_validate)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_param_descrs_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_param_descrs_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_param_descrs_get_kind(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_kind)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_param_descrs_size(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_param_descrs_get_name(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_name)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_param_descrs_get_documentation(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_documentation)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_param_descrs_get_documentation_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_param_descrs_get_documentation)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_param_descrs_to_string(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_param_descrs_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_param_descrs_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_int_symbol(a0, a1, _elems=Elementaries(_lib.Z3_mk_int_symbol)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_string_symbol(a0, a1, _elems=Elementaries(_lib.Z3_mk_string_symbol)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_mk_uninterpreted_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_uninterpreted_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bool_sort(a0, _elems=Elementaries(_lib.Z3_mk_bool_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_int_sort(a0, _elems=Elementaries(_lib.Z3_mk_int_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_real_sort(a0, _elems=Elementaries(_lib.Z3_mk_real_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_bv_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_bv_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_finite_domain_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_finite_domain_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_array_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_array_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_array_sort_n(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_array_sort_n)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_tuple_sort(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_tuple_sort)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_mk_enumeration_sort(a0, a1, a2, a3, a4, a5, _elems=Elementaries(_lib.Z3_mk_enumeration_sort)): r = _elems.f(a0, a1, a2, a3, a4, a5) _elems.Check(a0) return r def Z3_mk_list_sort(a0, a1, a2, a3, a4, a5, a6, a7, a8, _elems=Elementaries(_lib.Z3_mk_list_sort)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8) _elems.Check(a0) return r def Z3_mk_constructor(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_constructor)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_del_constructor(a0, a1, _elems=Elementaries(_lib.Z3_del_constructor)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_datatype(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_datatype)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_constructor_list(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_constructor_list)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_del_constructor_list(a0, a1, _elems=Elementaries(_lib.Z3_del_constructor_list)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_datatypes(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_datatypes)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_query_constructor(a0, a1, a2, a3, a4, a5, _elems=Elementaries(_lib.Z3_query_constructor)): _elems.f(a0, a1, a2, a3, a4, a5) _elems.Check(a0) def Z3_mk_func_decl(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_func_decl)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_app(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_app)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_const(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_const)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fresh_func_decl(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fresh_func_decl)): r = _elems.f(a0, _str_to_bytes(a1), a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fresh_const(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fresh_const)): r = _elems.f(a0, _str_to_bytes(a1), a2) _elems.Check(a0) return r def Z3_mk_rec_func_decl(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_rec_func_decl)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_add_rec_def(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_add_rec_def)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_mk_true(a0, _elems=Elementaries(_lib.Z3_mk_true)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_false(a0, _elems=Elementaries(_lib.Z3_mk_false)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_distinct(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_distinct)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_not(a0, a1, _elems=Elementaries(_lib.Z3_mk_not)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_ite(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_ite)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_iff(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_iff)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_implies(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_implies)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_xor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_xor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_and(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_and)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_or(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_or)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_mul(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_mul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_sub(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_sub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_unary_minus(a0, a1, _elems=Elementaries(_lib.Z3_mk_unary_minus)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_div(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_div)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_mod(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_mod)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_rem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_rem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_power(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_power)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_divides(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_divides)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int2real(a0, a1, _elems=Elementaries(_lib.Z3_mk_int2real)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_real2int(a0, a1, _elems=Elementaries(_lib.Z3_mk_real2int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_is_int(a0, a1, _elems=Elementaries(_lib.Z3_mk_is_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvnot(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvnot)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvredand(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvredand)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvredor(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvredor)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvand(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvand)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvxor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvxor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvnand(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvnand)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvnor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvnor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvxnor(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvxnor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvneg(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvneg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvadd(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvadd)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsub(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvmul(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvmul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvudiv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvudiv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsdiv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsdiv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvurem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvurem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsrem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsrem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsmod(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsmod)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvult(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvult)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvslt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvslt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvule(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvule)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsle(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsle)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvuge(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvuge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsge(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvugt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvugt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsgt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsgt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_concat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_concat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_extract(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_extract)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_sign_ext(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_sign_ext)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_zero_ext(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_zero_ext)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_repeat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_repeat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvshl(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvshl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvlshr(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvlshr)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvashr(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvashr)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_rotate_left(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_rotate_left)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_rotate_right(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_rotate_right)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_ext_rotate_left(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_ext_rotate_left)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_ext_rotate_right(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_ext_rotate_right)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int2bv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_int2bv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bv2int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bv2int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvadd_no_overflow(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_bvadd_no_overflow)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_bvadd_no_underflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvadd_no_underflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsub_no_overflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsub_no_overflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvsub_no_underflow(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_bvsub_no_underflow)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_bvsdiv_no_overflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvsdiv_no_overflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bvneg_no_overflow(a0, a1, _elems=Elementaries(_lib.Z3_mk_bvneg_no_overflow)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_bvmul_no_overflow(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_bvmul_no_overflow)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_bvmul_no_underflow(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bvmul_no_underflow)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_select(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_select)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_select_n(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_select_n)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_store(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_store)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_store_n(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_store_n)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_const_array(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_const_array)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_map(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_map)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_array_default(a0, a1, _elems=Elementaries(_lib.Z3_mk_array_default)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_as_array(a0, a1, _elems=Elementaries(_lib.Z3_mk_as_array)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_set_has_size(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_has_size)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_set_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_empty_set(a0, a1, _elems=Elementaries(_lib.Z3_mk_empty_set)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_full_set(a0, a1, _elems=Elementaries(_lib.Z3_mk_full_set)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_set_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_del(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_del)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_union(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_union)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_intersect(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_intersect)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_difference(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_difference)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_complement(a0, a1, _elems=Elementaries(_lib.Z3_mk_set_complement)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_set_member(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_member)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_set_subset(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_set_subset)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_array_ext(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_array_ext)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_numeral(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_numeral)): r = _elems.f(a0, _str_to_bytes(a1), a2) _elems.Check(a0) return r def Z3_mk_real(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_real)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_unsigned_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_unsigned_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_int64(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_int64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_unsigned_int64(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_unsigned_int64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bv_numeral(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bv_numeral)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_seq_sort(a0, a1, _elems=Elementaries(_lib.Z3_is_seq_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_seq_sort_basis(a0, a1, _elems=Elementaries(_lib.Z3_get_seq_sort_basis)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_sort(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_re_sort(a0, a1, _elems=Elementaries(_lib.Z3_is_re_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_re_sort_basis(a0, a1, _elems=Elementaries(_lib.Z3_get_re_sort_basis)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_string_sort(a0, _elems=Elementaries(_lib.Z3_mk_string_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_is_string_sort(a0, a1, _elems=Elementaries(_lib.Z3_is_string_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_string(a0, a1, _elems=Elementaries(_lib.Z3_mk_string)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_mk_lstring(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_lstring)): r = _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) return r def Z3_is_string(a0, a1, _elems=Elementaries(_lib.Z3_is_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_string(a0, a1, _elems=Elementaries(_lib.Z3_get_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_get_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_lstring(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_lstring)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_empty(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_empty)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_unit(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_unit)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_concat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_concat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_prefix(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_prefix)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_suffix(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_suffix)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_contains(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_contains)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_str_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_str_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_str_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_str_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_extract(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_seq_extract)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_seq_replace(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_seq_replace)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_seq_at(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_at)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_nth(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_nth)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_seq_length(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_length)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_index(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_seq_index)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_seq_last_index(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_last_index)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_str_to_int(a0, a1, _elems=Elementaries(_lib.Z3_mk_str_to_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_int_to_str(a0, a1, _elems=Elementaries(_lib.Z3_mk_int_to_str)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_to_re(a0, a1, _elems=Elementaries(_lib.Z3_mk_seq_to_re)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_seq_in_re(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_seq_in_re)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_plus(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_plus)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_star(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_star)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_option(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_option)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_union(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_union)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_concat(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_concat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_range(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_range)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_loop(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_re_loop)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_re_intersect(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_re_intersect)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_re_complement(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_complement)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_empty(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_empty)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_re_full(a0, a1, _elems=Elementaries(_lib.Z3_mk_re_full)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_linear_order(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_linear_order)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_partial_order(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_partial_order)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_piecewise_linear_order(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_piecewise_linear_order)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_tree_order(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_tree_order)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_transitive_closure(a0, a1, _elems=Elementaries(_lib.Z3_mk_transitive_closure)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_pattern(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_pattern)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_bound(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_bound)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_forall(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_mk_forall)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_mk_exists(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_mk_exists)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_mk_quantifier(a0, a1, a2, a3, a4, a5, a6, a7, a8, _elems=Elementaries(_lib.Z3_mk_quantifier)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8) _elems.Check(a0) return r def Z3_mk_quantifier_ex(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, _elems=Elementaries(_lib.Z3_mk_quantifier_ex)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) _elems.Check(a0) return r def Z3_mk_forall_const(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_forall_const)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_mk_exists_const(a0, a1, a2, a3, a4, a5, a6, _elems=Elementaries(_lib.Z3_mk_exists_const)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6) _elems.Check(a0) return r def Z3_mk_quantifier_const(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_mk_quantifier_const)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_mk_quantifier_const_ex(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, _elems=Elementaries(_lib.Z3_mk_quantifier_const_ex)): r = _elems.f(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) _elems.Check(a0) return r def Z3_mk_lambda(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_lambda)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_lambda_const(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_lambda_const)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_symbol_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_symbol_int(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_symbol_string(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_symbol_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_get_symbol_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_sort_name(a0, a1, _elems=Elementaries(_lib.Z3_get_sort_name)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_sort_id(a0, a1, _elems=Elementaries(_lib.Z3_get_sort_id)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_sort_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_sort_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_eq_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_is_eq_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_sort_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_sort_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_bv_sort_size(a0, a1, _elems=Elementaries(_lib.Z3_get_bv_sort_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_finite_domain_sort_size(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_finite_domain_sort_size)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_array_sort_domain(a0, a1, _elems=Elementaries(_lib.Z3_get_array_sort_domain)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_array_sort_range(a0, a1, _elems=Elementaries(_lib.Z3_get_array_sort_range)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_tuple_sort_mk_decl(a0, a1, _elems=Elementaries(_lib.Z3_get_tuple_sort_mk_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_tuple_sort_num_fields(a0, a1, _elems=Elementaries(_lib.Z3_get_tuple_sort_num_fields)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_tuple_sort_field_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_tuple_sort_field_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_datatype_sort_num_constructors(a0, a1, _elems=Elementaries(_lib.Z3_get_datatype_sort_num_constructors)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_datatype_sort_constructor(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_datatype_sort_constructor)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_datatype_sort_recognizer(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_datatype_sort_recognizer)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_datatype_sort_constructor_accessor(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_datatype_sort_constructor_accessor)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_datatype_update_field(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_datatype_update_field)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_relation_arity(a0, a1, _elems=Elementaries(_lib.Z3_get_relation_arity)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_relation_column(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_relation_column)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_atmost(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_atmost)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_atleast(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_atleast)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_pble(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_pble)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_pbge(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_pbge)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_pbeq(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_pbeq)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_func_decl_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_func_decl_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_eq_func_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_is_eq_func_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_func_decl_id(a0, a1, _elems=Elementaries(_lib.Z3_get_func_decl_id)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_name(a0, a1, _elems=Elementaries(_lib.Z3_get_decl_name)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_decl_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_domain_size(a0, a1, _elems=Elementaries(_lib.Z3_get_domain_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_arity(a0, a1, _elems=Elementaries(_lib.Z3_get_arity)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_domain(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_domain)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_range(a0, a1, _elems=Elementaries(_lib.Z3_get_range)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_num_parameters(a0, a1, _elems=Elementaries(_lib.Z3_get_decl_num_parameters)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_decl_parameter_kind(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_parameter_kind)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_int_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_int_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_double_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_double_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_symbol_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_symbol_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_sort_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_sort_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_ast_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_ast_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_func_decl_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_func_decl_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_decl_rational_parameter(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_rational_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_get_decl_rational_parameter_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_decl_rational_parameter)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_app_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_app_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_app_decl(a0, a1, _elems=Elementaries(_lib.Z3_get_app_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_app_num_args(a0, a1, _elems=Elementaries(_lib.Z3_get_app_num_args)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_app_arg(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_app_arg)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_is_eq_ast(a0, a1, a2, _elems=Elementaries(_lib.Z3_is_eq_ast)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_ast_id(a0, a1, _elems=Elementaries(_lib.Z3_get_ast_id)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_ast_hash(a0, a1, _elems=Elementaries(_lib.Z3_get_ast_hash)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_sort(a0, a1, _elems=Elementaries(_lib.Z3_get_sort)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_well_sorted(a0, a1, _elems=Elementaries(_lib.Z3_is_well_sorted)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_bool_value(a0, a1, _elems=Elementaries(_lib.Z3_get_bool_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_ast_kind(a0, a1, _elems=Elementaries(_lib.Z3_get_ast_kind)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_app(a0, a1, _elems=Elementaries(_lib.Z3_is_app)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_numeral_ast(a0, a1, _elems=Elementaries(_lib.Z3_is_numeral_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_algebraic_number(a0, a1, _elems=Elementaries(_lib.Z3_is_algebraic_number)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_to_app(a0, a1, _elems=Elementaries(_lib.Z3_to_app)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_to_func_decl(a0, a1, _elems=Elementaries(_lib.Z3_to_func_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numeral_string(a0, a1, _elems=Elementaries(_lib.Z3_get_numeral_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_numeral_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_get_numeral_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numeral_decimal_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_decimal_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_get_numeral_decimal_string_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_decimal_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_double(a0, a1, _elems=Elementaries(_lib.Z3_get_numeral_double)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numerator(a0, a1, _elems=Elementaries(_lib.Z3_get_numerator)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_denominator(a0, a1, _elems=Elementaries(_lib.Z3_get_denominator)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_numeral_small(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_numeral_small)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_numeral_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_uint(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_uint)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_uint64(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_uint64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_int64(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_numeral_int64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_numeral_rational_int64(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_numeral_rational_int64)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_algebraic_number_lower(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_algebraic_number_lower)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_algebraic_number_upper(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_algebraic_number_upper)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_pattern_to_ast(a0, a1, _elems=Elementaries(_lib.Z3_pattern_to_ast)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_pattern_num_terms(a0, a1, _elems=Elementaries(_lib.Z3_get_pattern_num_terms)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_pattern(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_pattern)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_index_value(a0, a1, _elems=Elementaries(_lib.Z3_get_index_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_quantifier_forall(a0, a1, _elems=Elementaries(_lib.Z3_is_quantifier_forall)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_quantifier_exists(a0, a1, _elems=Elementaries(_lib.Z3_is_quantifier_exists)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_is_lambda(a0, a1, _elems=Elementaries(_lib.Z3_is_lambda)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_weight(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_weight)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_num_patterns(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_num_patterns)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_pattern_ast(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_pattern_ast)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_num_no_patterns(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_num_no_patterns)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_no_pattern_ast(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_no_pattern_ast)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_num_bound(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_num_bound)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_quantifier_bound_name(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_bound_name)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_bound_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_get_quantifier_bound_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_quantifier_body(a0, a1, _elems=Elementaries(_lib.Z3_get_quantifier_body)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_simplify(a0, a1, _elems=Elementaries(_lib.Z3_simplify)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_simplify_ex(a0, a1, a2, _elems=Elementaries(_lib.Z3_simplify_ex)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_simplify_get_help(a0, _elems=Elementaries(_lib.Z3_simplify_get_help)): r = _elems.f(a0) _elems.Check(a0) return _to_pystr(r) def Z3_simplify_get_help_bytes(a0, _elems=Elementaries(_lib.Z3_simplify_get_help)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_simplify_get_param_descrs(a0, _elems=Elementaries(_lib.Z3_simplify_get_param_descrs)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_update_term(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_update_term)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_substitute(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_substitute)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_substitute_vars(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_substitute_vars)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_model(a0, _elems=Elementaries(_lib.Z3_mk_model)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_model_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_model_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_model_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_model_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_model_eval(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_model_eval)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_model_get_const_interp(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_const_interp)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_has_interp(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_has_interp)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_func_interp(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_func_interp)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_num_consts(a0, a1, _elems=Elementaries(_lib.Z3_model_get_num_consts)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_get_const_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_const_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_num_funcs(a0, a1, _elems=Elementaries(_lib.Z3_model_get_num_funcs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_get_func_decl(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_func_decl)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_num_sorts(a0, a1, _elems=Elementaries(_lib.Z3_model_get_num_sorts)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_get_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_get_sort_universe(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_get_sort_universe)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_model_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_is_as_array(a0, a1, _elems=Elementaries(_lib.Z3_is_as_array)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_as_array_func_decl(a0, a1, _elems=Elementaries(_lib.Z3_get_as_array_func_decl)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_add_func_interp(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_add_func_interp)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_add_const_interp(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_add_const_interp)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_func_interp_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_interp_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_interp_get_num_entries(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_get_num_entries)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_interp_get_entry(a0, a1, a2, _elems=Elementaries(_lib.Z3_func_interp_get_entry)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_func_interp_get_else(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_get_else)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_interp_set_else(a0, a1, a2, _elems=Elementaries(_lib.Z3_func_interp_set_else)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_func_interp_get_arity(a0, a1, _elems=Elementaries(_lib.Z3_func_interp_get_arity)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_interp_add_entry(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_func_interp_add_entry)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_func_entry_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_entry_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_func_entry_get_value(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_get_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_entry_get_num_args(a0, a1, _elems=Elementaries(_lib.Z3_func_entry_get_num_args)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_entry_get_arg(a0, a1, a2, _elems=Elementaries(_lib.Z3_func_entry_get_arg)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_open_log(a0, _elems=Elementaries(_lib.Z3_open_log)): r = _elems.f(_str_to_bytes(a0)) return r def Z3_append_log(a0, _elems=Elementaries(_lib.Z3_append_log)): _elems.f(_str_to_bytes(a0)) def Z3_close_log(_elems=Elementaries(_lib.Z3_close_log)): _elems.f() def Z3_toggle_warning_messages(a0, _elems=Elementaries(_lib.Z3_toggle_warning_messages)): _elems.f(a0) def Z3_set_ast_print_mode(a0, a1, _elems=Elementaries(_lib.Z3_set_ast_print_mode)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_to_string(a0, a1, _elems=Elementaries(_lib.Z3_ast_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_ast_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_ast_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_pattern_to_string(a0, a1, _elems=Elementaries(_lib.Z3_pattern_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_pattern_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_pattern_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_sort_to_string(a0, a1, _elems=Elementaries(_lib.Z3_sort_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_sort_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_sort_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_func_decl_to_string(a0, a1, _elems=Elementaries(_lib.Z3_func_decl_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_func_decl_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_func_decl_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_model_to_string(a0, a1, _elems=Elementaries(_lib.Z3_model_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_model_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_model_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_benchmark_to_smtlib_string(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_benchmark_to_smtlib_string)): r = _elems.f(a0, _str_to_bytes(a1), _str_to_bytes(a2), _str_to_bytes(a3), _str_to_bytes(a4), a5, a6, a7) _elems.Check(a0) return _to_pystr(r) def Z3_benchmark_to_smtlib_string_bytes(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_benchmark_to_smtlib_string)): r = _elems.f(a0, _str_to_bytes(a1), _str_to_bytes(a2), _str_to_bytes(a3), _str_to_bytes(a4), a5, a6, a7) _elems.Check(a0) return r def Z3_parse_smtlib2_string(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_parse_smtlib2_string)): r = _elems.f(a0, _str_to_bytes(a1), a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_parse_smtlib2_file(a0, a1, a2, a3, a4, a5, a6, a7, _elems=Elementaries(_lib.Z3_parse_smtlib2_file)): r = _elems.f(a0, _str_to_bytes(a1), a2, a3, a4, a5, a6, a7) _elems.Check(a0) return r def Z3_eval_smtlib2_string(a0, a1, _elems=Elementaries(_lib.Z3_eval_smtlib2_string)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return _to_pystr(r) def Z3_eval_smtlib2_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_eval_smtlib2_string)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_get_error_code(a0, _elems=Elementaries(_lib.Z3_get_error_code)): r = _elems.f(a0) return r def Z3_set_error(a0, a1, _elems=Elementaries(_lib.Z3_set_error)): _elems.f(a0, a1) _elems.Check(a0) def Z3_get_error_msg(a0, a1, _elems=Elementaries(_lib.Z3_get_error_msg)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_error_msg_bytes(a0, a1, _elems=Elementaries(_lib.Z3_get_error_msg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_version(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_get_version)): _elems.f(a0, a1, a2, a3) def Z3_get_full_version(_elems=Elementaries(_lib.Z3_get_full_version)): r = _elems.f() return _to_pystr(r) def Z3_get_full_version_bytes(_elems=Elementaries(_lib.Z3_get_full_version)): r = _elems.f() return r def Z3_enable_trace(a0, _elems=Elementaries(_lib.Z3_enable_trace)): _elems.f(_str_to_bytes(a0)) def Z3_disable_trace(a0, _elems=Elementaries(_lib.Z3_disable_trace)): _elems.f(_str_to_bytes(a0)) def Z3_reset_memory(_elems=Elementaries(_lib.Z3_reset_memory)): _elems.f() def Z3_finalize_memory(_elems=Elementaries(_lib.Z3_finalize_memory)): _elems.f() def Z3_mk_goal(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_goal)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_goal_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_goal_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_goal_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_goal_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_goal_precision(a0, a1, _elems=Elementaries(_lib.Z3_goal_precision)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_goal_inconsistent(a0, a1, _elems=Elementaries(_lib.Z3_goal_inconsistent)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_depth(a0, a1, _elems=Elementaries(_lib.Z3_goal_depth)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_reset(a0, a1, _elems=Elementaries(_lib.Z3_goal_reset)): _elems.f(a0, a1) _elems.Check(a0) def Z3_goal_size(a0, a1, _elems=Elementaries(_lib.Z3_goal_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_formula(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_formula)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_goal_num_exprs(a0, a1, _elems=Elementaries(_lib.Z3_goal_num_exprs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_is_decided_sat(a0, a1, _elems=Elementaries(_lib.Z3_goal_is_decided_sat)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_is_decided_unsat(a0, a1, _elems=Elementaries(_lib.Z3_goal_is_decided_unsat)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_goal_convert_model(a0, a1, a2, _elems=Elementaries(_lib.Z3_goal_convert_model)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_goal_to_string(a0, a1, _elems=Elementaries(_lib.Z3_goal_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_goal_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_goal_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_goal_to_dimacs_string(a0, a1, _elems=Elementaries(_lib.Z3_goal_to_dimacs_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_goal_to_dimacs_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_goal_to_dimacs_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_tactic(a0, a1, _elems=Elementaries(_lib.Z3_mk_tactic)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_tactic_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_tactic_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_tactic_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_tactic_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_mk_probe(a0, a1, _elems=Elementaries(_lib.Z3_mk_probe)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_probe_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_probe_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_probe_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_probe_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_tactic_and_then(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_and_then)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_or_else(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_or_else)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_par_or(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_par_or)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_par_and_then(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_par_and_then)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_try_for(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_try_for)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_when(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_when)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_cond(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_tactic_cond)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_tactic_repeat(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_repeat)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_skip(a0, _elems=Elementaries(_lib.Z3_tactic_skip)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_tactic_fail(a0, _elems=Elementaries(_lib.Z3_tactic_fail)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_tactic_fail_if(a0, a1, _elems=Elementaries(_lib.Z3_tactic_fail_if)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_tactic_fail_if_not_decided(a0, _elems=Elementaries(_lib.Z3_tactic_fail_if_not_decided)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_tactic_using_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_using_params)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_const(a0, a1, _elems=Elementaries(_lib.Z3_probe_const)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_probe_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_and(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_and)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_or(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_or)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_probe_not(a0, a1, _elems=Elementaries(_lib.Z3_probe_not)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_num_tactics(a0, _elems=Elementaries(_lib.Z3_get_num_tactics)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_get_tactic_name(a0, a1, _elems=Elementaries(_lib.Z3_get_tactic_name)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_tactic_name_bytes(a0, a1, _elems=Elementaries(_lib.Z3_get_tactic_name)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_get_num_probes(a0, _elems=Elementaries(_lib.Z3_get_num_probes)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_get_probe_name(a0, a1, _elems=Elementaries(_lib.Z3_get_probe_name)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_get_probe_name_bytes(a0, a1, _elems=Elementaries(_lib.Z3_get_probe_name)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_tactic_get_help(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_tactic_get_help_bytes(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_tactic_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_tactic_get_descr(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_descr)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return _to_pystr(r) def Z3_tactic_get_descr_bytes(a0, a1, _elems=Elementaries(_lib.Z3_tactic_get_descr)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_probe_get_descr(a0, a1, _elems=Elementaries(_lib.Z3_probe_get_descr)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return _to_pystr(r) def Z3_probe_get_descr_bytes(a0, a1, _elems=Elementaries(_lib.Z3_probe_get_descr)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_probe_apply(a0, a1, a2, _elems=Elementaries(_lib.Z3_probe_apply)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_apply(a0, a1, a2, _elems=Elementaries(_lib.Z3_tactic_apply)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_tactic_apply_ex(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_tactic_apply_ex)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_apply_result_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_apply_result_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_apply_result_to_string(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_apply_result_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_apply_result_get_num_subgoals(a0, a1, _elems=Elementaries(_lib.Z3_apply_result_get_num_subgoals)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_apply_result_get_subgoal(a0, a1, a2, _elems=Elementaries(_lib.Z3_apply_result_get_subgoal)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_solver(a0, _elems=Elementaries(_lib.Z3_mk_solver)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_simple_solver(a0, _elems=Elementaries(_lib.Z3_mk_simple_solver)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_solver_for_logic(a0, a1, _elems=Elementaries(_lib.Z3_mk_solver_for_logic)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_solver_from_tactic(a0, a1, _elems=Elementaries(_lib.Z3_mk_solver_from_tactic)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_solver_import_model_converter(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_import_model_converter)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_get_help(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_solver_get_help_bytes(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_set_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_set_params)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_solver_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_solver_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_interrupt(a0, a1, _elems=Elementaries(_lib.Z3_solver_interrupt)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_push(a0, a1, _elems=Elementaries(_lib.Z3_solver_push)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_pop(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_pop)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_reset(a0, a1, _elems=Elementaries(_lib.Z3_solver_reset)): _elems.f(a0, a1) _elems.Check(a0) def Z3_solver_get_num_scopes(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_num_scopes)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_solver_assert_and_track(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_solver_assert_and_track)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_solver_from_file(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_from_file)): _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) def Z3_solver_from_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_from_string)): _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) def Z3_solver_get_assertions(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_assertions)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_units(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_units)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_trail(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_trail)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_non_units(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_non_units)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_levels(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_solver_get_levels)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_solver_check(a0, a1, _elems=Elementaries(_lib.Z3_solver_check)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_check_assumptions(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_solver_check_assumptions)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_get_implied_equalities(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_get_implied_equalities)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_solver_get_consequences(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_solver_get_consequences)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_solver_cube(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_solver_cube)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_solver_get_model(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_model)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_proof(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_proof)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_unsat_core(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_unsat_core)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_reason_unknown(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_solver_get_reason_unknown_bytes(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_get_statistics(a0, a1, _elems=Elementaries(_lib.Z3_solver_get_statistics)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_to_string(a0, a1, _elems=Elementaries(_lib.Z3_solver_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_solver_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_solver_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_solver_to_dimacs_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_to_dimacs_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_solver_to_dimacs_string_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_solver_to_dimacs_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_to_string(a0, a1, _elems=Elementaries(_lib.Z3_stats_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_stats_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_stats_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_stats_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_stats_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_stats_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_stats_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_stats_size(a0, a1, _elems=Elementaries(_lib.Z3_stats_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_stats_get_key(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_key)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_stats_get_key_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_key)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_is_uint(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_is_uint)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_is_double(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_is_double)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_get_uint_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_uint_value)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_stats_get_double_value(a0, a1, a2, _elems=Elementaries(_lib.Z3_stats_get_double_value)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_get_estimated_alloc_size(_elems=Elementaries(_lib.Z3_get_estimated_alloc_size)): r = _elems.f() return r def Z3_mk_ast_vector(a0, _elems=Elementaries(_lib.Z3_mk_ast_vector)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_ast_vector_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_vector_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_vector_size(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_ast_vector_get(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_get)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_vector_set(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_ast_vector_set)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_ast_vector_resize(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_resize)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_ast_vector_push(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_push)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_ast_vector_translate(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_vector_translate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_vector_to_string(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_ast_vector_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_ast_vector_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_ast_map(a0, _elems=Elementaries(_lib.Z3_mk_ast_map)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_ast_map_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_map_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_map_contains(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_map_contains)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_map_find(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_map_find)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_ast_map_insert(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_ast_map_insert)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_ast_map_erase(a0, a1, a2, _elems=Elementaries(_lib.Z3_ast_map_erase)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_ast_map_reset(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_reset)): _elems.f(a0, a1) _elems.Check(a0) def Z3_ast_map_size(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_size)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_ast_map_keys(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_keys)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_ast_map_to_string(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_ast_map_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_ast_map_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_value(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_value)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_pos(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_pos)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_neg(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_neg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_is_zero(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_is_zero)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_sign(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_sign)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_algebraic_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_sub(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_sub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_mul(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_mul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_div(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_div)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_root(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_root)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_power(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_power)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_neq(a0, a1, a2, _elems=Elementaries(_lib.Z3_algebraic_neq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_algebraic_roots(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_algebraic_roots)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_algebraic_eval(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_algebraic_eval)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_polynomial_subresultants(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_polynomial_subresultants)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_rcf_del(a0, a1, _elems=Elementaries(_lib.Z3_rcf_del)): _elems.f(a0, a1) _elems.Check(a0) def Z3_rcf_mk_rational(a0, a1, _elems=Elementaries(_lib.Z3_rcf_mk_rational)): r = _elems.f(a0, _str_to_bytes(a1)) _elems.Check(a0) return r def Z3_rcf_mk_small_int(a0, a1, _elems=Elementaries(_lib.Z3_rcf_mk_small_int)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_rcf_mk_pi(a0, _elems=Elementaries(_lib.Z3_rcf_mk_pi)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_rcf_mk_e(a0, _elems=Elementaries(_lib.Z3_rcf_mk_e)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_rcf_mk_infinitesimal(a0, _elems=Elementaries(_lib.Z3_rcf_mk_infinitesimal)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_rcf_mk_roots(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_mk_roots)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_rcf_add(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_add)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_sub(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_sub)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_mul(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_mul)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_div(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_div)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_neg(a0, a1, _elems=Elementaries(_lib.Z3_rcf_neg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_rcf_inv(a0, a1, _elems=Elementaries(_lib.Z3_rcf_inv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_rcf_power(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_power)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_le(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_le)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_ge(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_ge)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_neq(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_neq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_num_to_string(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_num_to_string)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return _to_pystr(r) def Z3_rcf_num_to_string_bytes(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_num_to_string)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_rcf_num_to_decimal_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_num_to_decimal_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_rcf_num_to_decimal_string_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_rcf_num_to_decimal_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_rcf_get_numerator_denominator(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_rcf_get_numerator_denominator)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_mk_fixedpoint(a0, _elems=Elementaries(_lib.Z3_mk_fixedpoint)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_fixedpoint_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_fixedpoint_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_fixedpoint_add_rule(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_add_rule)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_fixedpoint_add_fact(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_fixedpoint_add_fact)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_fixedpoint_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_fixedpoint_query(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_query)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fixedpoint_query_relations(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_query_relations)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_get_answer(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_answer)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_reason_unknown(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_fixedpoint_get_reason_unknown_bytes(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_update_rule(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_update_rule)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_fixedpoint_get_num_levels(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_get_num_levels)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fixedpoint_get_cover_delta(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_get_cover_delta)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_add_cover(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_fixedpoint_add_cover)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_fixedpoint_get_statistics(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_statistics)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_register_relation(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_register_relation)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_fixedpoint_set_predicate_representation(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_fixedpoint_set_predicate_representation)): _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) def Z3_fixedpoint_get_rules(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_rules)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_assertions(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_assertions)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_set_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_set_params)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_fixedpoint_get_help(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_fixedpoint_get_help_bytes(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_to_string(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_to_string)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return _to_pystr(r) def Z3_fixedpoint_to_string_bytes(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_to_string)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_from_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_from_string)): r = _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) return r def Z3_fixedpoint_from_file(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_from_file)): r = _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) return r def Z3_mk_optimize(a0, _elems=Elementaries(_lib.Z3_mk_optimize)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_optimize_inc_ref(a0, a1, _elems=Elementaries(_lib.Z3_optimize_inc_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_dec_ref(a0, a1, _elems=Elementaries(_lib.Z3_optimize_dec_ref)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_assert(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_assert)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_optimize_assert_and_track(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_optimize_assert_and_track)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_optimize_assert_soft(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_optimize_assert_soft)): r = _elems.f(a0, a1, a2, _str_to_bytes(a3), a4) _elems.Check(a0) return r def Z3_optimize_maximize(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_maximize)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_minimize(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_minimize)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_push(a0, a1, _elems=Elementaries(_lib.Z3_optimize_push)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_pop(a0, a1, _elems=Elementaries(_lib.Z3_optimize_pop)): _elems.f(a0, a1) _elems.Check(a0) def Z3_optimize_check(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_optimize_check)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_optimize_get_reason_unknown(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_optimize_get_reason_unknown_bytes(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_reason_unknown)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_model(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_model)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_unsat_core(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_unsat_core)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_set_params(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_set_params)): _elems.f(a0, a1, a2) _elems.Check(a0) def Z3_optimize_get_param_descrs(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_param_descrs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_lower(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_lower)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_get_upper(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_upper)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_get_lower_as_vector(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_lower_as_vector)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_get_upper_as_vector(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_get_upper_as_vector)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_optimize_to_string(a0, a1, _elems=Elementaries(_lib.Z3_optimize_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_optimize_to_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_optimize_to_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_from_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_from_string)): _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) def Z3_optimize_from_file(a0, a1, a2, _elems=Elementaries(_lib.Z3_optimize_from_file)): _elems.f(a0, a1, _str_to_bytes(a2)) _elems.Check(a0) def Z3_optimize_get_help(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_optimize_get_help_bytes(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_help)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_statistics(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_statistics)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_assertions(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_assertions)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_optimize_get_objectives(a0, a1, _elems=Elementaries(_lib.Z3_optimize_get_objectives)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_rounding_mode_sort(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rounding_mode_sort)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_nearest_ties_to_even(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_nearest_ties_to_even)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rne(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rne)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_nearest_ties_to_away(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_nearest_ties_to_away)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rna(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rna)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_toward_positive(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_toward_positive)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rtp(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rtp)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_toward_negative(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_toward_negative)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rtn(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rtn)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_round_toward_zero(a0, _elems=Elementaries(_lib.Z3_mk_fpa_round_toward_zero)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_rtz(a0, _elems=Elementaries(_lib.Z3_mk_fpa_rtz)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_sort)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_sort_half(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_half)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_16(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_16)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_single(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_single)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_32(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_32)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_double(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_double)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_64(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_64)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_quadruple(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_quadruple)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_sort_128(a0, _elems=Elementaries(_lib.Z3_mk_fpa_sort_128)): r = _elems.f(a0) _elems.Check(a0) return r def Z3_mk_fpa_nan(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_nan)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_inf(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_inf)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_zero(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_zero)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_fp(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_fp)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_numeral_float(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_float)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_numeral_double(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_double)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_numeral_int(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_int)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_numeral_int_uint(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_int_uint)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fpa_numeral_int64_uint64(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_numeral_int64_uint64)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fpa_abs(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_abs)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_neg(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_neg)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_add(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_add)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_sub(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_sub)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_mul(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_mul)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_div(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_div)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_fma(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_fma)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_mk_fpa_sqrt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_sqrt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_rem(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_rem)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_round_to_integral(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_round_to_integral)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_min(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_min)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_max(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_max)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_leq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_leq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_lt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_lt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_geq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_geq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_gt(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_gt)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_eq(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_eq)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_is_normal(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_normal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_subnormal(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_subnormal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_zero(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_zero)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_infinite(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_infinite)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_nan(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_nan)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_negative(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_negative)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_is_positive(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_is_positive)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_bv(a0, a1, a2, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_bv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_float(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_float)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_real(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_real)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_signed(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_signed)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_unsigned(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_unsigned)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_ubv(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_ubv)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_sbv(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_mk_fpa_to_sbv)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_mk_fpa_to_real(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_to_real)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_ebits(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_ebits)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_sbits(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_sbits)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_nan(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_nan)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_inf(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_inf)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_zero(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_zero)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_normal(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_normal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_subnormal(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_subnormal)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_positive(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_positive)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_is_numeral_negative(a0, a1, _elems=Elementaries(_lib.Z3_fpa_is_numeral_negative)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_sign_bv(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_sign_bv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_significand_bv(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_bv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_sign(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_sign)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fpa_get_numeral_significand_string(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_string)): r = _elems.f(a0, a1) _elems.Check(a0) return _to_pystr(r) def Z3_fpa_get_numeral_significand_string_bytes(a0, a1, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_string)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fpa_get_numeral_significand_uint64(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_significand_uint64)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fpa_get_numeral_exponent_string(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return _to_pystr(r) def Z3_fpa_get_numeral_exponent_string_bytes(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_string)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_fpa_get_numeral_exponent_int64(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_int64)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fpa_get_numeral_exponent_bv(a0, a1, a2, _elems=Elementaries(_lib.Z3_fpa_get_numeral_exponent_bv)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_mk_fpa_to_ieee_bv(a0, a1, _elems=Elementaries(_lib.Z3_mk_fpa_to_ieee_bv)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_mk_fpa_to_fp_int_real(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_mk_fpa_to_fp_int_real)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_fixedpoint_query_from_lvl(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_query_from_lvl)): r = _elems.f(a0, a1, a2, a3) _elems.Check(a0) return r def Z3_fixedpoint_get_ground_sat_answer(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_ground_sat_answer)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_rules_along_trace(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_rules_along_trace)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_get_rule_names_along_trace(a0, a1, _elems=Elementaries(_lib.Z3_fixedpoint_get_rule_names_along_trace)): r = _elems.f(a0, a1) _elems.Check(a0) return r def Z3_fixedpoint_add_invariant(a0, a1, a2, a3, _elems=Elementaries(_lib.Z3_fixedpoint_add_invariant)): _elems.f(a0, a1, a2, a3) _elems.Check(a0) def Z3_fixedpoint_get_reachable(a0, a1, a2, _elems=Elementaries(_lib.Z3_fixedpoint_get_reachable)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_qe_model_project(a0, a1, a2, a3, a4, _elems=Elementaries(_lib.Z3_qe_model_project)): r = _elems.f(a0, a1, a2, a3, a4) _elems.Check(a0) return r def Z3_qe_model_project_skolem(a0, a1, a2, a3, a4, a5, _elems=Elementaries(_lib.Z3_qe_model_project_skolem)): r = _elems.f(a0, a1, a2, a3, a4, a5) _elems.Check(a0) return r def Z3_model_extrapolate(a0, a1, a2, _elems=Elementaries(_lib.Z3_model_extrapolate)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r def Z3_qe_lite(a0, a1, a2, _elems=Elementaries(_lib.Z3_qe_lite)): r = _elems.f(a0, a1, a2) _elems.Check(a0) return r # Clean up del _lib del _default_dirs del _all_dirs del _ext
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3core.py
z3core.py
from . import z3core from .z3core import * from .z3types import * from .z3consts import * from .z3printer import * from fractions import Fraction import sys import io import math import copy Z3_DEBUG = __debug__ def z3_debug(): global Z3_DEBUG return Z3_DEBUG if sys.version < '3': def _is_int(v): return isinstance(v, (int, long)) else: def _is_int(v): return isinstance(v, int) def enable_trace(msg): Z3_enable_trace(msg) def disable_trace(msg): Z3_disable_trace(msg) def get_version_string(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return "%s.%s.%s" % (major.value, minor.value, build.value) def get_version(): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major, minor, build, rev) return (major.value, minor.value, build.value, rev.value) def get_full_version(): return Z3_get_full_version() # We use _z3_assert instead of the assert command because we want to # produce nice error messages in Z3Py at rise4fun.com def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) def _z3_check_cint_overflow(n, name): _z3_assert(ctypes.c_int(n).value == n, name + " is too large") def open_log(fname): """Log interaction to a file. This function must be invoked immediately after init(). """ Z3_open_log(fname) def append_log(s): """Append user-defined string to interaction log. """ Z3_append_log(s) def to_symbol(s, ctx=None): """Convert an integer or string into a Z3 symbol.""" if _is_int(s): return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s) else: return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s) def _symbol2py(ctx, s): """Convert a Z3 symbol back into a Python object. """ if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL: return "k!%s" % Z3_get_symbol_int(ctx.ref(), s) else: return Z3_get_symbol_string(ctx.ref(), s) # Hack for having nary functions that can receive one argument that is the # list of arguments. # Use this when function takes a single list of arguments def _get_args(args): try: if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)): return args[0] elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)): return [arg for arg in args[0]] else: return args except: # len is not necessarily defined when args is not a sequence (use reflection?) return args # Use this when function takes multiple arguments def _get_args_ast_list(args): try: if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple): return [arg for arg in args] else: return args except: return args def _to_param_value(val): if isinstance(val, bool): if val == True: return "true" else: return "false" else: return str(val) def z3_error_handler(c, e): # Do nothing error handler, just avoid exit(0) # The wrappers in z3core.py will raise a Z3Exception if an error is detected return class Context: """A Context manages all other Z3 objects, global configuration options, etc. Z3Py uses a default global context. For most applications this is sufficient. An application may use multiple Z3 contexts. Objects created in one context cannot be used in another one. However, several objects may be "translated" from one context to another. It is not safe to access Z3 objects from multiple threads. The only exception is the method `interrupt()` that can be used to interrupt() a long computation. The initialization method receives global configuration options for the new context. """ def __init__(self, *args, **kws): if z3_debug(): _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") conf = Z3_mk_config() for key in kws: value = kws[key] Z3_set_param_value(conf, str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_set_param_value(conf, str(prev), _to_param_value(a)) prev = None self.ctx = Z3_mk_context_rc(conf) self.eh = Z3_set_error_handler(self.ctx, z3_error_handler) Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT) Z3_del_config(conf) def __del__(self): Z3_del_context(self.ctx) self.ctx = None self.eh = None def ref(self): """Return a reference to the actual C pointer to the Z3 context.""" return self.ctx def interrupt(self): """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions. This method can be invoked from a thread different from the one executing the interruptible procedure. """ Z3_interrupt(self.ref()) # Global Z3 context _main_ctx = None def main_ctx(): """Return a reference to the global Z3 context. >>> x = Real('x') >>> x.ctx == main_ctx() True >>> c = Context() >>> c == main_ctx() False >>> x2 = Real('x', c) >>> x2.ctx == c True >>> eq(x, x2) False """ global _main_ctx if _main_ctx is None: _main_ctx = Context() return _main_ctx def _get_ctx(ctx): if ctx is None: return main_ctx() else: return ctx def get_ctx(ctx): return _get_ctx(ctx) def set_param(*args, **kws): """Set Z3 global (or module) parameters. >>> set_param(precision=10) """ if z3_debug(): _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.") new_kws = {} for k in kws: v = kws[k] if not set_pp_option(k, v): new_kws[k] = v for key in new_kws: value = new_kws[key] Z3_global_param_set(str(key).upper(), _to_param_value(value)) prev = None for a in args: if prev is None: prev = a else: Z3_global_param_set(str(prev), _to_param_value(a)) prev = None def reset_params(): """Reset all global (or module) parameters. """ Z3_global_param_reset_all() def set_option(*args, **kws): """Alias for 'set_param' for backward compatibility. """ return set_param(*args, **kws) def get_param(name): """Return the value of a Z3 global (or module) parameter >>> get_param('nlsat.reorder') 'true' """ ptr = (ctypes.c_char_p * 1)() if Z3_global_param_get(str(name), ptr): r = z3core._to_pystr(ptr[0]) return r raise Z3Exception("failed to retrieve value for '%s'" % name) ######################################### # # ASTs base class # ######################################### # Mark objects that use pretty printer class Z3PPObject: """Superclass for all Z3 objects that have support for pretty printing.""" def use_pp(self): return True def _repr_html_(self): in_html = in_html_mode() set_html_mode(True) res = repr(self) set_html_mode(in_html) return res class AstRef(Z3PPObject): """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions.""" def __init__(self, ast, ctx=None): self.ast = ast self.ctx = _get_ctx(ctx) Z3_inc_ref(self.ctx.ref(), self.as_ast()) def __del__(self): if self.ctx.ref() is not None and self.ast is not None: Z3_dec_ref(self.ctx.ref(), self.as_ast()) self.ast = None def __deepcopy__(self, memo={}): return _to_ast_ref(self.ast, self.ctx) def __str__(self): return obj_to_string(self) def __repr__(self): return obj_to_string(self) def __eq__(self, other): return self.eq(other) def __hash__(self): return self.hash() def __nonzero__(self): return self.__bool__() def __bool__(self): if is_true(self): return True elif is_false(self): return False elif is_eq(self) and self.num_args() == 2: return self.arg(0).eq(self.arg(1)) else: raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.") def sexpr(self): """Return a string representing the AST node in s-expression notation. >>> x = Int('x') >>> ((x + 1)*x).sexpr() '(* (+ x 1) x)' """ return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): """Return a pointer to the corresponding C Z3_ast object.""" return self.ast def get_id(self): """Return unique identifier for object. It can be used for hash-tables and maps.""" return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def ctx_ref(self): """Return a reference to the C context where this AST node is stored.""" return self.ctx.ref() def eq(self, other): """Return `True` if `self` and `other` are structurally identical. >>> x = Int('x') >>> n1 = x + 1 >>> n2 = 1 + x >>> n1.eq(n2) False >>> n1 = simplify(n1) >>> n2 = simplify(n2) >>> n1.eq(n2) True """ if z3_debug(): _z3_assert(is_ast(other), "Z3 AST expected") return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast()) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> x = Int('x', c1) >>> y = Int('y', c2) >>> # Nodes in different contexts can't be mixed. >>> # However, we can translate nodes from one context to another. >>> x.translate(c2) + y x + y """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target) def __copy__(self): return self.translate(self.ctx) def hash(self): """Return a hashcode for the `self`. >>> n1 = simplify(Int('x') + 1) >>> n2 = simplify(2 + Int('x') - 1) >>> n1.hash() == n2.hash() True """ return Z3_get_ast_hash(self.ctx_ref(), self.as_ast()) def is_ast(a): """Return `True` if `a` is an AST node. >>> is_ast(10) False >>> is_ast(IntVal(10)) True >>> is_ast(Int('x')) True >>> is_ast(BoolSort()) True >>> is_ast(Function('f', IntSort(), IntSort())) True >>> is_ast("x") False >>> is_ast(Solver()) False """ return isinstance(a, AstRef) def eq(a, b): """Return `True` if `a` and `b` are structurally identical AST nodes. >>> x = Int('x') >>> y = Int('y') >>> eq(x, y) False >>> eq(x + 1, x + 1) True >>> eq(x + 1, 1 + x) False >>> eq(simplify(x + 1), simplify(1 + x)) True """ if z3_debug(): _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected") return a.eq(b) def _ast_kind(ctx, a): if is_ast(a): a = a.as_ast() return Z3_get_ast_kind(ctx.ref(), a) def _ctx_from_ast_arg_list(args, default_ctx=None): ctx = None for a in args: if is_ast(a) or is_probe(a): if ctx is None: ctx = a.ctx else: if z3_debug(): _z3_assert(ctx == a.ctx, "Context mismatch") if ctx is None: ctx = default_ctx return ctx def _ctx_from_ast_args(*args): return _ctx_from_ast_arg_list(args) def _to_func_decl_array(args): sz = len(args) _args = (FuncDecl * sz)() for i in range(sz): _args[i] = args[i].as_func_decl() return _args, sz def _to_ast_array(args): sz = len(args) _args = (Ast * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ref_array(ref, args): sz = len(args) _args = (ref * sz)() for i in range(sz): _args[i] = args[i].as_ast() return _args, sz def _to_ast_ref(a, ctx): k = _ast_kind(ctx, a) if k == Z3_SORT_AST: return _to_sort_ref(a, ctx) elif k == Z3_FUNC_DECL_AST: return _to_func_decl_ref(a, ctx) else: return _to_expr_ref(a, ctx) ######################################### # # Sorts # ######################################### def _sort_kind(ctx, s): return Z3_get_sort_kind(ctx.ref(), s) class SortRef(AstRef): """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node.""" def as_ast(self): return Z3_sort_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def kind(self): """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts. >>> b = BoolSort() >>> b.kind() == Z3_BOOL_SORT True >>> b.kind() == Z3_INT_SORT False >>> A = ArraySort(IntSort(), IntSort()) >>> A.kind() == Z3_ARRAY_SORT True >>> A.kind() == Z3_INT_SORT False """ return _sort_kind(self.ctx, self.ast) def subsort(self, other): """Return `True` if `self` is a subsort of `other`. >>> IntSort().subsort(RealSort()) True """ return False def cast(self, val): """Try to cast `val` as an element of sort `self`. This method is used in Z3Py to convert Python objects such as integers, floats, longs and strings into Z3 expressions. >>> x = Int('x') >>> RealSort().cast(x) ToReal(x) """ if z3_debug(): _z3_assert(is_expr(val), "Z3 expression expected") _z3_assert(self.eq(val.sort()), "Sort mismatch") return val def name(self): """Return the name (string) of sort `self`. >>> BoolSort().name() 'Bool' >>> ArraySort(IntSort(), IntSort()).name() 'Array' """ return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast)) def __eq__(self, other): """Return `True` if `self` and `other` are the same Z3 sort. >>> p = Bool('p') >>> p.sort() == BoolSort() True >>> p.sort() == IntSort() False """ if other is None: return False return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __ne__(self, other): """Return `True` if `self` and `other` are not the same Z3 sort. >>> p = Bool('p') >>> p.sort() != BoolSort() False >>> p.sort() != IntSort() True """ return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def is_sort(s): """Return `True` if `s` is a Z3 sort. >>> is_sort(IntSort()) True >>> is_sort(Int('x')) False >>> is_expr(Int('x')) True """ return isinstance(s, SortRef) def _to_sort_ref(s, ctx): if z3_debug(): _z3_assert(isinstance(s, Sort), "Z3 Sort expected") k = _sort_kind(ctx, s) if k == Z3_BOOL_SORT: return BoolSortRef(s, ctx) elif k == Z3_INT_SORT or k == Z3_REAL_SORT: return ArithSortRef(s, ctx) elif k == Z3_BV_SORT: return BitVecSortRef(s, ctx) elif k == Z3_ARRAY_SORT: return ArraySortRef(s, ctx) elif k == Z3_DATATYPE_SORT: return DatatypeSortRef(s, ctx) elif k == Z3_FINITE_DOMAIN_SORT: return FiniteDomainSortRef(s, ctx) elif k == Z3_FLOATING_POINT_SORT: return FPSortRef(s, ctx) elif k == Z3_ROUNDING_MODE_SORT: return FPRMSortRef(s, ctx) elif k == Z3_RE_SORT: return ReSortRef(s, ctx) elif k == Z3_SEQ_SORT: return SeqSortRef(s, ctx) return SortRef(s, ctx) def _sort(ctx, a): return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx) def DeclareSort(name, ctx=None): """Create a new uninterpreted sort named `name`. If `ctx=None`, then the new sort is declared in the global Z3Py context. >>> A = DeclareSort('A') >>> a = Const('a', A) >>> b = Const('b', A) >>> a.sort() == A True >>> b.sort() == A True >>> a == b a == b """ ctx = _get_ctx(ctx) return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx) ######################################### # # Function Declarations # ######################################### class FuncDeclRef(AstRef): """Function declaration. Every constant and function have an associated declaration. The declaration assigns a name, a sort (i.e., type), and for function the sort (i.e., type) of each of its arguments. Note that, in Z3, a constant is a function with 0 arguments. """ def as_ast(self): return Z3_func_decl_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def as_func_decl(self): return self.ast def name(self): """Return the name of the function declaration `self`. >>> f = Function('f', IntSort(), IntSort()) >>> f.name() 'f' >>> isinstance(f.name(), str) True """ return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast)) def arity(self): """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.arity() 2 """ return int(Z3_get_arity(self.ctx_ref(), self.ast)) def domain(self, i): """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.domain(0) Int >>> f.domain(1) Real """ if z3_debug(): _z3_assert(i < self.arity(), "Index out of bounds") return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx) def range(self): """Return the sort of the range of a function declaration. For constants, this is the sort of the constant. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> f.range() Bool """ return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx) def kind(self): """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc. >>> x = Int('x') >>> d = (x + 1).decl() >>> d.kind() == Z3_OP_ADD True >>> d.kind() == Z3_OP_MUL False """ return Z3_get_decl_kind(self.ctx_ref(), self.ast) def params(self): ctx = self.ctx n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast) result = [ None for i in range(n) ] for i in range(n): k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i) if k == Z3_PARAMETER_INT: result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_DOUBLE: result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_RATIONAL: result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SYMBOL: result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i) elif k == Z3_PARAMETER_SORT: result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_AST: result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx) elif k == Z3_PARAMETER_FUNC_DECL: result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx) else: assert(False) return result def __call__(self, *args): """Create a Z3 application expression using the function `self`, and the given arguments. The arguments must be Z3 expressions. This method assumes that the sorts of the elements in `args` match the sorts of the domain. Limited coercion is supported. For example, if args[0] is a Python integer, and the function expects a Z3 integer, then the argument is automatically converted into a Z3 integer. >>> f = Function('f', IntSort(), RealSort(), BoolSort()) >>> x = Int('x') >>> y = Real('y') >>> f(x, y) f(x, y) >>> f(x, x) f(x, ToReal(x)) """ args = _get_args(args) num = len(args) if z3_debug(): _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self) _args = (Ast * num)() saved = [] for i in range(num): # self.domain(i).cast(args[i]) may create a new Z3 expression, # then we must save in 'saved' to prevent it from being garbage collected. tmp = self.domain(i).cast(args[i]) saved.append(tmp) _args[i] = tmp.as_ast() return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx) def is_func_decl(a): """Return `True` if `a` is a Z3 function declaration. >>> f = Function('f', IntSort(), IntSort()) >>> is_func_decl(f) True >>> x = Real('x') >>> is_func_decl(x) False """ return isinstance(a, FuncDeclRef) def Function(name, *sig): """Create a new Z3 uninterpreted function with the given sorts. >>> f = Function('f', IntSort(), IntSort()) >>> f(f(0)) f(f(0)) """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def FreshFunction(*sig): """Create a new fresh Z3 uninterpreted function with the given sorts. """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (z3.Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_fresh_func_decl(ctx.ref(), 'f', arity, dom, rng.ast), ctx) def _to_func_decl_ref(a, ctx): return FuncDeclRef(a, ctx) def RecFunction(name, *sig): """Create a new Z3 recursive with the given sorts.""" sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 0, "At least two arguments expected") arity = len(sig) - 1 rng = sig[arity] if z3_debug(): _z3_assert(is_sort(rng), "Z3 sort expected") dom = (Sort * arity)() for i in range(arity): if z3_debug(): _z3_assert(is_sort(sig[i]), "Z3 sort expected") dom[i] = sig[i].ast ctx = rng.ctx return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) def RecAddDefinition(f, args, body): """Set the body of a recursive function. Recursive definitions are only unfolded during search. >>> ctx = Context() >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx)) >>> n = Int('n', ctx) >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1))) >>> simplify(fac(5)) fac(5) >>> s = Solver(ctx=ctx) >>> s.add(fac(n) < 3) >>> s.check() sat >>> s.model().eval(fac(5)) 120 """ if is_app(args): args = [args] ctx = body.ctx args = _get_args(args) n = len(args) _args = (Ast * n)() for i in range(n): _args[i] = args[i].ast Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast) ######################################### # # Expressions # ######################################### class ExprRef(AstRef): """Constraints, formulas and terms are expressions in Z3. Expressions are ASTs. Every expression has a sort. There are three main kinds of expressions: function applications, quantifiers and bounded variables. A constant is a function application with 0 arguments. For quantifier free problems, all expressions are function applications. """ def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the sort of expression `self`. >>> x = Int('x') >>> (x + 1).sort() Int >>> y = Real('y') >>> (x + y).sort() Real """ return _sort(self.ctx, self.as_ast()) def sort_kind(self): """Shorthand for `self.sort().kind()`. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort_kind() == Z3_ARRAY_SORT True >>> a.sort_kind() == Z3_INT_SORT False """ return self.sort().kind() def __eq__(self, other): """Return a Z3 expression that represents the constraint `self == other`. If `other` is `None`, then this method simply returns `False`. >>> a = Int('a') >>> b = Int('b') >>> a == b a == b >>> a is None False """ if other is None: return False a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __hash__(self): """ Hash code. """ return AstRef.__hash__(self) def __ne__(self, other): """Return a Z3 expression that represents the constraint `self != other`. If `other` is `None`, then this method simply returns `True`. >>> a = Int('a') >>> b = Int('b') >>> a != b a != b >>> a is not None True """ if other is None: return True a, b = _coerce_exprs(self, other) _args, sz = _to_ast_array((a, b)) return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx) def params(self): return self.decl().params() def decl(self): """Return the Z3 function declaration associated with a Z3 application. >>> f = Function('f', IntSort(), IntSort()) >>> a = Int('a') >>> t = f(a) >>> eq(t.decl(), f) True >>> (a + 1).decl() + """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx) def num_args(self): """Return the number of arguments of a Z3 application. >>> a = Int('a') >>> b = Int('b') >>> (a + b).num_args() 2 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.num_args() 3 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast())) def arg(self, idx): """Return argument `idx` of the application `self`. This method assumes that `self` is a function application with at least `idx+1` arguments. >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.arg(0) a >>> t.arg(1) b >>> t.arg(2) 0 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") _z3_assert(idx < self.num_args(), "Invalid argument index") return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx) def children(self): """Return a list containing the children of the given expression >>> a = Int('a') >>> b = Int('b') >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.children() [a, b, 0] """ if is_app(self): return [self.arg(i) for i in range(self.num_args())] else: return [] def _to_expr_ref(a, ctx): if isinstance(a, Pattern): return PatternRef(a, ctx) ctx_ref = ctx.ref() k = Z3_get_ast_kind(ctx_ref, a) if k == Z3_QUANTIFIER_AST: return QuantifierRef(a, ctx) sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a)) if sk == Z3_BOOL_SORT: return BoolRef(a, ctx) if sk == Z3_INT_SORT: if k == Z3_NUMERAL_AST: return IntNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_REAL_SORT: if k == Z3_NUMERAL_AST: return RatNumRef(a, ctx) if _is_algebraic(ctx, a): return AlgebraicNumRef(a, ctx) return ArithRef(a, ctx) if sk == Z3_BV_SORT: if k == Z3_NUMERAL_AST: return BitVecNumRef(a, ctx) else: return BitVecRef(a, ctx) if sk == Z3_ARRAY_SORT: return ArrayRef(a, ctx) if sk == Z3_DATATYPE_SORT: return DatatypeRef(a, ctx) if sk == Z3_FLOATING_POINT_SORT: if k == Z3_APP_AST and _is_numeral(ctx, a): return FPNumRef(a, ctx) else: return FPRef(a, ctx) if sk == Z3_FINITE_DOMAIN_SORT: if k == Z3_NUMERAL_AST: return FiniteDomainNumRef(a, ctx) else: return FiniteDomainRef(a, ctx) if sk == Z3_ROUNDING_MODE_SORT: return FPRMRef(a, ctx) if sk == Z3_SEQ_SORT: return SeqRef(a, ctx) if sk == Z3_RE_SORT: return ReRef(a, ctx) return ExprRef(a, ctx) def _coerce_expr_merge(s, a): if is_expr(a): s1 = a.sort() if s is None: return s1 if s1.eq(s): return s elif s.subsort(s1): return s1 elif s1.subsort(s): return s else: if z3_debug(): _z3_assert(s1.ctx == s.ctx, "context mismatch") _z3_assert(False, "sort mismatch") else: return s def _coerce_exprs(a, b, ctx=None): if not is_expr(a) and not is_expr(b): a = _py2expr(a, ctx) b = _py2expr(b, ctx) s = None s = _coerce_expr_merge(s, a) s = _coerce_expr_merge(s, b) a = s.cast(a) b = s.cast(b) return (a, b) def _reduce(f, l, a): r = a for e in l: r = f(r, e) return r def _coerce_expr_list(alist, ctx=None): has_expr = False for a in alist: if is_expr(a): has_expr = True break if not has_expr: alist = [ _py2expr(a, ctx) for a in alist ] s = _reduce(_coerce_expr_merge, alist, None) return [ s.cast(a) for a in alist ] def is_expr(a): """Return `True` if `a` is a Z3 expression. >>> a = Int('a') >>> is_expr(a) True >>> is_expr(a + 1) True >>> is_expr(IntSort()) False >>> is_expr(1) False >>> is_expr(IntVal(1)) True >>> x = Int('x') >>> is_expr(ForAll(x, x >= 0)) True >>> is_expr(FPVal(1.0)) True """ return isinstance(a, ExprRef) def is_app(a): """Return `True` if `a` is a Z3 function application. Note that, constants are function applications with 0 arguments. >>> a = Int('a') >>> is_app(a) True >>> is_app(a + 1) True >>> is_app(IntSort()) False >>> is_app(1) False >>> is_app(IntVal(1)) True >>> x = Int('x') >>> is_app(ForAll(x, x >= 0)) False """ if not isinstance(a, ExprRef): return False k = _ast_kind(a.ctx, a) return k == Z3_NUMERAL_AST or k == Z3_APP_AST def is_const(a): """Return `True` if `a` is Z3 constant/variable expression. >>> a = Int('a') >>> is_const(a) True >>> is_const(a + 1) False >>> is_const(1) False >>> is_const(IntVal(1)) True >>> x = Int('x') >>> is_const(ForAll(x, x >= 0)) False """ return is_app(a) and a.num_args() == 0 def is_var(a): """Return `True` if `a` is variable. Z3 uses de-Bruijn indices for representing bound variables in quantifiers. >>> x = Int('x') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort()) >>> # Z3 replaces x with bound variables when ForAll is executed. >>> q = ForAll(x, f(x) == x) >>> b = q.body() >>> b f(Var(0)) == Var(0) >>> b.arg(1) Var(0) >>> is_var(b.arg(1)) True """ return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST def get_var_index(a): """Return the de-Bruijn index of the Z3 bounded variable `a`. >>> x = Int('x') >>> y = Int('y') >>> is_var(x) False >>> is_const(x) True >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # Z3 replaces x and y with bound variables when ForAll is executed. >>> q = ForAll([x, y], f(x, y) == x + y) >>> q.body() f(Var(1), Var(0)) == Var(1) + Var(0) >>> b = q.body() >>> b.arg(0) f(Var(1), Var(0)) >>> v1 = b.arg(0).arg(0) >>> v2 = b.arg(0).arg(1) >>> v1 Var(1) >>> v2 Var(0) >>> get_var_index(v1) 1 >>> get_var_index(v2) 0 """ if z3_debug(): _z3_assert(is_var(a), "Z3 bound variable expected") return int(Z3_get_index_value(a.ctx.ref(), a.as_ast())) def is_app_of(a, k): """Return `True` if `a` is an application of the given kind `k`. >>> x = Int('x') >>> n = x + 1 >>> is_app_of(n, Z3_OP_ADD) True >>> is_app_of(n, Z3_OP_MUL) False """ return is_app(a) and a.decl().kind() == k def If(a, b, c, ctx=None): """Create a Z3 if-then-else expression. >>> x = Int('x') >>> y = Int('y') >>> max = If(x > y, x, y) >>> max If(x > y, x, y) >>> simplify(max) If(x <= y, y, x) """ if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic): return Cond(a, b, c, ctx) else: ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx)) s = BoolSort(ctx) a = s.cast(a) b, c = _coerce_exprs(b, c, ctx) if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def Distinct(*args): """Create a Z3 distinct expression. >>> x = Int('x') >>> y = Int('y') >>> Distinct(x, y) x != y >>> z = Int('z') >>> Distinct(x, y, z) Distinct(x, y, z) >>> simplify(Distinct(x, y, z)) Distinct(x, y, z) >>> simplify(Distinct(x, y, z), blast_distinct=True) And(Not(x == y), Not(x == z), Not(y == z)) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx) def _mk_bin(f, a, b): args = (Ast * 2)() if z3_debug(): _z3_assert(a.ctx == b.ctx, "Context mismatch") args[0] = a.as_ast() args[1] = b.as_ast() return f(a.ctx.ref(), 2, args) def Const(name, sort): """Create a constant of the given sort. >>> Const('x', IntSort()) x """ if z3_debug(): _z3_assert(isinstance(sort, SortRef), "Z3 sort expected") ctx = sort.ctx return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx) def Consts(names, sort): """Create several constants of the given sort. `names` is a string containing the names of all constants to be created. Blank spaces separate the names of different constants. >>> x, y, z = Consts('x y z', IntSort()) >>> x + y + z x + y + z """ if isinstance(names, str): names = names.split(" ") return [Const(name, sort) for name in names] def FreshConst(sort, prefix='c'): """Create a fresh constant of a specified sort""" ctx = _get_ctx(sort.ctx) return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx) def Var(idx, s): """Create a Z3 free variable. Free variables are used to create quantified formulas. >>> Var(0, IntSort()) Var(0) >>> eq(Var(0, IntSort()), Var(0, BoolSort())) False """ if z3_debug(): _z3_assert(is_sort(s), "Z3 sort expected") return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx) def RealVar(idx, ctx=None): """ Create a real free variable. Free variables are used to create quantified formulas. They are also used to create polynomials. >>> RealVar(0) Var(0) """ return Var(idx, RealSort(ctx)) def RealVarVector(n, ctx=None): """ Create a list of Real free variables. The variables have ids: 0, 1, ..., n-1 >>> x0, x1, x2, x3 = RealVarVector(4) >>> x2 Var(2) """ return [ RealVar(i, ctx) for i in range(n) ] ######################################### # # Booleans # ######################################### class BoolSortRef(SortRef): """Boolean sort.""" def cast(self, val): """Try to cast `val` as a Boolean. >>> x = BoolSort().cast(True) >>> x True >>> is_expr(x) True >>> is_expr(True) False >>> x.sort() Bool """ if isinstance(val, bool): return BoolVal(val, self.ctx) if z3_debug(): if not is_expr(val): _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val) if not self.eq(val.sort()): _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value") return val def subsort(self, other): return isinstance(other, ArithSortRef) def is_int(self): return True def is_bool(self): return True class BoolRef(ExprRef): """All Boolean expressions are instances of this class.""" def sort(self): return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __rmul__(self, other): return self * other def __mul__(self, other): """Create the Z3 expression `self * other`. """ if other == 1: return self if other == 0: return 0 return If(self, other, 0) def is_bool(a): """Return `True` if `a` is a Z3 Boolean expression. >>> p = Bool('p') >>> is_bool(p) True >>> q = Bool('q') >>> is_bool(And(p, q)) True >>> x = Real('x') >>> is_bool(x) False >>> is_bool(x == 0) True """ return isinstance(a, BoolRef) def is_true(a): """Return `True` if `a` is the Z3 true expression. >>> p = Bool('p') >>> is_true(p) False >>> is_true(simplify(p == p)) True >>> x = Real('x') >>> is_true(x == 0) False >>> # True is a Python Boolean expression >>> is_true(True) False """ return is_app_of(a, Z3_OP_TRUE) def is_false(a): """Return `True` if `a` is the Z3 false expression. >>> p = Bool('p') >>> is_false(p) False >>> is_false(False) False >>> is_false(BoolVal(False)) True """ return is_app_of(a, Z3_OP_FALSE) def is_and(a): """Return `True` if `a` is a Z3 and expression. >>> p, q = Bools('p q') >>> is_and(And(p, q)) True >>> is_and(Or(p, q)) False """ return is_app_of(a, Z3_OP_AND) def is_or(a): """Return `True` if `a` is a Z3 or expression. >>> p, q = Bools('p q') >>> is_or(Or(p, q)) True >>> is_or(And(p, q)) False """ return is_app_of(a, Z3_OP_OR) def is_implies(a): """Return `True` if `a` is a Z3 implication expression. >>> p, q = Bools('p q') >>> is_implies(Implies(p, q)) True >>> is_implies(And(p, q)) False """ return is_app_of(a, Z3_OP_IMPLIES) def is_not(a): """Return `True` if `a` is a Z3 not expression. >>> p = Bool('p') >>> is_not(p) False >>> is_not(Not(p)) True """ return is_app_of(a, Z3_OP_NOT) def is_eq(a): """Return `True` if `a` is a Z3 equality expression. >>> x, y = Ints('x y') >>> is_eq(x == y) True """ return is_app_of(a, Z3_OP_EQ) def is_distinct(a): """Return `True` if `a` is a Z3 distinct expression. >>> x, y, z = Ints('x y z') >>> is_distinct(x == y) False >>> is_distinct(Distinct(x, y, z)) True """ return is_app_of(a, Z3_OP_DISTINCT) def BoolSort(ctx=None): """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used. >>> BoolSort() Bool >>> p = Const('p', BoolSort()) >>> is_bool(p) True >>> r = Function('r', IntSort(), IntSort(), BoolSort()) >>> r(0, 1) r(0, 1) >>> is_bool(r(0, 1)) True """ ctx = _get_ctx(ctx) return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx) def BoolVal(val, ctx=None): """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used. >>> BoolVal(True) True >>> is_true(BoolVal(True)) True >>> is_true(True) False >>> is_false(BoolVal(False)) True """ ctx = _get_ctx(ctx) if val == False: return BoolRef(Z3_mk_false(ctx.ref()), ctx) else: return BoolRef(Z3_mk_true(ctx.ref()), ctx) def Bool(name, ctx=None): """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q) """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx) def Bools(names, ctx=None): """Return a tuple of Boolean constants. `names` is a single string containing all names separated by blank spaces. If `ctx=None`, then the global context is used. >>> p, q, r = Bools('p q r') >>> And(p, Or(q, r)) And(p, Or(q, r)) """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Bool(name, ctx) for name in names] def BoolVector(prefix, sz, ctx=None): """Return a list of Boolean constants of size `sz`. The constants are named using the given prefix. If `ctx=None`, then the global context is used. >>> P = BoolVector('p', 3) >>> P [p__0, p__1, p__2] >>> And(P) And(p__0, p__1, p__2) """ return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ] def FreshBool(prefix='b', ctx=None): """Return a fresh Boolean constant in the given context using the given prefix. If `ctx=None`, then the global context is used. >>> b1 = FreshBool() >>> b2 = FreshBool() >>> eq(b1, b2) False """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx) def Implies(a, b, ctx=None): """Create a Z3 implies expression. >>> p, q = Bools('p q') >>> Implies(p, q) Implies(p, q) """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Xor(a, b, ctx=None): """Create a Z3 Xor expression. >>> p, q = Bools('p q') >>> Xor(p, q) Xor(p, q) >>> simplify(Xor(p, q)) Not(p) == q """ ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) s = BoolSort(ctx) a = s.cast(a) b = s.cast(b) return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def Not(a, ctx=None): """Create a Z3 not expression or probe. >>> p = Bool('p') >>> Not(Not(p)) Not(Not(p)) >>> simplify(Not(Not(p))) p """ ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx)) if is_probe(a): # Not is also used to build probes return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx) else: s = BoolSort(ctx) a = s.cast(a) return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx) def mk_not(a): if is_not(a): return a.arg(0) else: return Not(a) def _has_probe(args): """Return `True` if one of the elements of the given collection is a Z3 probe.""" for arg in args: if is_probe(arg): return True return False def And(*args): """Create a Z3 and-expression or and-probe. >>> p, q, r = Bools('p q r') >>> And(p, q, r) And(p, q, r) >>> P = BoolVector('p', 5) >>> And(P) And(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args)-1] if isinstance(last_arg, Context): ctx = args[len(args)-1] args = args[:len(args)-1] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = main_ctx() args = _get_args(args) ctx_args = _ctx_from_ast_arg_list(args, ctx) if z3_debug(): _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch") _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_and(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx) def Or(*args): """Create a Z3 or-expression or or-probe. >>> p, q, r = Bools('p q r') >>> Or(p, q, r) Or(p, q, r) >>> P = BoolVector('p', 5) >>> Or(P) Or(p__0, p__1, p__2, p__3, p__4) """ last_arg = None if len(args) > 0: last_arg = args[len(args)-1] if isinstance(last_arg, Context): ctx = args[len(args)-1] args = args[:len(args)-1] else: ctx = main_ctx() args = _get_args(args) ctx_args = _ctx_from_ast_arg_list(args, ctx) if z3_debug(): _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch") _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe") if _has_probe(args): return _probe_or(args, ctx) else: args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx) ######################################### # # Patterns # ######################################### class PatternRef(ExprRef): """Patterns are hints for quantifier instantiation. """ def as_ast(self): return Z3_pattern_to_ast(self.ctx_ref(), self.ast) def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def is_pattern(a): """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ]) >>> q ForAll(x, f(x) == 0) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) f(Var(0)) """ return isinstance(a, PatternRef) def MultiPattern(*args): """Create a Z3 multi-pattern using the given expressions `*args` >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ]) >>> q ForAll(x, f(x) != g(x)) >>> q.num_patterns() 1 >>> is_pattern(q.pattern(0)) True >>> q.pattern(0) MultiPattern(f(Var(0)), g(Var(0))) """ if z3_debug(): _z3_assert(len(args) > 0, "At least one argument expected") _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected") ctx = args[0].ctx args, sz = _to_ast_array(args) return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx) def _to_pattern(arg): if is_pattern(arg): return arg else: return MultiPattern(arg) ######################################### # # Quantifiers # ######################################### class QuantifierRef(BoolRef): """Universally and Existentially quantified formulas.""" def as_ast(self): return self.ast def get_id(self): return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) def sort(self): """Return the Boolean sort or sort of Lambda.""" if self.is_lambda(): return _sort(self.ctx, self.as_ast()) return BoolSort(self.ctx) def is_forall(self): """Return `True` if `self` is a universal quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_forall() True >>> q = Exists(x, f(x) != 0) >>> q.is_forall() False """ return Z3_is_quantifier_forall(self.ctx_ref(), self.ast) def is_exists(self): """Return `True` if `self` is an existential quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.is_exists() False >>> q = Exists(x, f(x) != 0) >>> q.is_exists() True """ return Z3_is_quantifier_exists(self.ctx_ref(), self.ast) def is_lambda(self): """Return `True` if `self` is a lambda expression. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = Lambda(x, f(x)) >>> q.is_lambda() True >>> q = Exists(x, f(x) != 0) >>> q.is_lambda() False """ return Z3_is_lambda(self.ctx_ref(), self.ast) def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. """ if z3_debug(): _z3_assert(self.is_lambda(), "quantifier should be a lambda expression") arg = self.sort().domain().cast(arg) return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx) def weight(self): """Return the weight annotation of `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.weight() 1 >>> q = ForAll(x, f(x) == 0, weight=10) >>> q.weight() 10 """ return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast)) def num_patterns(self): """Return the number of patterns (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 """ return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast)) def pattern(self, idx): """Return a pattern (i.e., quantifier instantiation hints) in `self`. >>> f = Function('f', IntSort(), IntSort()) >>> g = Function('g', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ]) >>> q.num_patterns() 2 >>> q.pattern(0) f(Var(0)) >>> q.pattern(1) g(Var(0)) """ if z3_debug(): _z3_assert(idx < self.num_patterns(), "Invalid pattern idx") return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def num_no_patterns(self): """Return the number of no-patterns.""" return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast) def no_pattern(self, idx): """Return a no-pattern.""" if z3_debug(): _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx") return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) def body(self): """Return the expression being quantified. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.body() f(Var(0)) == 0 """ return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx) def num_vars(self): """Return the number of variables bounded by this quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.num_vars() 2 """ return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast)) def var_name(self, idx): """Return a string representing a name used when displaying the quantifier. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_name(0) 'x' >>> q.var_name(1) 'y' """ if z3_debug(): _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx)) def var_sort(self, idx): """Return the sort of a bound variable. >>> f = Function('f', IntSort(), RealSort(), IntSort()) >>> x = Int('x') >>> y = Real('y') >>> q = ForAll([x, y], f(x, y) >= x) >>> q.var_sort(0) Int >>> q.var_sort(1) Real """ if z3_debug(): _z3_assert(idx < self.num_vars(), "Invalid variable idx") return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx) def children(self): """Return a list containing a single element self.body() >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> q.children() [f(Var(0)) == 0] """ return [ self.body() ] def is_quantifier(a): """Return `True` if `a` is a Z3 quantifier. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> q = ForAll(x, f(x) == 0) >>> is_quantifier(q) True >>> is_quantifier(f(x)) False """ return isinstance(a, QuantifierRef) def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): if z3_debug(): _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected") _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)") _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected") _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions") if is_app(vs): ctx = vs.ctx vs = [vs] else: ctx = vs[0].ctx if not is_expr(body): body = BoolVal(body, ctx) num_vars = len(vs) if num_vars == 0: return body _vs = (Ast * num_vars)() for i in range(num_vars): ## TODO: Check if is constant _vs[i] = vs[i].as_ast() patterns = [ _to_pattern(p) for p in patterns ] num_pats = len(patterns) _pats = (Pattern * num_pats)() for i in range(num_pats): _pats[i] = patterns[i].ast _no_pats, num_no_pats = _to_ast_array(no_patterns) qid = to_symbol(qid, ctx) skid = to_symbol(skid, ctx) return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid, num_vars, _vs, num_pats, _pats, num_no_pats, _no_pats, body.as_ast()), ctx) def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 forall formula. The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> ForAll([x, y], f(x, y) >= x) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ]) ForAll([x, y], f(x, y) >= x) >>> ForAll([x, y], f(x, y) >= x, weight=10) ForAll([x, y], f(x, y) >= x) """ return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns) def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): """Create a Z3 exists formula. The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> x = Int('x') >>> y = Int('y') >>> q = Exists([x, y], f(x, y) >= x, skid="foo") >>> q Exists([x, y], f(x, y) >= x) >>> is_quantifier(q) True >>> r = Tactic('nnf')(q).as_expr() >>> is_quantifier(r) False """ return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns) def Lambda(vs, body): """Create a Z3 lambda expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> mem0 = Array('mem0', IntSort(), IntSort()) >>> lo, hi, e, i = Ints('lo hi e i') >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i])) >>> mem1 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i])) """ ctx = body.ctx if is_app(vs): vs = [vs] num_vars = len(vs) _vs = (Ast * num_vars)() for i in range(num_vars): ## TODO: Check if is constant _vs[i] = vs[i].as_ast() return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx) ######################################### # # Arithmetic # ######################################### class ArithSortRef(SortRef): """Real and Integer sorts.""" def is_real(self): """Return `True` if `self` is of the sort Real. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True >>> x = Int('x') >>> x.is_real() False """ return self.kind() == Z3_REAL_SORT def is_int(self): """Return `True` if `self` is of the sort Integer. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> x = Real('x') >>> x.is_int() False """ return self.kind() == Z3_INT_SORT def subsort(self, other): """Return `True` if `self` is a subsort of `other`.""" return self.is_int() and is_arith_sort(other) and other.is_real() def cast(self, val): """Try to cast `val` as an Integer or Real. >>> IntSort().cast(10) 10 >>> is_int(IntSort().cast(10)) True >>> is_int(10) False >>> RealSort().cast(10) 10 >>> is_real(RealSort().cast(10)) True """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") val_s = val.sort() if self.eq(val_s): return val if val_s.is_int() and self.is_real(): return ToReal(val) if val_s.is_bool() and self.is_int(): return If(val, 1, 0) if val_s.is_bool() and self.is_real(): return ToReal(If(val, 1, 0)) if z3_debug(): _z3_assert(False, "Z3 Integer/Real expression expected" ) else: if self.is_int(): return IntVal(val, self.ctx) if self.is_real(): return RealVal(val, self.ctx) if z3_debug(): _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self) def is_arith_sort(s): """Return `True` if s is an arithmetical sort (type). >>> is_arith_sort(IntSort()) True >>> is_arith_sort(RealSort()) True >>> is_arith_sort(BoolSort()) False >>> n = Int('x') + 1 >>> is_arith_sort(n.sort()) True """ return isinstance(s, ArithSortRef) class ArithRef(ExprRef): """Integer and Real expressions.""" def sort(self): """Return the sort (type) of the arithmetical expression `self`. >>> Int('x').sort() Int >>> (Real('x') + 1).sort() Real """ return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def is_int(self): """Return `True` if `self` is an integer expression. >>> x = Int('x') >>> x.is_int() True >>> (x + 1).is_int() True >>> y = Real('y') >>> (x + y).is_int() False """ return self.sort().is_int() def is_real(self): """Return `True` if `self` is an real expression. >>> x = Real('x') >>> x.is_real() True >>> (x + 1).is_real() True """ return self.sort().is_real() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = Int('x') >>> y = Int('y') >>> x + y x + y >>> (x + y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = Int('x') >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = Real('x') >>> y = Real('y') >>> x * y x*y >>> (x * y).sort() Real """ if isinstance(other, BoolRef): return If(other, self, 0) a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = Real('x') >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = Int('x') >>> y = Int('y') >>> x - y x - y >>> (x - y).sort() Int """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = Int('x') >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx) def __pow__(self, other): """Create the Z3 expression `self**other` (** is the power operator). >>> x = Real('x') >>> x**3 x**3 >>> (x**3).sort() Real >>> simplify(IntVal(2)**8) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rpow__(self, other): """Create the Z3 expression `other**self` (** is the power operator). >>> x = Real('x') >>> 2**x 2**x >>> (2**x).sort() Real >>> simplify(2**IntVal(8)) 256 """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> y = Int('y') >>> x/y x/y >>> (x/y).sort() Int >>> (x/y).sexpr() '(div x y)' >>> x = Real('x') >>> y = Real('y') >>> x/y x/y >>> (x/y).sort() Real >>> (x/y).sexpr() '(/ x y)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression `other/self`. >>> x = Int('x') >>> 10/x 10/x >>> (10/x).sexpr() '(div 10 x)' >>> x = Real('x') >>> 10/x 10/x >>> (10/x).sexpr() '(/ 10.0 x)' """ a, b = _coerce_exprs(self, other) return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression `other/self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> y = Int('y') >>> x % y x%y >>> simplify(IntVal(10) % IntVal(3)) 1 """ a, b = _coerce_exprs(self, other) if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression `other%self`. >>> x = Int('x') >>> 10 % x 10%x """ a, b = _coerce_exprs(self, other) if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected") return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __neg__(self): """Return an expression representing `-self`. >>> x = Int('x') >>> -x -x >>> simplify(-(-x)) x """ return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = Int('x') >>> +x x """ return self def __le__(self, other): """Create the Z3 expression `other <= self`. >>> x, y = Ints('x y') >>> x <= y x <= y >>> y = Real('y') >>> x <= y ToReal(x) <= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression `other < self`. >>> x, y = Ints('x y') >>> x < y x < y >>> y = Real('y') >>> x < y ToReal(x) < y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression `other > self`. >>> x, y = Ints('x y') >>> x > y x > y >>> y = Real('y') >>> x > y ToReal(x) > y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression `other >= self`. >>> x, y = Ints('x y') >>> x >= y x >= y >>> y = Real('y') >>> x >= y ToReal(x) >= y """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def is_arith(a): """Return `True` if `a` is an arithmetical expression. >>> x = Int('x') >>> is_arith(x) True >>> is_arith(x + 1) True >>> is_arith(1) False >>> is_arith(IntVal(1)) True >>> y = Real('y') >>> is_arith(y) True >>> is_arith(y + 1) True """ return isinstance(a, ArithRef) def is_int(a): """Return `True` if `a` is an integer expression. >>> x = Int('x') >>> is_int(x + 1) True >>> is_int(1) False >>> is_int(IntVal(1)) True >>> y = Real('y') >>> is_int(y) False >>> is_int(y + 1) False """ return is_arith(a) and a.is_int() def is_real(a): """Return `True` if `a` is a real expression. >>> x = Int('x') >>> is_real(x + 1) False >>> y = Real('y') >>> is_real(y) True >>> is_real(y + 1) True >>> is_real(1) False >>> is_real(RealVal(1)) True """ return is_arith(a) and a.is_real() def _is_numeral(ctx, a): return Z3_is_numeral_ast(ctx.ref(), a) def _is_algebraic(ctx, a): return Z3_is_algebraic_number(ctx.ref(), a) def is_int_value(a): """Return `True` if `a` is an integer value of sort Int. >>> is_int_value(IntVal(1)) True >>> is_int_value(1) False >>> is_int_value(Int('x')) False >>> n = Int('x') + 1 >>> n x + 1 >>> n.arg(1) 1 >>> is_int_value(n.arg(1)) True >>> is_int_value(RealVal("1/3")) False >>> is_int_value(RealVal(1)) False """ return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast()) def is_rational_value(a): """Return `True` if `a` is rational value of sort Real. >>> is_rational_value(RealVal(1)) True >>> is_rational_value(RealVal("3/5")) True >>> is_rational_value(IntVal(1)) False >>> is_rational_value(1) False >>> n = Real('x') + 1 >>> n.arg(1) 1 >>> is_rational_value(n.arg(1)) True >>> is_rational_value(Real('x')) False """ return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast()) def is_algebraic_value(a): """Return `True` if `a` is an algebraic value of sort Real. >>> is_algebraic_value(RealVal("3/5")) False >>> n = simplify(Sqrt(2)) >>> n 1.4142135623? >>> is_algebraic_value(n) True """ return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast()) def is_add(a): """Return `True` if `a` is an expression of the form b + c. >>> x, y = Ints('x y') >>> is_add(x + y) True >>> is_add(x - y) False """ return is_app_of(a, Z3_OP_ADD) def is_mul(a): """Return `True` if `a` is an expression of the form b * c. >>> x, y = Ints('x y') >>> is_mul(x * y) True >>> is_mul(x - y) False """ return is_app_of(a, Z3_OP_MUL) def is_sub(a): """Return `True` if `a` is an expression of the form b - c. >>> x, y = Ints('x y') >>> is_sub(x - y) True >>> is_sub(x + y) False """ return is_app_of(a, Z3_OP_SUB) def is_div(a): """Return `True` if `a` is an expression of the form b / c. >>> x, y = Reals('x y') >>> is_div(x / y) True >>> is_div(x + y) False >>> x, y = Ints('x y') >>> is_div(x / y) False >>> is_idiv(x / y) True """ return is_app_of(a, Z3_OP_DIV) def is_idiv(a): """Return `True` if `a` is an expression of the form b div c. >>> x, y = Ints('x y') >>> is_idiv(x / y) True >>> is_idiv(x + y) False """ return is_app_of(a, Z3_OP_IDIV) def is_mod(a): """Return `True` if `a` is an expression of the form b % c. >>> x, y = Ints('x y') >>> is_mod(x % y) True >>> is_mod(x + y) False """ return is_app_of(a, Z3_OP_MOD) def is_le(a): """Return `True` if `a` is an expression of the form b <= c. >>> x, y = Ints('x y') >>> is_le(x <= y) True >>> is_le(x < y) False """ return is_app_of(a, Z3_OP_LE) def is_lt(a): """Return `True` if `a` is an expression of the form b < c. >>> x, y = Ints('x y') >>> is_lt(x < y) True >>> is_lt(x == y) False """ return is_app_of(a, Z3_OP_LT) def is_ge(a): """Return `True` if `a` is an expression of the form b >= c. >>> x, y = Ints('x y') >>> is_ge(x >= y) True >>> is_ge(x == y) False """ return is_app_of(a, Z3_OP_GE) def is_gt(a): """Return `True` if `a` is an expression of the form b > c. >>> x, y = Ints('x y') >>> is_gt(x > y) True >>> is_gt(x == y) False """ return is_app_of(a, Z3_OP_GT) def is_is_int(a): """Return `True` if `a` is an expression of the form IsInt(b). >>> x = Real('x') >>> is_is_int(IsInt(x)) True >>> is_is_int(x) False """ return is_app_of(a, Z3_OP_IS_INT) def is_to_real(a): """Return `True` if `a` is an expression of the form ToReal(b). >>> x = Int('x') >>> n = ToReal(x) >>> n ToReal(x) >>> is_to_real(n) True >>> is_to_real(x) False """ return is_app_of(a, Z3_OP_TO_REAL) def is_to_int(a): """Return `True` if `a` is an expression of the form ToInt(b). >>> x = Real('x') >>> n = ToInt(x) >>> n ToInt(x) >>> is_to_int(n) True >>> is_to_int(x) False """ return is_app_of(a, Z3_OP_TO_INT) class IntNumRef(ArithRef): """Integer values.""" def as_long(self): """Return a Z3 integer numeral as a Python long (bignum) numeral. >>> v = IntVal(1) >>> v + 1 1 + 1 >>> v.as_long() + 1 2 """ if z3_debug(): _z3_assert(self.is_int(), "Integer value expected") return int(self.as_string()) def as_string(self): """Return a Z3 integer numeral as a Python string. >>> v = IntVal(100) >>> v.as_string() '100' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) class RatNumRef(ArithRef): """Rational values.""" def numerator(self): """ Return the numerator of a Z3 rational numeral. >>> is_rational_value(RealVal("3/5")) True >>> n = RealVal("3/5") >>> n.numerator() 3 >>> is_rational_value(Q(3,5)) True >>> Q(3,5).numerator() 3 """ return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def denominator(self): """ Return the denominator of a Z3 rational numeral. >>> is_rational_value(Q(3,5)) True >>> n = Q(3,5) >>> n.denominator() 5 """ return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator_as_long(self): """ Return the numerator as a Python long. >>> v = RealVal(10000000000) >>> v 10000000000 >>> v + 1 10000000000 + 1 >>> v.numerator_as_long() + 1 == 10000000001 True """ return self.numerator().as_long() def denominator_as_long(self): """ Return the denominator as a Python long. >>> v = RealVal("1/3") >>> v 1/3 >>> v.denominator_as_long() 3 """ return self.denominator().as_long() def is_int(self): return False def is_real(self): return True def is_int_value(self): return self.denominator().is_int() and self.denominator_as_long() == 1 def as_long(self): _z3_assert(self.is_int_value(), "Expected integer fraction") return self.numerator_as_long() def as_decimal(self, prec): """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places. >>> v = RealVal("1/5") >>> v.as_decimal(3) '0.2' >>> v = RealVal("1/3") >>> v.as_decimal(3) '0.333?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def as_string(self): """Return a Z3 rational numeral as a Python string. >>> v = Q(3,6) >>> v.as_string() '1/2' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def as_fraction(self): """Return a Z3 rational as a Python Fraction object. >>> v = RealVal("1/5") >>> v.as_fraction() Fraction(1, 5) """ return Fraction(self.numerator_as_long(), self.denominator_as_long()) class AlgebraicNumRef(ArithRef): """Algebraic irrational values.""" def approx(self, precision=10): """Return a Z3 rational number that approximates the algebraic number `self`. The result `r` is such that |r - self| <= 1/10^precision >>> x = simplify(Sqrt(2)) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 """ return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def as_decimal(self, prec): """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places >>> x = simplify(Sqrt(2)) >>> x.as_decimal(10) '1.4142135623?' >>> x.as_decimal(20) '1.41421356237309504880?' """ return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) def _py2expr(a, ctx=None): if isinstance(a, bool): return BoolVal(a, ctx) if _is_int(a): return IntVal(a, ctx) if isinstance(a, float): return RealVal(a, ctx) if is_expr(a): return a if z3_debug(): _z3_assert(False, "Python bool, int, long or float expected") def IntSort(ctx=None): """Return the integer sort in the given context. If `ctx=None`, then the global context is used. >>> IntSort() Int >>> x = Const('x', IntSort()) >>> is_int(x) True >>> x.sort() == IntSort() True >>> x.sort() == BoolSort() False """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx) def RealSort(ctx=None): """Return the real sort in the given context. If `ctx=None`, then the global context is used. >>> RealSort() Real >>> x = Const('x', RealSort()) >>> is_real(x) True >>> is_int(x) False >>> x.sort() == RealSort() True """ ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx) def _to_int_str(val): if isinstance(val, float): return str(int(val)) elif isinstance(val, bool): if val: return "1" else: return "0" elif _is_int(val): return str(val) elif isinstance(val, str): return val if z3_debug(): _z3_assert(False, "Python value cannot be used as a Z3 integer") def IntVal(val, ctx=None): """Return a Z3 integer value. If `ctx=None`, then the global context is used. >>> IntVal(1) 1 >>> IntVal("100") 100 """ ctx = _get_ctx(ctx) return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx) def RealVal(val, ctx=None): """Return a Z3 real value. `val` may be a Python int, long, float or string representing a number in decimal or rational notation. If `ctx=None`, then the global context is used. >>> RealVal(1) 1 >>> RealVal(1).sort() Real >>> RealVal("3/5") 3/5 >>> RealVal("1.5") 3/2 """ ctx = _get_ctx(ctx) return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx) def RatVal(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> RatVal(3,5) 3/5 >>> RatVal(3,5).sort() Real """ if z3_debug(): _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer") _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer") return simplify(RealVal(a, ctx)/RealVal(b, ctx)) def Q(a, b, ctx=None): """Return a Z3 rational a/b. If `ctx=None`, then the global context is used. >>> Q(3,5) 3/5 >>> Q(3,5).sort() Real """ return simplify(RatVal(a, b)) def Int(name, ctx=None): """Return an integer constant named `name`. If `ctx=None`, then the global context is used. >>> x = Int('x') >>> is_int(x) True >>> is_int(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx) def Ints(names, ctx=None): """Return a tuple of Integer constants. >>> x, y, z = Ints('x y z') >>> Sum(x, y, z) x + y + z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Int(name, ctx) for name in names] def IntVector(prefix, sz, ctx=None): """Return a list of integer constants of size `sz`. >>> X = IntVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 """ return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ] def FreshInt(prefix='x', ctx=None): """Return a fresh integer constant in the given context using the given prefix. >>> x = FreshInt() >>> y = FreshInt() >>> eq(x, y) False >>> x.sort() Int """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx) def Real(name, ctx=None): """Return a real constant named `name`. If `ctx=None`, then the global context is used. >>> x = Real('x') >>> is_real(x) True >>> is_real(x + 1) True """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx) def Reals(names, ctx=None): """Return a tuple of real constants. >>> x, y, z = Reals('x y z') >>> Sum(x, y, z) x + y + z >>> Sum(x, y, z).sort() Real """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [Real(name, ctx) for name in names] def RealVector(prefix, sz, ctx=None): """Return a list of real constants of size `sz`. >>> X = RealVector('x', 3) >>> X [x__0, x__1, x__2] >>> Sum(X) x__0 + x__1 + x__2 >>> Sum(X).sort() Real """ return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ] def FreshReal(prefix='b', ctx=None): """Return a fresh real constant in the given context using the given prefix. >>> x = FreshReal() >>> y = FreshReal() >>> eq(x, y) False >>> x.sort() Real """ ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx) def ToReal(a): """ Return the Z3 expression ToReal(a). >>> x = Int('x') >>> x.sort() Int >>> n = ToReal(x) >>> n ToReal(x) >>> n.sort() Real """ if z3_debug(): _z3_assert(a.is_int(), "Z3 integer expression expected.") ctx = a.ctx return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx) def ToInt(a): """ Return the Z3 expression ToInt(a). >>> x = Real('x') >>> x.sort() Real >>> n = ToInt(x) >>> n ToInt(x) >>> n.sort() Int """ if z3_debug(): _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx) def IsInt(a): """ Return the Z3 predicate IsInt(a). >>> x = Real('x') >>> IsInt(x + "1/2") IsInt(x + 1/2) >>> solve(IsInt(x + "1/2"), x > 0, x < 1) [x = 1/2] >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2") no solution """ if z3_debug(): _z3_assert(a.is_real(), "Z3 real expression expected.") ctx = a.ctx return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx) def Sqrt(a, ctx=None): """ Return a Z3 expression which represents the square root of a. >>> x = Real('x') >>> Sqrt(x) x**(1/2) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/2" def Cbrt(a, ctx=None): """ Return a Z3 expression which represents the cubic root of a. >>> x = Real('x') >>> Cbrt(x) x**(1/3) """ if not is_expr(a): ctx = _get_ctx(ctx) a = RealVal(a, ctx) return a ** "1/3" ######################################### # # Bit-Vectors # ######################################### class BitVecSortRef(SortRef): """Bit-vector sort.""" def size(self): """Return the size (number of bits) of the bit-vector sort `self`. >>> b = BitVecSort(32) >>> b.size() 32 """ return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast)) def subsort(self, other): return is_bv_sort(other) and self.size() < other.size() def cast(self, val): """Try to cast `val` as a Bit-Vector. >>> b = BitVecSort(32) >>> b.cast(10) 10 >>> b.cast(10).sexpr() '#x0000000a' """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") # Idea: use sign_extend if sort of val is a bitvector of smaller size return val else: return BitVecVal(val, self) def is_bv_sort(s): """Return True if `s` is a Z3 bit-vector sort. >>> is_bv_sort(BitVecSort(32)) True >>> is_bv_sort(IntSort()) False """ return isinstance(s, BitVecSortRef) class BitVecRef(ExprRef): """Bit-vector expressions.""" def sort(self): """Return the sort of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> x.sort() BitVec(32) >>> x.sort() == BitVecSort(32) True """ return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def size(self): """Return the number of bits of the bit-vector expression `self`. >>> x = BitVec('x', 32) >>> (x + 1).size() 32 >>> Concat(x, x).size() 64 """ return self.sort().size() def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x + y x + y >>> (x + y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = BitVec('x', 32) >>> 10 + x 10 + x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x * y x*y >>> (x * y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = BitVec('x', 32) >>> 10 * x 10*x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x - y x - y >>> (x - y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = BitVec('x', 32) >>> 10 - x 10 - x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __or__(self, other): """Create the Z3 expression bitwise-or `self | other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x | y x | y >>> (x | y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ror__(self, other): """Create the Z3 expression bitwise-or `other | self`. >>> x = BitVec('x', 32) >>> 10 | x 10 | x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __and__(self, other): """Create the Z3 expression bitwise-and `self & other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x & y x & y >>> (x & y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rand__(self, other): """Create the Z3 expression bitwise-or `other & self`. >>> x = BitVec('x', 32) >>> 10 & x 10 & x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __xor__(self, other): """Create the Z3 expression bitwise-xor `self ^ other`. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x ^ y x ^ y >>> (x ^ y).sort() BitVec(32) """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rxor__(self, other): """Create the Z3 expression bitwise-xor `other ^ self`. >>> x = BitVec('x', 32) >>> 10 ^ x 10 ^ x """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __pos__(self): """Return `self`. >>> x = BitVec('x', 32) >>> +x x """ return self def __neg__(self): """Return an expression representing `-self`. >>> x = BitVec('x', 32) >>> -x -x >>> simplify(-(-x)) x """ return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx) def __invert__(self): """Create the Z3 expression bitwise-not `~self`. >>> x = BitVec('x', 32) >>> ~x ~x >>> simplify(~(~x)) x """ return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx) def __div__(self, other): """Create the Z3 expression (signed) division `self / other`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x / y x/y >>> (x / y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __truediv__(self, other): """Create the Z3 expression (signed) division `self / other`.""" return self.__div__(other) def __rdiv__(self, other): """Create the Z3 expression (signed) division `other / self`. Use the function UDiv() for unsigned division. >>> x = BitVec('x', 32) >>> 10 / x 10/x >>> (10 / x).sexpr() '(bvsdiv #x0000000a x)' >>> UDiv(10, x).sexpr() '(bvudiv #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rtruediv__(self, other): """Create the Z3 expression (signed) division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression (signed) mod `self % other`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> x % y x%y >>> (x % y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rmod__(self, other): """Create the Z3 expression (signed) mod `other % self`. Use the function URem() for unsigned remainder, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> 10 % x 10%x >>> (10 % x).sexpr() '(bvsmod #x0000000a x)' >>> URem(10, x).sexpr() '(bvurem #x0000000a x)' >>> SRem(10, x).sexpr() '(bvsrem #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __le__(self, other): """Create the Z3 expression (signed) `other <= self`. Use the function ULE() for unsigned less than or equal to. >>> x, y = BitVecs('x y', 32) >>> x <= y x <= y >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lt__(self, other): """Create the Z3 expression (signed) `other < self`. Use the function ULT() for unsigned less than. >>> x, y = BitVecs('x y', 32) >>> x < y x < y >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __gt__(self, other): """Create the Z3 expression (signed) `other > self`. Use the function UGT() for unsigned greater than. >>> x, y = BitVecs('x y', 32) >>> x > y x > y >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __ge__(self, other): """Create the Z3 expression (signed) `other >= self`. Use the function UGE() for unsigned greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> x >= y x >= y >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ a, b = _coerce_exprs(self, other) return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rshift__(self, other): """Create the Z3 expression (arithmetical) right shift `self >> other` Use the function LShR() for the right logical shift >>> x, y = BitVecs('x y', 32) >>> x >> y x >> y >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __lshift__(self, other): """Create the Z3 expression left shift `self << other` >>> x, y = BitVecs('x y', 32) >>> x << y x << y >>> (x << y).sexpr() '(bvshl x y)' >>> simplify(BitVecVal(2, 3) << 1) 4 """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) def __rrshift__(self, other): """Create the Z3 expression (arithmetical) right shift `other` >> `self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 >> x 10 >> x >>> (10 >> x).sexpr() '(bvashr #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) def __rlshift__(self, other): """Create the Z3 expression left shift `other << self`. Use the function LShR() for the right logical shift >>> x = BitVec('x', 32) >>> 10 << x 10 << x >>> (10 << x).sexpr() '(bvshl #x0000000a x)' """ a, b = _coerce_exprs(self, other) return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) class BitVecNumRef(BitVecRef): """Bit-vector values.""" def as_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. >>> v = BitVecVal(0xbadc0de, 32) >>> v 195936478 >>> print("0x%.8x" % v.as_long()) 0x0badc0de """ return int(self.as_string()) def as_signed_long(self): """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign. >>> BitVecVal(4, 3).as_signed_long() -4 >>> BitVecVal(7, 3).as_signed_long() -1 >>> BitVecVal(3, 3).as_signed_long() 3 >>> BitVecVal(2**32 - 1, 32).as_signed_long() -1 >>> BitVecVal(2**64 - 1, 64).as_signed_long() -1 """ sz = self.size() val = self.as_long() if val >= 2**(sz - 1): val = val - 2**sz if val < -2**(sz - 1): val = val + 2**sz return int(val) def as_string(self): return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def is_bv(a): """Return `True` if `a` is a Z3 bit-vector expression. >>> b = BitVec('b', 32) >>> is_bv(b) True >>> is_bv(b + 10) True >>> is_bv(Int('x')) False """ return isinstance(a, BitVecRef) def is_bv_value(a): """Return `True` if `a` is a Z3 bit-vector numeral value. >>> b = BitVec('b', 32) >>> is_bv_value(b) False >>> b = BitVecVal(10, 32) >>> b 10 >>> is_bv_value(b) True """ return is_bv(a) and _is_numeral(a.ctx, a.as_ast()) def BV2Int(a, is_signed=False): """Return the Z3 expression BV2Int(a). >>> b = BitVec('b', 3) >>> BV2Int(b).sort() Int >>> x = Int('x') >>> x > BV2Int(b) x > BV2Int(b) >>> x > BV2Int(b, is_signed=False) x > BV2Int(b) >>> x > BV2Int(b, is_signed=True) x > If(b < 0, BV2Int(b) - 8, BV2Int(b)) >>> solve(x > BV2Int(b), b == 1, x < 3) [x = 2, b = 1] """ if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") ctx = a.ctx ## investigate problem with bv2int return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx) def Int2BV(a, num_bits): """Return the z3 expression Int2BV(a, num_bits). It is a bit-vector of width num_bits and represents the modulo of a by 2^num_bits """ ctx = a.ctx return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx) def BitVecSort(sz, ctx=None): """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used. >>> Byte = BitVecSort(8) >>> Word = BitVecSort(16) >>> Byte BitVec(8) >>> x = Const('x', Byte) >>> eq(x, BitVec('x', 8)) True """ ctx = _get_ctx(ctx) return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx) def BitVecVal(val, bv, ctx=None): """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used. >>> v = BitVecVal(10, 32) >>> v 10 >>> print("0x%.8x" % v.as_long()) 0x0000000a """ if is_bv_sort(bv): ctx = bv.ctx return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx) else: ctx = _get_ctx(ctx) return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx) def BitVec(name, bv, ctx=None): """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort. If `ctx=None`, then the global context is used. >>> x = BitVec('x', 16) >>> is_bv(x) True >>> x.size() 16 >>> x.sort() BitVec(16) >>> word = BitVecSort(16) >>> x2 = BitVec('x', word) >>> eq(x, x2) True """ if isinstance(bv, BitVecSortRef): ctx = bv.ctx else: ctx = _get_ctx(ctx) bv = BitVecSort(bv, ctx) return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) def BitVecs(names, bv, ctx=None): """Return a tuple of bit-vector constants of size bv. >>> x, y, z = BitVecs('x y z', 16) >>> x.size() 16 >>> x.sort() BitVec(16) >>> Sum(x, y, z) 0 + x + y + z >>> Product(x, y, z) 1*x*y*z >>> simplify(Product(x, y, z)) x*y*z """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [BitVec(name, bv, ctx) for name in names] def Concat(*args): """Create a Z3 bit-vector concatenation expression. >>> v = BitVecVal(1, 4) >>> Concat(v, v+1, v) Concat(Concat(1, 1 + 1), 1) >>> simplify(Concat(v, v+1, v)) 289 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long()) 121 """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz >= 2, "At least two arguments expected.") ctx = None for a in args: if is_expr(a): ctx = a.ctx break if is_seq(args[0]) or isinstance(args[0], str): args = [_coerce_seq(s, ctx) for s in args] if z3_debug(): _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx) if is_re(args[0]): if z3_debug(): _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx) if z3_debug(): _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.") r = args[0] for i in range(sz - 1): r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx) return r def Extract(high, low, a): """Create a Z3 bit-vector extraction expression, or create a string extraction expression. >>> x = BitVec('x', 8) >>> Extract(6, 2, x) Extract(6, 2, x) >>> Extract(6, 2, x).sort() BitVec(5) >>> simplify(Extract(StringVal("abcd"),2,1)) "c" """ if isinstance(high, str): high = StringVal(high) if is_seq(high): s = high offset, length = _coerce_exprs(low, a, s.ctx) return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx) if z3_debug(): _z3_assert(low <= high, "First argument must be greater than or equal to second argument") _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers") _z3_assert(is_bv(a), "Third argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx) def _check_bv_args(a, b): if z3_debug(): _z3_assert(is_bv(a) or is_bv(b), "First or second argument must be a Z3 bit-vector expression") def ULE(a, b): """Create the Z3 expression (unsigned) `other <= self`. Use the operator <= for signed less than or equal to. >>> x, y = BitVecs('x y', 32) >>> ULE(x, y) ULE(x, y) >>> (x <= y).sexpr() '(bvsle x y)' >>> ULE(x, y).sexpr() '(bvule x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def ULT(a, b): """Create the Z3 expression (unsigned) `other < self`. Use the operator < for signed less than. >>> x, y = BitVecs('x y', 32) >>> ULT(x, y) ULT(x, y) >>> (x < y).sexpr() '(bvslt x y)' >>> ULT(x, y).sexpr() '(bvult x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGE(a, b): """Create the Z3 expression (unsigned) `other >= self`. Use the operator >= for signed greater than or equal to. >>> x, y = BitVecs('x y', 32) >>> UGE(x, y) UGE(x, y) >>> (x >= y).sexpr() '(bvsge x y)' >>> UGE(x, y).sexpr() '(bvuge x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UGT(a, b): """Create the Z3 expression (unsigned) `other > self`. Use the operator > for signed greater than. >>> x, y = BitVecs('x y', 32) >>> UGT(x, y) UGT(x, y) >>> (x > y).sexpr() '(bvsgt x y)' >>> UGT(x, y).sexpr() '(bvugt x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def UDiv(a, b): """Create the Z3 expression (unsigned) division `self / other`. Use the operator / for signed division. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> UDiv(x, y) UDiv(x, y) >>> UDiv(x, y).sort() BitVec(32) >>> (x / y).sexpr() '(bvsdiv x y)' >>> UDiv(x, y).sexpr() '(bvudiv x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def URem(a, b): """Create the Z3 expression (unsigned) remainder `self % other`. Use the operator % for signed modulus, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> URem(x, y) URem(x, y) >>> URem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> URem(x, y).sexpr() '(bvurem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SRem(a, b): """Create the Z3 expression signed remainder. Use the operator % for signed modulus, and URem() for unsigned remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> SRem(x, y) SRem(x, y) >>> SRem(x, y).sort() BitVec(32) >>> (x % y).sexpr() '(bvsmod x y)' >>> SRem(x, y).sexpr() '(bvsrem x y)' """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def LShR(a, b): """Create the Z3 expression logical right shift. Use the operator >> for the arithmetical right shift. >>> x, y = BitVecs('x y', 32) >>> LShR(x, y) LShR(x, y) >>> (x >> y).sexpr() '(bvashr x y)' >>> LShR(x, y).sexpr() '(bvlshr x y)' >>> BitVecVal(4, 3) 4 >>> BitVecVal(4, 3).as_signed_long() -4 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long() -2 >>> simplify(BitVecVal(4, 3) >> 1) 6 >>> simplify(LShR(BitVecVal(4, 3), 1)) 2 >>> simplify(BitVecVal(2, 3) >> 1) 1 >>> simplify(LShR(BitVecVal(2, 3), 1)) 1 """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateLeft(a, b): """Return an expression representing `a` rotated to the left `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateLeft(a, b) RotateLeft(a, b) >>> simplify(RotateLeft(a, 0)) a >>> simplify(RotateLeft(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def RotateRight(a, b): """Return an expression representing `a` rotated to the right `b` times. >>> a, b = BitVecs('a b', 16) >>> RotateRight(a, b) RotateRight(a, b) >>> simplify(RotateRight(a, 0)) a >>> simplify(RotateRight(a, 16)) a """ _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SignExt(n, a): """Return a bit-vector expression with `n` extra sign-bits. >>> x = BitVec('x', 16) >>> n = SignExt(8, x) >>> n.size() 24 >>> n SignExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(SignExt(6, v0)) >>> v 254 >>> v.size() 8 >>> print("%.x" % v.as_long()) fe """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def ZeroExt(n, a): """Return a bit-vector expression with `n` extra zero-bits. >>> x = BitVec('x', 16) >>> n = ZeroExt(8, x) >>> n.size() 24 >>> n ZeroExt(8, x) >>> n.sort() BitVec(24) >>> v0 = BitVecVal(2, 2) >>> v0 2 >>> v0.size() 2 >>> v = simplify(ZeroExt(6, v0)) >>> v 2 >>> v.size() 8 """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) def RepeatBitVec(n, a): """Return an expression representing `n` copies of `a`. >>> x = BitVec('x', 8) >>> n = RepeatBitVec(4, x) >>> n RepeatBitVec(4, x) >>> n.size() 32 >>> v0 = BitVecVal(10, 4) >>> print("%.x" % v0.as_long()) a >>> v = simplify(RepeatBitVec(4, v0)) >>> v.size() 16 >>> print("%.x" % v.as_long()) aaaa """ if z3_debug(): _z3_assert(_is_int(n), "First argument must be an integer") _z3_assert(is_bv(a), "Second argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx) def BVRedAnd(a): """Return the reduction-and expression of `a`.""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx) def BVRedOr(a): """Return the reduction-or expression of `a`.""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx) def BVAddNoOverflow(a, b, signed): """A predicate the determines that bit-vector addition does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVAddNoUnderflow(a, b): """A predicate the determines that signed bit-vector addition does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoOverflow(a, b): """A predicate the determines that bit-vector subtraction does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSubNoUnderflow(a, b, signed): """A predicate the determines that bit-vector subtraction does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVSDivNoOverflow(a, b): """A predicate the determines that bit-vector signed division does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def BVSNegNoOverflow(a): """A predicate the determines that bit-vector unary negation does not overflow""" if z3_debug(): _z3_assert(is_bv(a), "First argument must be a Z3 bit-vector expression") return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx) def BVMulNoOverflow(a, b, signed): """A predicate the determines that bit-vector multiplication does not overflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx) def BVMulNoUnderflow(a, b): """A predicate the determines that bit-vector signed multiplication does not underflow""" _check_bv_args(a, b) a, b = _coerce_exprs(a, b) return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) ######################################### # # Arrays # ######################################### class ArraySortRef(SortRef): """Array sorts.""" def domain(self): """Return the domain of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.domain() Int """ return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx) def range(self): """Return the range of the array sort `self`. >>> A = ArraySort(IntSort(), BoolSort()) >>> A.range() Bool """ return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx) class ArrayRef(ExprRef): """Array expressions. """ def sort(self): """Return the array sort of the array expression `self`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.sort() Array(Int, Bool) """ return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def domain(self): """Shorthand for `self.sort().domain()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.domain() Int """ return self.sort().domain() def range(self): """Shorthand for `self.sort().range()`. >>> a = Array('a', IntSort(), BoolSort()) >>> a.range() Bool """ return self.sort().range() def __getitem__(self, arg): """Return the Z3 expression `self[arg]`. >>> a = Array('a', IntSort(), BoolSort()) >>> i = Int('i') >>> a[i] a[i] >>> a[i].sexpr() '(select a i)' """ arg = self.domain().cast(arg) return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx) def default(self): return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx) def is_array_sort(a): return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT def is_array(a): """Return `True` if `a` is a Z3 array expression. >>> a = Array('a', IntSort(), IntSort()) >>> is_array(a) True >>> is_array(Store(a, 0, 1)) True >>> is_array(a[0]) False """ return isinstance(a, ArrayRef) def is_const_array(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_const_array(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_const_array(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_K(a): """Return `True` if `a` is a Z3 constant array. >>> a = K(IntSort(), 10) >>> is_K(a) True >>> a = Array('a', IntSort(), IntSort()) >>> is_K(a) False """ return is_app_of(a, Z3_OP_CONST_ARRAY) def is_map(a): """Return `True` if `a` is a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> a Map(f, b) >>> is_map(a) True >>> is_map(b) False """ return is_app_of(a, Z3_OP_ARRAY_MAP) def is_default(a): """Return `True` if `a` is a Z3 default array expression. >>> d = Default(K(IntSort(), 10)) >>> is_default(d) True """ return is_app_of(a, Z3_OP_ARRAY_DEFAULT) def get_map_func(a): """Return the function declaration associated with a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort()) >>> b = Array('b', IntSort(), IntSort()) >>> a = Map(f, b) >>> eq(f, get_map_func(a)) True >>> get_map_func(a) f >>> get_map_func(a)(0) f(0) """ if z3_debug(): _z3_assert(is_map(a), "Z3 array map expression expected.") return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx) def ArraySort(*sig): """Return the Z3 array sort with the given domain and range sorts. >>> A = ArraySort(IntSort(), BoolSort()) >>> A Array(Int, Bool) >>> A.domain() Int >>> A.range() Bool >>> AA = ArraySort(IntSort(), A) >>> AA Array(Int, Array(Int, Bool)) """ sig = _get_args(sig) if z3_debug(): _z3_assert(len(sig) > 1, "At least two arguments expected") arity = len(sig) - 1 r = sig[arity] d = sig[0] if z3_debug(): for s in sig: _z3_assert(is_sort(s), "Z3 sort expected") _z3_assert(s.ctx == r.ctx, "Context mismatch") ctx = d.ctx if len(sig) == 2: return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx) dom = (Sort * arity)() for i in range(arity): dom[i] = sig[i].ast return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx) def Array(name, dom, rng): """Return an array constant named `name` with the given domain and range sorts. >>> a = Array('a', IntSort(), IntSort()) >>> a.sort() Array(Int, Int) >>> a[0] a[0] """ s = ArraySort(dom, rng) ctx = s.ctx return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx) def Update(a, i, v): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Update(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") i = a.sort().domain().cast(i) v = a.sort().range().cast(v) ctx = a.ctx return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx) def Default(a): """ Return a default value for array expression. >>> b = K(IntSort(), 1) >>> prove(Default(b) == 1) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a.default() def Store(a, i, v): """Return a Z3 store array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i, v = Ints('i v') >>> s = Store(a, i, v) >>> s.sort() Array(Int, Int) >>> prove(s[i] == v) proved >>> j = Int('j') >>> prove(Implies(i != j, s[j] == a[j])) proved """ return Update(a, i, v) def Select(a, i): """Return a Z3 select array expression. >>> a = Array('a', IntSort(), IntSort()) >>> i = Int('i') >>> Select(a, i) a[i] >>> eq(Select(a, i), a[i]) True """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a[i] def Map(f, *args): """Return a Z3 map array expression. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> a1 = Array('a1', IntSort(), IntSort()) >>> a2 = Array('a2', IntSort(), IntSort()) >>> b = Map(f, a1, a2) >>> b Map(f, a1, a2) >>> prove(b[0] == f(a1[0], a2[0])) proved """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 0, "At least one Z3 array expression expected") _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration") _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected") _z3_assert(len(args) == f.arity(), "Number of arguments mismatch") _args, sz = _to_ast_array(args) ctx = f.ctx return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx) def K(dom, v): """Return a Z3 constant array expression. >>> a = K(IntSort(), 10) >>> a K(Int, 10) >>> a.sort() Array(Int, Int) >>> i = Int('i') >>> a[i] K(Int, 10)[i] >>> simplify(a[i]) 10 """ if z3_debug(): _z3_assert(is_sort(dom), "Z3 sort expected") ctx = dom.ctx if not is_expr(v): v = _py2expr(v, ctx) return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx) def Ext(a, b): """Return extensionality index for one-dimensional arrays. >> a, b = Consts('a b', SetSort(IntSort())) >> Ext(a, b) Ext(a, b) """ ctx = a.ctx if z3_debug(): _z3_assert(is_array_sort(a) and is_array(b), "arguments must be arrays") return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def SetHasSize(a, k): ctx = a.ctx k = _py2expr(k, ctx) return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx) def is_select(a): """Return `True` if `a` is a Z3 array select application. >>> a = Array('a', IntSort(), IntSort()) >>> is_select(a) False >>> i = Int('i') >>> is_select(a[i]) True """ return is_app_of(a, Z3_OP_SELECT) def is_store(a): """Return `True` if `a` is a Z3 array store application. >>> a = Array('a', IntSort(), IntSort()) >>> is_store(a) False >>> is_store(Store(a, 0, 1)) True """ return is_app_of(a, Z3_OP_STORE) ######################################### # # Sets # ######################################### def SetSort(s): """ Create a set sort over element sort s""" return ArraySort(s, BoolSort()) def EmptySet(s): """Create the empty set >>> EmptySet(IntSort()) K(Int, False) """ ctx = s.ctx return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx) def FullSet(s): """Create the full set >>> FullSet(IntSort()) K(Int, True) """ ctx = s.ctx return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx) def SetUnion(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetUnion(a, b) union(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx) def SetIntersect(*args): """ Take the union of sets >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetIntersect(a, b) intersection(a, b) """ args = _get_args(args) ctx = _ctx_from_ast_arg_list(args) _args, sz = _to_ast_array(args) return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx) def SetAdd(s, e): """ Add element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetAdd(a, 1) Store(a, 1, True) """ ctx = _ctx_from_ast_arg_list([s,e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetDel(s, e): """ Remove element e to set s >>> a = Const('a', SetSort(IntSort())) >>> SetDel(a, 1) Store(a, 1, False) """ ctx = _ctx_from_ast_arg_list([s,e]) e = _py2expr(e, ctx) return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx) def SetComplement(s): """ The complement of set s >>> a = Const('a', SetSort(IntSort())) >>> SetComplement(a) complement(a) """ ctx = s.ctx return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx) def SetDifference(a, b): """ The set difference of a and b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> SetDifference(a, b) setminus(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def IsMember(e, s): """ Check if e is a member of set s >>> a = Const('a', SetSort(IntSort())) >>> IsMember(1, a) a[1] """ ctx = _ctx_from_ast_arg_list([s,e]) e = _py2expr(e, ctx) return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx) def IsSubset(a, b): """ Check if a is a subset of b >>> a = Const('a', SetSort(IntSort())) >>> b = Const('b', SetSort(IntSort())) >>> IsSubset(a, b) subset(a, b) """ ctx = _ctx_from_ast_arg_list([a, b]) return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx) ######################################### # # Datatypes # ######################################### def _valid_accessor(acc): """Return `True` if acc is pair of the form (String, Datatype or Sort). """ return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1])) class Datatype: """Helper class for declaring Z3 datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) >>> List.cons(10, List.nil).sort() List >>> cons = List.cons >>> nil = List.nil >>> car = List.car >>> cdr = List.cdr >>> n = cons(1, cons(0, nil)) >>> n cons(1, cons(0, nil)) >>> simplify(cdr(n)) cons(0, nil) >>> simplify(car(n)) 1 """ def __init__(self, name, ctx=None): self.ctx = _get_ctx(ctx) self.name = name self.constructors = [] def __deepcopy__(self, memo={}): r = Datatype(self.name, self.ctx) r.constructors = copy.deepcopy(self.constructors) return r def declare_core(self, name, rec_name, *args): if z3_debug(): _z3_assert(isinstance(name, str), "String expected") _z3_assert(isinstance(rec_name, str), "String expected") _z3_assert(all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)") self.constructors.append((name, rec_name, args)) def declare(self, name, *args): """Declare constructor named `name` with the given accessors `args`. Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared. In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))` declares the constructor named `cons` that builds a new List using an integer and a List. It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create the actual datatype in Z3. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() """ if z3_debug(): _z3_assert(isinstance(name, str), "String expected") _z3_assert(name != "", "Constructor name cannot be empty") return self.declare_core(name, "is-" + name, *args) def __repr__(self): return "Datatype(%s, %s)" % (self.name, self.constructors) def create(self): """Create a Z3 datatype based on the constructors declared using the method `declare()`. The function `CreateDatatypes()` must be used to define mutually recursive datatypes. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.nil nil >>> List.cons(10, List.nil) cons(10, nil) """ return CreateDatatypes([self])[0] class ScopedConstructor: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None: Z3_del_constructor(self.ctx.ref(), self.c) class ScopedConstructorList: """Auxiliary object used to create Z3 datatypes.""" def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if self.ctx.ref() is not None: Z3_del_constructor_list(self.ctx.ref(), self.c) def CreateDatatypes(*ds): """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects. In the following example we define a Tree-List using two mutually recursive datatypes. >>> TreeList = Datatype('TreeList') >>> Tree = Datatype('Tree') >>> # Tree has two constructors: leaf and node >>> Tree.declare('leaf', ('val', IntSort())) >>> # a node contains a list of trees >>> Tree.declare('node', ('children', TreeList)) >>> TreeList.declare('nil') >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList)) >>> Tree, TreeList = CreateDatatypes(Tree, TreeList) >>> Tree.val(Tree.leaf(10)) val(leaf(10)) >>> simplify(Tree.val(Tree.leaf(10))) 10 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil))) >>> n1 node(cons(leaf(10), cons(leaf(20), nil))) >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil)) >>> simplify(n2 == n1) False >>> simplify(TreeList.car(Tree.children(n2)) == n1) True """ ds = _get_args(ds) if z3_debug(): _z3_assert(len(ds) > 0, "At least one Datatype must be specified") _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes") _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch") _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected") ctx = ds[0].ctx num = len(ds) names = (Symbol * num)() out = (Sort * num)() clists = (ConstructorList * num)() to_delete = [] for i in range(num): d = ds[i] names[i] = to_symbol(d.name, ctx) num_cs = len(d.constructors) cs = (Constructor * num_cs)() for j in range(num_cs): c = d.constructors[j] cname = to_symbol(c[0], ctx) rname = to_symbol(c[1], ctx) fs = c[2] num_fs = len(fs) fnames = (Symbol * num_fs)() sorts = (Sort * num_fs)() refs = (ctypes.c_uint * num_fs)() for k in range(num_fs): fname = fs[k][0] ftype = fs[k][1] fnames[k] = to_symbol(fname, ctx) if isinstance(ftype, Datatype): if z3_debug(): _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected") sorts[k] = None refs[k] = ds.index(ftype) else: if z3_debug(): _z3_assert(is_sort(ftype), "Z3 sort expected") sorts[k] = ftype.ast refs[k] = 0 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs) to_delete.append(ScopedConstructor(cs[j], ctx)) clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs) to_delete.append(ScopedConstructorList(clists[i], ctx)) Z3_mk_datatypes(ctx.ref(), num, names, out, clists) result = [] ## Create a field for every constructor, recognizer and accessor for i in range(num): dref = DatatypeSortRef(out[i], ctx) num_cs = dref.num_constructors() for j in range(num_cs): cref = dref.constructor(j) cref_name = cref.name() cref_arity = cref.arity() if cref.arity() == 0: cref = cref() setattr(dref, cref_name, cref) rref = dref.recognizer(j) setattr(dref, "is_" + cref_name, rref) for k in range(cref_arity): aref = dref.accessor(j, k) setattr(dref, aref.name(), aref) result.append(dref) return tuple(result) class DatatypeSortRef(SortRef): """Datatype sorts.""" def num_constructors(self): """Return the number of constructors in the given Z3 datatype. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 """ return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast)) def constructor(self, idx): """Return a constructor of the datatype `self`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> List.constructor(1) nil """ if z3_debug(): _z3_assert(idx < self.num_constructors(), "Invalid constructor index") return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx) def recognizer(self, idx): """In Z3, each constructor has an associated recognizer predicate. If the constructor is named `name`, then the recognizer `is_name`. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> # List is now a Z3 declaration >>> List.num_constructors() 2 >>> List.recognizer(0) is(cons) >>> List.recognizer(1) is(nil) >>> simplify(List.is_nil(List.cons(10, List.nil))) False >>> simplify(List.is_cons(List.cons(10, List.nil))) True >>> l = Const('l', List) >>> simplify(List.is_cons(l)) is(cons, l) """ if z3_debug(): _z3_assert(idx < self.num_constructors(), "Invalid recognizer index") return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx) def accessor(self, i, j): """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor. >>> List = Datatype('List') >>> List.declare('cons', ('car', IntSort()), ('cdr', List)) >>> List.declare('nil') >>> List = List.create() >>> List.num_constructors() 2 >>> List.constructor(0) cons >>> num_accs = List.constructor(0).arity() >>> num_accs 2 >>> List.accessor(0, 0) car >>> List.accessor(0, 1) cdr >>> List.constructor(1) nil >>> num_accs = List.constructor(1).arity() >>> num_accs 0 """ if z3_debug(): _z3_assert(i < self.num_constructors(), "Invalid constructor index") _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index") return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx) class DatatypeRef(ExprRef): """Datatype expressions.""" def sort(self): """Return the datatype sort of the datatype expression `self`.""" return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def TupleSort(name, sorts, ctx = None): """Create a named tuple sort base on a set of underlying sorts Example: >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()]) """ tuple = Datatype(name, ctx) projects = [ ('project%d' % i, sorts[i]) for i in range(len(sorts)) ] tuple.declare(name, *projects) tuple = tuple.create() return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))] def DisjointSum(name, sorts, ctx=None): """Create a named tagged union sort base on a set of underlying sorts Example: >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()]) """ sum = Datatype(name, ctx) for i in range(len(sorts)): sum.declare("inject%d" % i, ("project%d" % i, sorts[i])) sum = sum.create() return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))] def EnumSort(name, values, ctx=None): """Return a new enumeration sort named `name` containing the given values. The result is a pair (sort, list of constants). Example: >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue']) """ if z3_debug(): _z3_assert(isinstance(name, str), "Name must be a string") _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings") _z3_assert(len(values) > 0, "At least one value expected") ctx = _get_ctx(ctx) num = len(values) _val_names = (Symbol * num)() for i in range(num): _val_names[i] = to_symbol(values[i]) _values = (FuncDecl * num)() _testers = (FuncDecl * num)() name = to_symbol(name) S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx) V = [] for i in range(num): V.append(FuncDeclRef(_values[i], ctx)) V = [a() for a in V] return S, V ######################################### # # Parameter Sets # ######################################### class ParamsRef: """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3. Consider using the function `args2params` to create instances of this object. """ def __init__(self, ctx=None, params=None): self.ctx = _get_ctx(ctx) if params is None: self.params = Z3_mk_params(self.ctx.ref()) else: self.params = params Z3_params_inc_ref(self.ctx.ref(), self.params) def __deepcopy__(self, memo={}): return ParamsRef(self.ctx, self.params) def __del__(self): if self.ctx.ref() is not None: Z3_params_dec_ref(self.ctx.ref(), self.params) def set(self, name, val): """Set parameter name with value val.""" if z3_debug(): _z3_assert(isinstance(name, str), "parameter name must be a string") name_sym = to_symbol(name, self.ctx) if isinstance(val, bool): Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val) elif _is_int(val): Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, float): Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val) elif isinstance(val, str): Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx)) else: if z3_debug(): _z3_assert(False, "invalid parameter value") def __repr__(self): return Z3_params_to_string(self.ctx.ref(), self.params) def validate(self, ds): _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected") Z3_params_validate(self.ctx.ref(), self.params, ds.descr) def args2params(arguments, keywords, ctx=None): """Convert python arguments into a Z3_params object. A ':' is added to the keywords, and '_' is replaced with '-' >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True}) (params model true relevancy 2 elim_and true) """ if z3_debug(): _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.") prev = None r = ParamsRef(ctx) for a in arguments: if prev is None: prev = a else: r.set(prev, a) prev = None for k in keywords: v = keywords[k] r.set(k, v) return r class ParamDescrsRef: """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3. """ def __init__(self, descr, ctx=None): _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected") self.ctx = _get_ctx(ctx) self.descr = descr Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr) def __deepcopy__(self, memo={}): return ParamsDescrsRef(self.descr, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr) def size(self): """Return the size of in the parameter description `self`. """ return int(Z3_param_descrs_size(self.ctx.ref(), self.descr)) def __len__(self): """Return the size of in the parameter description `self`. """ return self.size() def get_name(self, i): """Return the i-th parameter name in the parameter description `self`. """ return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i)) def get_kind(self, n): """Return the kind of the parameter named `n`. """ return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def get_documentation(self, n): """Return the documentation string of the parameter named `n`. """ return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) def __getitem__(self, arg): if _is_int(arg): return self.get_name(arg) else: return self.get_kind(arg) def __repr__(self): return Z3_param_descrs_to_string(self.ctx.ref(), self.descr) ######################################### # # Goals # ######################################### class Goal(Z3PPObject): """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible). Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals. A goal has a solution if one of its subgoals has a solution. A goal is unsatisfiable if all subgoals are unsatisfiable. """ def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None): if z3_debug(): _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None") self.ctx = _get_ctx(ctx) self.goal = goal if self.goal is None: self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs) Z3_goal_inc_ref(self.ctx.ref(), self.goal) def __deepcopy__(self, memo={}): return Goal(False, False, False, self.ctx, self.goal) def __del__(self): if self.goal is not None and self.ctx.ref() is not None: Z3_goal_dec_ref(self.ctx.ref(), self.goal) def depth(self): """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`. >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x == 0, y >= x + 1) >>> g.depth() 0 >>> r = Then('simplify', 'solve-eqs')(g) >>> # r has 1 subgoal >>> len(r) 1 >>> r[0].depth() 2 """ return int(Z3_goal_depth(self.ctx.ref(), self.goal)) def inconsistent(self): """Return `True` if `self` contains the `False` constraints. >>> x, y = Ints('x y') >>> g = Goal() >>> g.inconsistent() False >>> g.add(x == 0, x == 1) >>> g [x == 0, x == 1] >>> g.inconsistent() False >>> g2 = Tactic('propagate-values')(g)[0] >>> g2.inconsistent() True """ return Z3_goal_inconsistent(self.ctx.ref(), self.goal) def prec(self): """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`. >>> g = Goal() >>> g.prec() == Z3_GOAL_PRECISE True >>> x, y = Ints('x y') >>> g.add(x == y + 1) >>> g.prec() == Z3_GOAL_PRECISE True >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10) >>> g2 = t(g)[0] >>> g2 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0] >>> g2.prec() == Z3_GOAL_PRECISE False >>> g2.prec() == Z3_GOAL_UNDER True """ return Z3_goal_precision(self.ctx.ref(), self.goal) def precision(self): """Alias for `prec()`. >>> g = Goal() >>> g.precision() == Z3_GOAL_PRECISE True """ return self.prec() def size(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> g.size() 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.size() 2 """ return int(Z3_goal_size(self.ctx.ref(), self.goal)) def __len__(self): """Return the number of constraints in the goal `self`. >>> g = Goal() >>> len(g) 0 >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> len(g) 2 """ return self.size() def get(self, i): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g.get(0) x == 0 >>> g.get(1) y > x """ return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx) def __getitem__(self, arg): """Return a constraint in the goal `self`. >>> g = Goal() >>> x, y = Ints('x y') >>> g.add(x == 0, y > x) >>> g[0] x == 0 >>> g[1] y > x """ if arg >= len(self): raise IndexError return self.get(arg) def assert_exprs(self, *args): """Assert constraints into the goal. >>> x = Int('x') >>> g = Goal() >>> g.assert_exprs(x > 0, x < 2) >>> g [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: arg = s.cast(arg) Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast()) def append(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.append(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.insert(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def add(self, *args): """Add constraints. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0, x < 2) >>> g [x > 0, x < 2] """ self.assert_exprs(*args) def convert_model(self, model): """Retrieve model from a satisfiable goal >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs')) >>> r = t(g) >>> r[0] [Or(b == 0, b == 1), Not(0 <= b)] >>> r[1] [Or(b == 0, b == 1), Not(1 <= b)] >>> # Remark: the subgoal r[0] is unsatisfiable >>> # Creating a solver for solving the second subgoal >>> s = Solver() >>> s.add(r[1]) >>> s.check() sat >>> s.model() [b = 0] >>> # Model s.model() does not assign a value to `a` >>> # It is a model for subgoal `r[1]`, but not for goal `g` >>> # The method convert_model creates a model for `g` from a model for `r[1]`. >>> r[1].convert_model(s.model()) [b = 0, a = 1] """ if z3_debug(): _z3_assert(isinstance(model, ModelRef), "Z3 Model expected") return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the goal.""" return Z3_goal_to_string(self.ctx.ref(), self.goal) def dimacs(self): """Return a textual representation of the goal in DIMACS format.""" return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal) def translate(self, target): """Copy goal `self` to context `target`. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 10) >>> g [x > 10] >>> c2 = Context() >>> g2 = g.translate(c2) >>> g2 [x > 10] >>> g.ctx == main_ctx() True >>> g2.ctx == c2 True >>> g2.ctx == main_ctx() False """ if z3_debug(): _z3_assert(isinstance(target, Context), "target must be a context") return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def simplify(self, *arguments, **keywords): """Return a new simplified goal. This method is essentially invoking the simplify tactic. >>> g = Goal() >>> x = Int('x') >>> g.add(x + 1 >= 2) >>> g [x + 1 >= 2] >>> g2 = g.simplify() >>> g2 [x >= 1] >>> # g was not modified >>> g [x + 1 >= 2] """ t = Tactic('simplify') return t.apply(self, *arguments, **keywords)[0] def as_expr(self): """Return goal `self` as a single Z3 expression. >>> x = Int('x') >>> g = Goal() >>> g.as_expr() True >>> g.add(x > 1) >>> g.as_expr() x > 1 >>> g.add(x < 10) >>> g.as_expr() And(x > 1, x < 10) """ sz = len(self) if sz == 0: return BoolVal(True, self.ctx) elif sz == 1: return self.get(0) else: return And([ self.get(i) for i in range(len(self)) ], self.ctx) ######################################### # # AST Vector # ######################################### class AstVector(Z3PPObject): """A collection (vector) of ASTs.""" def __init__(self, v=None, ctx=None): self.vector = None if v is None: self.ctx = _get_ctx(ctx) self.vector = Z3_mk_ast_vector(self.ctx.ref()) else: self.vector = v assert ctx is not None self.ctx = ctx Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector) def __deepcopy__(self, memo={}): return AstVector(self.vector, self.ctx) def __del__(self): if self.vector is not None and self.ctx.ref() is not None: Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector) def __len__(self): """Return the size of the vector `self`. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> A.push(Int('x')) >>> len(A) 2 """ return int(Z3_ast_vector_size(self.ctx.ref(), self.vector)) def __getitem__(self, i): """Return the AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[1] y """ if isinstance(i, int): if i < 0: i += self.__len__() if i >= self.__len__(): raise IndexError return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx) elif isinstance(i, slice): return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))] def __setitem__(self, i, v): """Update AST at position `i`. >>> A = AstVector() >>> A.push(Int('x') + 1) >>> A.push(Int('y')) >>> A[0] x + 1 >>> A[0] = Int('x') >>> A[0] x """ if i >= self.__len__(): raise IndexError Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast()) def push(self, v): """Add `v` in the end of the vector. >>> A = AstVector() >>> len(A) 0 >>> A.push(Int('x')) >>> len(A) 1 """ Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast()) def resize(self, sz): """Resize the vector to `sz` elements. >>> A = AstVector() >>> A.resize(10) >>> len(A) 10 >>> for i in range(10): A[i] = Int('x') >>> A[5] x """ Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz) def __contains__(self, item): """Return `True` if the vector contains `item`. >>> x = Int('x') >>> A = AstVector() >>> x in A False >>> A.push(x) >>> x in A True >>> (x+1) in A False >>> A.push(x+1) >>> (x+1) in A True >>> A [x, x + 1] """ for elem in self: if elem.eq(item): return True return False def translate(self, other_ctx): """Copy vector `self` to context `other_ctx`. >>> x = Int('x') >>> A = AstVector() >>> A.push(x) >>> c2 = Context() >>> B = A.translate(c2) >>> B [x] """ return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the vector.""" return Z3_ast_vector_to_string(self.ctx.ref(), self.vector) ######################################### # # AST Map # ######################################### class AstMap: """A mapping from ASTs to ASTs.""" def __init__(self, m=None, ctx=None): self.map = None if m is None: self.ctx = _get_ctx(ctx) self.map = Z3_mk_ast_map(self.ctx.ref()) else: self.map = m assert ctx is not None self.ctx = ctx Z3_ast_map_inc_ref(self.ctx.ref(), self.map) def __deepcopy__(self, memo={}): return AstMap(self.map, self.ctx) def __del__(self): if self.map is not None and self.ctx.ref() is not None: Z3_ast_map_dec_ref(self.ctx.ref(), self.map) def __len__(self): """Return the size of the map. >>> M = AstMap() >>> len(M) 0 >>> x = Int('x') >>> M[x] = IntVal(1) >>> len(M) 1 """ return int(Z3_ast_map_size(self.ctx.ref(), self.map)) def __contains__(self, key): """Return `True` if the map contains key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> x in M True >>> x+1 in M False """ return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast()) def __getitem__(self, key): """Retrieve the value associated with key `key`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x] x + 1 """ return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx) def __setitem__(self, k, v): """Add/Update key `k` with value `v`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M[x] x + 1 >>> M[x] = IntVal(1) >>> M[x] 1 """ Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast()) def __repr__(self): return Z3_ast_map_to_string(self.ctx.ref(), self.map) def erase(self, k): """Remove the entry associated with key `k`. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> len(M) 1 >>> M.erase(x) >>> len(M) 0 """ Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast()) def reset(self): """Remove all entries from the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> len(M) 2 >>> M.reset() >>> len(M) 0 """ Z3_ast_map_reset(self.ctx.ref(), self.map) def keys(self): """Return an AstVector containing all keys in the map. >>> M = AstMap() >>> x = Int('x') >>> M[x] = x + 1 >>> M[x+x] = IntVal(1) >>> M.keys() [x, x + x] """ return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx) ######################################### # # Model # ######################################### class FuncEntry: """Store the value of the interpretation of a function in a particular point.""" def __init__(self, entry, ctx): self.entry = entry self.ctx = ctx Z3_func_entry_inc_ref(self.ctx.ref(), self.entry) def __deepcopy__(self, memo={}): return FuncEntry(self.entry, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_func_entry_dec_ref(self.ctx.ref(), self.entry) def num_args(self): """Return the number of arguments in the given entry. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.num_args() 2 """ return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry)) def arg_value(self, idx): """Return the value of argument `idx`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.arg_value(0) 1 >>> e.arg_value(1) 2 >>> try: ... e.arg_value(2) ... except IndexError: ... print("index error") index error """ if idx >= self.num_args(): raise IndexError return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx) def value(self): """Return the value of the function at point `self`. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e [1, 2, 20] >>> e.num_args() 2 >>> e.value() 20 """ return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx) def as_list(self): """Return entry `self` as a Python list. >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10) >>> s.check() sat >>> m = s.model() >>> f_i = m[f] >>> f_i.num_entries() 1 >>> e = f_i.entry(0) >>> e.as_list() [1, 2, 20] """ args = [ self.arg_value(i) for i in range(self.num_args())] args.append(self.value()) return args def __repr__(self): return repr(self.as_list()) class FuncInterp(Z3PPObject): """Stores the interpretation of a function in a Z3 model.""" def __init__(self, f, ctx): self.f = f self.ctx = ctx if self.f is not None: Z3_func_interp_inc_ref(self.ctx.ref(), self.f) def __deepcopy__(self, memo={}): return FuncInterp(self.f, self.ctx) def __del__(self): if self.f is not None and self.ctx.ref() is not None: Z3_func_interp_dec_ref(self.ctx.ref(), self.f) def else_value(self): """ Return the `else` value for a function interpretation. Return None if Z3 did not specify the `else` value for this object. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].else_value() 1 """ r = Z3_func_interp_get_else(self.ctx.ref(), self.f) if r: return _to_expr_ref(r, self.ctx) else: return None def num_entries(self): """Return the number of entries/points in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 """ return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f)) def arity(self): """Return the number of arguments for each entry in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f].arity() 1 """ return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f)) def entry(self, idx): """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].num_entries() 1 >>> m[f].entry(0) [2, 0] """ if idx >= self.num_entries(): raise IndexError return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx) def translate(self, other_ctx): """Copy model 'self' to context 'other_ctx'. """ return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def as_list(self): """Return the function interpretation as a Python list. >>> f = Function('f', IntSort(), IntSort()) >>> s = Solver() >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0) >>> s.check() sat >>> m = s.model() >>> m[f] [2 -> 0, else -> 1] >>> m[f].as_list() [[2, 0], 1] """ r = [ self.entry(i).as_list() for i in range(self.num_entries())] r.append(self.else_value()) return r def __repr__(self): return obj_to_string(self) class ModelRef(Z3PPObject): """Model/Solution of a satisfiability problem (aka system of constraints).""" def __init__(self, m, ctx): assert ctx is not None self.model = m self.ctx = ctx Z3_model_inc_ref(self.ctx.ref(), self.model) def __del__(self): if self.ctx.ref() is not None: Z3_model_dec_ref(self.ctx.ref(), self.model) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the model.""" return Z3_model_to_string(self.ctx.ref(), self.model) def eval(self, t, model_completion=False): """Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.eval(x + 1) 2 >>> m.eval(x == 1) True >>> y = Int('y') >>> m.eval(y + x) 1 + y >>> m.eval(y) y >>> m.eval(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.eval(y + x) 1 """ r = (Ast * 1)() if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r): return _to_expr_ref(r[0], self.ctx) raise Z3Exception("failed to evaluate expression in the model") def evaluate(self, t, model_completion=False): """Alias for `eval`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s.check() sat >>> m = s.model() >>> m.evaluate(x + 1) 2 >>> m.evaluate(x == 1) True >>> y = Int('y') >>> m.evaluate(y + x) 1 + y >>> m.evaluate(y) y >>> m.evaluate(y, model_completion=True) 0 >>> # Now, m contains an interpretation for y >>> m.evaluate(y + x) 1 """ return self.eval(t, model_completion) def __len__(self): """Return the number of constant and function declarations in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, f(x) != x) >>> s.check() sat >>> m = s.model() >>> len(m) 2 """ return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model)) def get_interp(self, decl): """Return the interpretation for a given declaration or constant. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1 >>> m[f] [else -> 0] """ if z3_debug(): _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected") if is_const(decl): decl = decl.decl() try: if decl.arity() == 0: _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast) if _r.value is None: return None r = _to_expr_ref(_r, self.ctx) if is_as_array(r): return self.get_interp(get_as_array_func(r)) else: return r else: return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx) except Z3Exception: return None def num_sorts(self): """Return the number of uninterpreted sorts that contain an interpretation in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 1 """ return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model)) def get_sort(self, idx): """Return the uninterpreted sort at position `idx` < self.num_sorts(). >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.num_sorts() 2 >>> m.get_sort(0) A >>> m.get_sort(1) B """ if idx >= self.num_sorts(): raise IndexError return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx) def sorts(self): """Return all uninterpreted sorts that have an interpretation in the model `self`. >>> A = DeclareSort('A') >>> B = DeclareSort('B') >>> a1, a2 = Consts('a1 a2', A) >>> b1, b2 = Consts('b1 b2', B) >>> s = Solver() >>> s.add(a1 != a2, b1 != b2) >>> s.check() sat >>> m = s.model() >>> m.sorts() [A, B] """ return [ self.get_sort(i) for i in range(self.num_sorts()) ] def get_universe(self, s): """Return the interpretation for the uninterpreted sort `s` in the model `self`. >>> A = DeclareSort('A') >>> a, b = Consts('a b', A) >>> s = Solver() >>> s.add(a != b) >>> s.check() sat >>> m = s.model() >>> m.get_universe(A) [A!val!0, A!val!1] """ if z3_debug(): _z3_assert(isinstance(s, SortRef), "Z3 sort expected") try: return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx) except Z3Exception: return None def __getitem__(self, idx): """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned. The elements can be retrieved using position or the actual declaration. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> len(m) 2 >>> m[0] x >>> m[1] f >>> m[x] 1 >>> m[f] [else -> 0] >>> for d in m: print("%s -> %s" % (d, m[d])) x -> 1 f -> [else -> 0] """ if _is_int(idx): if idx >= len(self): raise IndexError num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model) if (idx < num_consts): return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx) else: return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx) if isinstance(idx, FuncDeclRef): return self.get_interp(idx) if is_const(idx): return self.get_interp(idx.decl()) if isinstance(idx, SortRef): return self.get_universe(idx) if z3_debug(): _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected") return None def decls(self): """Return a list with all symbols that have an interpretation in the model `self`. >>> f = Function('f', IntSort(), IntSort()) >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2, f(x) == 0) >>> s.check() sat >>> m = s.model() >>> m.decls() [x, f] """ r = [] for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx)) for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)): r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx)) return r def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") model = Z3_model_translate(self.ctx.ref(), self.model, target.ref()) return Model(model, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def Model(ctx = None): ctx = _get_ctx(ctx) return ModelRef(Z3_mk_model(ctx.ref()), ctx) def is_as_array(n): """Return true if n is a Z3 expression of the form (_ as-array f).""" return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast()) def get_as_array_func(n): """Return the function declaration f associated with a Z3 expression of the form (_ as-array f).""" if z3_debug(): _z3_assert(is_as_array(n), "as-array Z3 expression expected.") return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx) ######################################### # # Statistics # ######################################### class Statistics: """Statistics for `Solver.check()`.""" def __init__(self, stats, ctx): self.stats = stats self.ctx = ctx Z3_stats_inc_ref(self.ctx.ref(), self.stats) def __deepcopy__(self, memo={}): return Statistics(self.stats, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_stats_dec_ref(self.ctx.ref(), self.stats) def __repr__(self): if in_html_mode(): out = io.StringIO() even = True out.write(u('<table border="1" cellpadding="2" cellspacing="0">')) for k, v in self: if even: out.write(u('<tr style="background-color:#CFCFCF">')) even = False else: out.write(u('<tr>')) even = True out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v))) out.write(u('</table>')) return out.getvalue() else: return Z3_stats_to_string(self.ctx.ref(), self.stats) def __len__(self): """Return the number of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 """ return int(Z3_stats_size(self.ctx.ref(), self.stats)) def __getitem__(self, idx): """Return the value of statistical counter at position `idx`. The result is a pair (key, value). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> len(st) 6 >>> st[0] ('nlsat propagations', 2) >>> st[1] ('nlsat stages', 2) """ if idx >= len(self): raise IndexError if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val) def keys(self): """Return the list of statistical counters. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() """ return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))] def get_key_value(self, key): """Return the value of a particular statistical counter. >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('nlsat propagations') 2 """ for idx in range(len(self)): if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx): if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) else: return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) raise Z3Exception("unknown key") def __getattr__(self, name): """Access the value of statistical using attributes. Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'), we should use '_' (e.g., 'nlsat_propagations'). >>> x = Int('x') >>> s = Then('simplify', 'nlsat').solver() >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.nlsat_propagations 2 >>> st.nlsat_stages 2 """ key = name.replace('_', ' ') try: return self.get_key_value(key) except Z3Exception: raise AttributeError ######################################### # # Solver # ######################################### class CheckSatResult: """Represents the result of a satisfiability check: sat, unsat, unknown. >>> s = Solver() >>> s.check() sat >>> r = s.check() >>> isinstance(r, CheckSatResult) True """ def __init__(self, r): self.r = r def __deepcopy__(self, memo={}): return CheckSatResult(self.r) def __eq__(self, other): return isinstance(other, CheckSatResult) and self.r == other.r def __ne__(self, other): return not self.__eq__(other) def __repr__(self): if in_html_mode(): if self.r == Z3_L_TRUE: return "<b>sat</b>" elif self.r == Z3_L_FALSE: return "<b>unsat</b>" else: return "<b>unknown</b>" else: if self.r == Z3_L_TRUE: return "sat" elif self.r == Z3_L_FALSE: return "unsat" else: return "unknown" def _repr_html_(self): in_html = in_html_mode() set_html_mode(True) res = repr(self) set_html_mode(in_html) return res sat = CheckSatResult(Z3_L_TRUE) unsat = CheckSatResult(Z3_L_FALSE) unknown = CheckSatResult(Z3_L_UNDEF) class Solver(Z3PPObject): """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc.""" def __init__(self, solver=None, ctx=None, logFile=None): assert solver is None or ctx is not None self.ctx = _get_ctx(ctx) self.backtrack_level = 4000000000 self.solver = None if solver is None: self.solver = Z3_mk_solver(self.ctx.ref()) else: self.solver = solver Z3_solver_inc_ref(self.ctx.ref(), self.solver) if logFile is not None: self.set("solver.smtlib2_log", logFile) def __del__(self): if self.solver is not None and self.ctx.ref() is not None: Z3_solver_dec_ref(self.ctx.ref(), self.solver) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. >>> s = Solver() >>> # The option MBQI can be set using three different approaches. >>> s.set(mbqi=True) >>> s.set('MBQI', True) >>> s.set(':mbqi', True) """ p = args2params(args, keys, self.ctx) Z3_solver_set_params(self.ctx.ref(), self.solver, p.params) def push(self): """Create a backtracking point. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_push(self.ctx.ref(), self.solver) def pop(self, num=1): """Backtrack \c num backtracking points. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.push() >>> s.add(x < 1) >>> s [x > 0, x < 1] >>> s.check() unsat >>> s.pop() >>> s.check() sat >>> s [x > 0] """ Z3_solver_pop(self.ctx.ref(), self.solver, num) def num_scopes(self): """Return the current number of backtracking points. >>> s = Solver() >>> s.num_scopes() 0L >>> s.push() >>> s.num_scopes() 1L >>> s.push() >>> s.num_scopes() 2L >>> s.pop() >>> s.num_scopes() 1L """ return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver) def reset(self): """Remove all asserted constraints and backtracking points created using `push()`. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s [x > 0] >>> s.reset() >>> s [] """ Z3_solver_reset(self.ctx.ref(), self.solver) def assert_exprs(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.assert_exprs(x > 0, x < 2) >>> s [x > 0, x < 2] """ args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast()) else: arg = s.cast(arg) Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast()) def add(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.append(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def insert(self, *args): """Assert constraints into the solver. >>> x = Int('x') >>> s = Solver() >>> s.insert(x > 0, x < 2) >>> s [x > 0, x < 2] """ self.assert_exprs(*args) def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Solver() >>> s.set(unsat_core=True) >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast()) def check(self, *assumptions): """Check whether the assertions in the given solver plus the optional assumptions are consistent or not. >>> x = Int('x') >>> s = Solver() >>> s.check() sat >>> s.add(x > 0, x < 2) >>> s.check() sat >>> s.model().eval(x) 1 >>> s.add(x < 1) >>> s.check() unsat >>> s.reset() >>> s.add(2**x == 4) >>> s.check() unknown """ assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = assumptions[i].as_ast() r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions) return CheckSatResult(r) def model(self): """Return a model for the last `check()`. This function raises an exception if a model is not available (e.g., last `check()` returned unsat). >>> s = Solver() >>> a = Int('a') >>> s.add(a + 2 == 0) >>> s.check() sat >>> s.model() [a = -2] """ try: return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def import_model_converter(self, other): """Import model converter from other into the current solver""" Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver) def unsat_core(self): """Return a subset (as an AST vector) of the assumptions provided to the last check(). These are the assumptions Z3 used in the unsatisfiability proof. Assumptions are available in Z3. They are used to extract unsatisfiable cores. They may be also used to "retract" assumptions. Note that, assumptions are not really "soft constraints", but they can be used to implement them. >>> p1, p2, p3 = Bools('p1 p2 p3') >>> x, y = Ints('x y') >>> s = Solver() >>> s.add(Implies(p1, x > 0)) >>> s.add(Implies(p2, y > x)) >>> s.add(Implies(p2, y < 1)) >>> s.add(Implies(p3, y > -3)) >>> s.check(p1, p2, p3) unsat >>> core = s.unsat_core() >>> len(core) 2 >>> p1 in core True >>> p2 in core True >>> p3 in core False >>> # "Retracting" p2 >>> s.check(p1, p3) sat """ return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx) def consequences(self, assumptions, variables): """Determine fixed values for the variables based on the solver state and assumptions. >>> s = Solver() >>> a, b, c, d = Bools('a b c d') >>> s.add(Implies(a,b), Implies(b, c)) >>> s.consequences([a],[b,c,d]) (sat, [Implies(a, b), Implies(a, c)]) >>> s.consequences([Not(c),d],[a,b,c,d]) (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))]) """ if isinstance(assumptions, list): _asms = AstVector(None, self.ctx) for a in assumptions: _asms.push(a) assumptions = _asms if isinstance(variables, list): _vars = AstVector(None, self.ctx) for a in variables: _vars.push(a) variables = _vars _z3_assert(isinstance(assumptions, AstVector), "ast vector expected") _z3_assert(isinstance(variables, AstVector), "ast vector expected") consequences = AstVector(None, self.ctx) r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector) sz = len(consequences) consequences = [ consequences[i] for i in range(sz) ] return CheckSatResult(r), consequences def from_file(self, filename): """Parse assertions from a file""" Z3_solver_from_file(self.ctx.ref(), self.solver, filename) def from_string(self, s): """Parse assertions from a string""" Z3_solver_from_string(self.ctx.ref(), self.solver, s) def cube(self, vars = None): """Get set of cubes The method takes an optional set of variables that restrict which variables may be used as a starting point for cubing. If vars is not None, then the first case split is based on a variable in this set. """ self.cube_vs = AstVector(None, self.ctx) if vars is not None: for v in vars: self.cube_vs.push(v) while True: lvl = self.backtrack_level self.backtrack_level = 4000000000 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx) if (len(r) == 1 and is_false(r[0])): return yield r if (len(r) == 0): return def cube_vars(self): """Access the set of variables that were touched by the most recently generated cube. This set of variables can be used as a starting point for additional cubes. The idea is that variables that appear in clauses that are reduced by the most recent cube are likely more useful to cube on.""" return self.cube_vs def proof(self): """Return a proof for the last `check()`. Proof construction must be enabled.""" return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx) def assertions(self): """Return an AST vector containing all added constraints. >>> s = Solver() >>> s.assertions() [] >>> a = Int('a') >>> s.add(a > 0) >>> s.add(a < 10) >>> s.assertions() [a > 0, a < 10] """ return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx) def units(self): """Return an AST vector containing all currently inferred units. """ return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx) def non_units(self): """Return an AST vector containing all atomic formulas in solver state that are not units. """ return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx) def trail_levels(self): """Return trail and decision levels of the solver state after a check() call. """ trail = self.trail() levels = (ctypes.c_uint * len(trail))() Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels) return trail, levels def trail(self): """Return trail of the solver state after a check() call. """ return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx) def statistics(self): """Return statistics for the last `check()`. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat >>> st = s.statistics() >>> st.get_key_value('final checks') 1 >>> len(st) > 0 True >>> st[0] != 0 True """ return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx) def reason_unknown(self): """Return a string describing why the last `check()` returned `unknown`. >>> x = Int('x') >>> s = SimpleSolver() >>> s.add(2**x == 4) >>> s.check() unknown >>> s.reason_unknown() '(incomplete (theory arithmetic))' """ return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver) def help(self): """Display a string describing all available options.""" print(Z3_solver_get_help(self.ctx.ref(), self.solver)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx) def __repr__(self): """Return a formatted string with all added constraints.""" return obj_to_string(self) def translate(self, target): """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. >>> c1 = Context() >>> c2 = Context() >>> s1 = Solver(ctx=c1) >>> s2 = s1.translate(c2) """ if z3_debug(): _z3_assert(isinstance(target, Context), "argument must be a Z3 context") solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref()) return Solver(solver, target) def __copy__(self): return self.translate(self.ctx) def __deepcopy__(self, memo={}): return self.translate(self.ctx) def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. >>> x = Int('x') >>> s = Solver() >>> s.add(x > 0) >>> s.add(x < 2) >>> r = s.sexpr() """ return Z3_solver_to_string(self.ctx.ref(), self.solver) def dimacs(self, include_names=True): """Return a textual representation of the solver in DIMACS format.""" return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names) def to_smt2(self): """return SMTLIB2 formatted benchmark for solver's assertions""" es = self.assertions() sz = len(es) sz1 = sz if sz1 > 0: sz1 -= 1 v = (Ast * sz1)() for i in range(sz1): v[i] = es[i].as_ast() if sz > 0: e = es[sz1].as_ast() else: e = BoolVal(True, self.ctx).as_ast() return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e) def SolverFor(logic, ctx=None, logFile=None): """Create a solver customized for the given logic. The parameter `logic` is a string. It should be contains the name of a SMT-LIB logic. See http://www.smtlib.org/ for the name of all available logics. >>> s = SolverFor("QF_LIA") >>> x = Int('x') >>> s.add(x > 0) >>> s.add(x < 2) >>> s.check() sat >>> s.model() [x = 1] """ ctx = _get_ctx(ctx) logic = to_symbol(logic) return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile) def SimpleSolver(ctx=None, logFile=None): """Return a simple general purpose solver with limited amount of preprocessing. >>> s = SimpleSolver() >>> x = Int('x') >>> s.add(x > 0) >>> s.check() sat """ ctx = _get_ctx(ctx) return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile) ######################################### # # Fixedpoint # ######################################### class Fixedpoint(Z3PPObject): """Fixedpoint API provides methods for solving with recursive predicates""" def __init__(self, fixedpoint=None, ctx=None): assert fixedpoint is None or ctx is not None self.ctx = _get_ctx(ctx) self.fixedpoint = None if fixedpoint is None: self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref()) else: self.fixedpoint = fixedpoint Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint) self.vars = [] def __deepcopy__(self, memo={}): return FixedPoint(self.fixedpoint, self.ctx) def __del__(self): if self.fixedpoint is not None and self.ctx.ref() is not None: Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params) def help(self): """Display a string describing all available options.""" print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the fixedpoint solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: f = self.abstract(f) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast()) else: arg = s.cast(arg) arg = self.abstract(arg) Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def append(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def insert(self, *args): """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" self.assert_exprs(*args) def add_rule(self, head, body = None, name = None): """Assert rules defining recursive predicates to the fixedpoint solver. >>> a = Bool('a') >>> b = Bool('b') >>> s = Fixedpoint() >>> s.register_relation(a.decl()) >>> s.register_relation(b.decl()) >>> s.fact(a) >>> s.rule(b, a) >>> s.query(b) sat """ if name is None: name = "" name = to_symbol(name, self.ctx) if body is None: head = self.abstract(head) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name) else: body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx),head)) Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def rule(self, head, body = None, name = None): """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, body, name) def fact(self, head, name = None): """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" self.add_rule(head, None, name) def query(self, *query): """Query the fixedpoint engine whether formula is derivable. You can also pass an tuple or list of recursive predicates. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDeclRef): _decls = (FuncDecl * sz)() i = 0 for q in query: _decls[i] = q.ast i = i + 1 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls) else: if sz == 1: query = query[0] else: query = And(query, self.ctx) query = self.abstract(query, False) r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast()) return CheckSatResult(r) def query_from_lvl (self, lvl, *query): """Query the fixedpoint engine whether formula is derivable starting at the given query level. """ query = _get_args(query) sz = len(query) if sz >= 1 and isinstance(query[0], FuncDecl): _z3_assert (False, "unsupported") else: if sz == 1: query = query[0] else: query = And(query) query = self.abstract(query, False) r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl) return CheckSatResult(r) def update_rule(self, head, body, name): """update rule""" if name is None: name = "" name = to_symbol(name, self.ctx) body = _get_args(body) f = self.abstract(Implies(And(body, self.ctx),head)) Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name) def get_answer(self): """Retrieve answer from last query call.""" r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_ground_sat_answer(self): """Retrieve a ground cex from last query call.""" r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint) return _to_expr_ref(r, self.ctx) def get_rules_along_trace(self): """retrieve rules along the counterexample trace""" return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx) def get_rule_names_along_trace(self): """retrieve rule names along the counterexample trace""" # this is a hack as I don't know how to return a list of symbols from C++; # obtain names as a single string separated by semicolons names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint)) # split into individual names return names.split (';') def get_num_levels(self, predicate): """Retrieve number of levels used for predicate in PDR engine""" return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast) def get_cover_delta(self, level, predicate): """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)""" r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast) return _to_expr_ref(r, self.ctx) def add_cover(self, level, predicate, property): """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)""" Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast) def register_relation(self, *relations): """Register relation as recursive""" relations = _get_args(relations) for f in relations: Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast) def set_predicate_representation(self, f, *representations): """Control how relation is represented""" representations = _get_args(representations) representations = [to_symbol(s) for s in representations] sz = len(representations) args = (Symbol * sz)() for i in range(sz): args[i] = representations[i] Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args) def parse_string(self, s): """Parse rules and queries from a string""" return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx) def parse_file(self, f): """Parse rules and queries from a file""" return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx) def get_rules(self): """retrieve rules that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx) def get_assertions(self): """retrieve assertions that have been added to fixedpoint context""" return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)()) def to_string(self, queries): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. Include also queries. """ args, len = _to_ast_array(queries) return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args) def statistics(self): """Return statistics for the last `query()`. """ return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx) def reason_unknown(self): """Return a string describing why the last `query()` returned `unknown`. """ return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint) def declare_var(self, *vars): """Add variable or several variables. The added variable or variables will be bound in the rules and queries """ vars = _get_args(vars) for v in vars: self.vars += [v] def abstract(self, fml, is_forall=True): if self.vars == []: return fml if is_forall: return ForAll(self.vars, fml) else: return Exists(self.vars, fml) ######################################### # # Finite domains # ######################################### class FiniteDomainSortRef(SortRef): """Finite domain sort.""" def size(self): """Return the size of the finite domain sort""" r = (ctypes.c_ulonglong * 1)() if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r): return r[0] else: raise Z3Exception("Failed to retrieve finite domain sort size") def FiniteDomainSort(name, sz, ctx=None): """Create a named finite domain sort of a given size sz""" if not isinstance(name, Symbol): name = to_symbol(name) ctx = _get_ctx(ctx) return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx) def is_finite_domain_sort(s): """Return True if `s` is a Z3 finite-domain sort. >>> is_finite_domain_sort(FiniteDomainSort('S', 100)) True >>> is_finite_domain_sort(IntSort()) False """ return isinstance(s, FiniteDomainSortRef) class FiniteDomainRef(ExprRef): """Finite-domain expressions.""" def sort(self): """Return the sort of the finite-domain expression `self`.""" return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def is_finite_domain(a): """Return `True` if `a` is a Z3 finite-domain expression. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain(b) True >>> is_finite_domain(Int('x')) False """ return isinstance(a, FiniteDomainRef) class FiniteDomainNumRef(FiniteDomainRef): """Integer values.""" def as_long(self): """Return a Z3 finite-domain numeral as a Python long (bignum) numeral. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(3, s) >>> v 3 >>> v.as_long() + 1 4 """ return int(self.as_string()) def as_string(self): """Return a Z3 finite-domain numeral as a Python string. >>> s = FiniteDomainSort('S', 100) >>> v = FiniteDomainVal(42, s) >>> v.as_string() '42' """ return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) def FiniteDomainVal(val, sort, ctx=None): """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used. >>> s = FiniteDomainSort('S', 256) >>> FiniteDomainVal(255, s) 255 >>> FiniteDomainVal('100', s) 100 """ if z3_debug(): _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" ) ctx = sort.ctx return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx) def is_finite_domain_value(a): """Return `True` if `a` is a Z3 finite-domain value. >>> s = FiniteDomainSort('S', 100) >>> b = Const('b', s) >>> is_finite_domain_value(b) False >>> b = FiniteDomainVal(10, s) >>> b 10 >>> is_finite_domain_value(b) True """ return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast()) ######################################### # # Optimize # ######################################### class OptimizeObjective: def __init__(self, opt, value, is_max): self._opt = opt self._value = value self._is_max = is_max def lower(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper(self): opt = self._opt return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def lower_values(self): opt = self._opt return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def upper_values(self): opt = self._opt return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx) def value(self): if self._is_max: return self.upper() else: return self.lower() def __str__(self): return "%s:%s" % (self._value, self._is_max) class Optimize(Z3PPObject): """Optimize API provides methods for solving using objective functions and weighted soft constraints""" def __init__(self, ctx=None): self.ctx = _get_ctx(ctx) self.optimize = Z3_mk_optimize(self.ctx.ref()) Z3_optimize_inc_ref(self.ctx.ref(), self.optimize) def __deepcopy__(self, memo={}): return Optimize(self.optimize, self.ctx) def __del__(self): if self.optimize is not None and self.ctx.ref() is not None: Z3_optimize_dec_ref(self.ctx.ref(), self.optimize) def set(self, *args, **keys): """Set a configuration option. The method `help()` return a string containing all available options. """ p = args2params(args, keys, self.ctx) Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params) def help(self): """Display a string describing all available options.""" print(Z3_optimize_get_help(self.ctx.ref(), self.optimize)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx) def assert_exprs(self, *args): """Assert constraints as background axioms for the optimize solver.""" args = _get_args(args) s = BoolSort(self.ctx) for arg in args: if isinstance(arg, Goal) or isinstance(arg, AstVector): for f in arg: Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast()) else: arg = s.cast(arg) Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast()) def add(self, *args): """Assert constraints as background axioms for the optimize solver. Alias for assert_expr.""" self.assert_exprs(*args) def __iadd__(self, fml): self.add(fml) return self def assert_and_track(self, a, p): """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`. If `p` is a string, it will be automatically converted into a Boolean constant. >>> x = Int('x') >>> p3 = Bool('p3') >>> s = Optimize() >>> s.assert_and_track(x > 0, 'p1') >>> s.assert_and_track(x != 1, 'p2') >>> s.assert_and_track(x < 0, p3) >>> print(s.check()) unsat >>> c = s.unsat_core() >>> len(c) 2 >>> Bool('p1') in c True >>> Bool('p2') in c False >>> p3 in c True """ if isinstance(p, str): p = Bool(p, self.ctx) _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast()) def add_soft(self, arg, weight = "1", id = None): """Add soft constraint with optional weight and optional identifier. If no weight is supplied, then the penalty for violating the soft constraint is 1. Soft constraints are grouped by identifiers. Soft constraints that are added without identifiers are grouped by default. """ if _is_int(weight): weight = "%d" % weight elif isinstance(weight, float): weight = "%f" % weight if not isinstance(weight, str): raise Z3Exception("weight should be a string or an integer") if id is None: id = "" id = to_symbol(id, self.ctx) v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id) return OptimizeObjective(self, v, False) def maximize(self, arg): """Add objective function to maximize.""" return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True) def minimize(self, arg): """Add objective function to minimize.""" return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False) def push(self): """create a backtracking point for added rules, facts and assertions""" Z3_optimize_push(self.ctx.ref(), self.optimize) def pop(self): """restore to previously created backtracking point""" Z3_optimize_pop(self.ctx.ref(), self.optimize) def check(self, *assumptions): """Check satisfiability while optimizing objective functions.""" assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = assumptions[i].as_ast() return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions)) def reason_unknown(self): """Return a string that describes why the last `check()` returned `unknown`.""" return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize) def model(self): """Return a model for the last check().""" try: return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx) except Z3Exception: raise Z3Exception("model is not available") def unsat_core(self): return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx) def lower(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower() def upper(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper() def lower_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.lower_values() def upper_values(self, obj): if not isinstance(obj, OptimizeObjective): raise Z3Exception("Expecting objective handle returned by maximize/minimize") return obj.upper_values() def from_file(self, filename): """Parse assertions and objectives from a file""" Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename) def from_string(self, s): """Parse assertions and objectives from a string""" Z3_optimize_from_string(self.ctx.ref(), self.optimize, s) def assertions(self): """Return an AST vector containing all added constraints.""" return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx) def objectives(self): """returns set of objective functions""" return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx) def __repr__(self): """Return a formatted string with all added rules and constraints.""" return self.sexpr() def sexpr(self): """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. """ return Z3_optimize_to_string(self.ctx.ref(), self.optimize) def statistics(self): """Return statistics for the last check`. """ return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx) ######################################### # # ApplyResult # ######################################### class ApplyResult(Z3PPObject): """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters.""" def __init__(self, result, ctx): self.result = result self.ctx = ctx Z3_apply_result_inc_ref(self.ctx.ref(), self.result) def __deepcopy__(self, memo={}): return ApplyResult(self.result, self.ctx) def __del__(self): if self.ctx.ref() is not None: Z3_apply_result_dec_ref(self.ctx.ref(), self.result) def __len__(self): """Return the number of subgoals in `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> len(r) 2 >>> t = Then(Tactic('split-clause'), Tactic('split-clause')) >>> len(t(g)) 4 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values')) >>> len(t(g)) 1 """ return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result)) def __getitem__(self, idx): """Return one of the subgoals stored in ApplyResult object `self`. >>> a, b = Ints('a b') >>> g = Goal() >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) >>> t = Tactic('split-clause') >>> r = t(g) >>> r[0] [a == 0, Or(b == 0, b == 1), a > b] >>> r[1] [a == 1, Or(b == 0, b == 1), a > b] """ if idx >= len(self): raise IndexError return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx) def __repr__(self): return obj_to_string(self) def sexpr(self): """Return a textual representation of the s-expression representing the set of subgoals in `self`.""" return Z3_apply_result_to_string(self.ctx.ref(), self.result) def as_expr(self): """Return a Z3 expression consisting of all subgoals. >>> x = Int('x') >>> g = Goal() >>> g.add(x > 1) >>> g.add(Or(x == 2, x == 3)) >>> r = Tactic('simplify')(g) >>> r [[Not(x <= 1), Or(x == 2, x == 3)]] >>> r.as_expr() And(Not(x <= 1), Or(x == 2, x == 3)) >>> r = Tactic('split-clause')(g) >>> r [[x > 1, x == 2], [x > 1, x == 3]] >>> r.as_expr() Or(And(x > 1, x == 2), And(x > 1, x == 3)) """ sz = len(self) if sz == 0: return BoolVal(False, self.ctx) elif sz == 1: return self[0].as_expr() else: return Or([ self[i].as_expr() for i in range(len(self)) ]) ######################################### # # Tactics # ######################################### class Tactic: """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver(). Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond(). """ def __init__(self, tactic, ctx=None): self.ctx = _get_ctx(ctx) self.tactic = None if isinstance(tactic, TacticObj): self.tactic = tactic else: if z3_debug(): _z3_assert(isinstance(tactic, str), "tactic name expected") try: self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic)) except Z3Exception: raise Z3Exception("unknown tactic '%s'" % tactic) Z3_tactic_inc_ref(self.ctx.ref(), self.tactic) def __deepcopy__(self, memo={}): return Tactic(self.tactic, self.ctx) def __del__(self): if self.tactic is not None and self.ctx.ref() is not None: Z3_tactic_dec_ref(self.ctx.ref(), self.tactic) def solver(self, logFile=None): """Create a solver using the tactic `self`. The solver supports the methods `push()` and `pop()`, but it will always solve each `check()` from scratch. >>> t = Then('simplify', 'nlsat') >>> s = t.solver() >>> x = Real('x') >>> s.add(x**2 == 2, x > 0) >>> s.check() sat >>> s.model() [x = 1.4142135623?] """ return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile) def apply(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t.apply(And(x == 0, y >= x + 1)) [[y >= 1]] """ if z3_debug(): _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected") goal = _to_goal(goal) if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, self.ctx) return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx) else: return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx) def __call__(self, goal, *arguments, **keywords): """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. >>> x, y = Ints('x y') >>> t = Tactic('solve-eqs') >>> t(And(x == 0, y >= x + 1)) [[y >= 1]] """ return self.apply(goal, *arguments, **keywords) def help(self): """Display a string containing a description of the available options for the `self` tactic.""" print(Z3_tactic_get_help(self.ctx.ref(), self.tactic)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx) def _to_goal(a): if isinstance(a, BoolRef): goal = Goal(ctx = a.ctx) goal.add(a) return goal else: return a def _to_tactic(t, ctx=None): if isinstance(t, Tactic): return t else: return Tactic(t, ctx) def _and_then(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def _or_else(t1, t2, ctx=None): t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def AndThen(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. >>> x, y = Ints('x y') >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get('ctx', None) num = len(ts) r = ts[0] for i in range(num - 1): r = _and_then(r, ts[i+1], ctx) return r def Then(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks). >>> x, y = Ints('x y') >>> t = Then(Tactic('simplify'), Tactic('solve-eqs')) >>> t(And(x == 0, y > x + 1)) [[Not(y <= 1)]] >>> t(And(x == 0, y > x + 1)).as_expr() Not(y <= 1) """ return AndThen(*ts, **ks) def OrElse(*ts, **ks): """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = OrElse(Tactic('split-clause'), Tactic('skip')) >>> # Tactic split-clause fails if there is no clause in the given goal. >>> t(x == 0) [[x == 0]] >>> t(Or(x == 0, x == 1)) [[x == 0], [x == 1]] """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = ks.get('ctx', None) num = len(ts) r = ts[0] for i in range(num - 1): r = _or_else(r, ts[i+1], ctx) return r def ParOr(*ts, **ks): """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail). >>> x = Int('x') >>> t = ParOr(Tactic('simplify'), Tactic('fail')) >>> t(x + 1 == 2) [[x == 1]] """ if z3_debug(): _z3_assert(len(ts) >= 2, "At least two arguments expected") ctx = _get_ctx(ks.get('ctx', None)) ts = [ _to_tactic(t, ctx) for t in ts ] sz = len(ts) _args = (TacticObj * sz)() for i in range(sz): _args[i] = ts[i].tactic return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx) def ParThen(t1, t2, ctx=None): """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel. >>> x, y = Ints('x y') >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values')) >>> t(And(Or(x == 1, x == 2), y == x + 1)) [[x == 1, y == 2], [x == 2, y == 3]] """ t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) if z3_debug(): _z3_assert(t1.ctx == t2.ctx, "Context mismatch") return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) def ParAndThen(t1, t2, ctx=None): """Alias for ParThen(t1, t2, ctx).""" return ParThen(t1, t2, ctx) def With(t, *args, **keys): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> t = With(Tactic('simplify'), som=True) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ ctx = keys.pop('ctx', None) t = _to_tactic(t, ctx) p = args2params(args, keys, t.ctx) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def WithParams(t, p): """Return a tactic that applies tactic `t` using the given configuration options. >>> x, y = Ints('x y') >>> p = ParamsRef() >>> p.set("som", True) >>> t = WithParams(Tactic('simplify'), p) >>> t((x + 1)*(y + 2) == 0) [[2*x + y + x*y == -2]] """ t = _to_tactic(t, None) return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx) def Repeat(t, max=4294967295, ctx=None): """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached. >>> x, y = Ints('x y') >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y) >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) >>> r = t(c) >>> for subgoal in r: print(subgoal) [x == 0, y == 0, x > y] [x == 0, y == 1, x > y] [x == 1, y == 0, x > y] [x == 1, y == 1, x > y] >>> t = Then(t, Tactic('propagate-values')) >>> t(c) [[x == 1, y == 0]] """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx) def TryFor(t, ms, ctx=None): """Return a tactic that applies `t` to a given goal for `ms` milliseconds. If `t` does not terminate in `ms` milliseconds, then it fails. """ t = _to_tactic(t, ctx) return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx) def tactics(ctx=None): """Return a list of all available tactics in Z3. >>> l = tactics() >>> l.count('simplify') == 1 True """ ctx = _get_ctx(ctx) return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ] def tactic_description(name, ctx=None): """Return a short description for the tactic named `name`. >>> d = tactic_description('simplify') """ ctx = _get_ctx(ctx) return Z3_tactic_get_descr(ctx.ref(), name) def describe_tactics(): """Display a (tabular) description of all available tactics in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for t in tactics(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print('<tr>') even = True print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40))) print('</table>') else: for t in tactics(): print('%s : %s' % (t, tactic_description(t))) class Probe: """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used.""" def __init__(self, probe, ctx=None): self.ctx = _get_ctx(ctx) self.probe = None if isinstance(probe, ProbeObj): self.probe = probe elif isinstance(probe, float): self.probe = Z3_probe_const(self.ctx.ref(), probe) elif _is_int(probe): self.probe = Z3_probe_const(self.ctx.ref(), float(probe)) elif isinstance(probe, bool): if probe: self.probe = Z3_probe_const(self.ctx.ref(), 1.0) else: self.probe = Z3_probe_const(self.ctx.ref(), 0.0) else: if z3_debug(): _z3_assert(isinstance(probe, str), "probe name expected") try: self.probe = Z3_mk_probe(self.ctx.ref(), probe) except Z3Exception: raise Z3Exception("unknown probe '%s'" % probe) Z3_probe_inc_ref(self.ctx.ref(), self.probe) def __deepcopy__(self, memo={}): return Probe(self.probe, self.ctx) def __del__(self): if self.probe is not None and self.ctx.ref() is not None: Z3_probe_dec_ref(self.ctx.ref(), self.probe) def __lt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`. >>> p = Probe('size') < 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __gt__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`. >>> p = Probe('size') > 10 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __le__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`. >>> p = Probe('size') <= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ge__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`. >>> p = Probe('size') >= 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __eq__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`. >>> p = Probe('size') == 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 1.0 """ return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx) def __ne__(self, other): """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`. >>> p = Probe('size') != 2 >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 0.0 """ p = self.__eq__(other) return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx) def __call__(self, goal): """Evaluate the probe `self` in the given goal. >>> p = Probe('size') >>> x = Int('x') >>> g = Goal() >>> g.add(x > 0) >>> g.add(x < 10) >>> p(g) 2.0 >>> g.add(x < 20) >>> p(g) 3.0 >>> p = Probe('num-consts') >>> p(g) 1.0 >>> p = Probe('is-propositional') >>> p(g) 0.0 >>> p = Probe('is-qflia') >>> p(g) 1.0 """ if z3_debug(): _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected") goal = _to_goal(goal) return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal) def is_probe(p): """Return `True` if `p` is a Z3 probe. >>> is_probe(Int('x')) False >>> is_probe(Probe('memory')) True """ return isinstance(p, Probe) def _to_probe(p, ctx=None): if is_probe(p): return p else: return Probe(p, ctx) def probes(ctx=None): """Return a list of all available probes in Z3. >>> l = probes() >>> l.count('memory') == 1 True """ ctx = _get_ctx(ctx) return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ] def probe_description(name, ctx=None): """Return a short description for the probe named `name`. >>> d = probe_description('memory') """ ctx = _get_ctx(ctx) return Z3_probe_get_descr(ctx.ref(), name) def describe_probes(): """Display a (tabular) description of all available probes in Z3.""" if in_html_mode(): even = True print('<table border="1" cellpadding="2" cellspacing="0">') for p in probes(): if even: print('<tr style="background-color:#CFCFCF">') even = False else: print('<tr>') even = True print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40))) print('</table>') else: for p in probes(): print('%s : %s' % (p, probe_description(p))) def _probe_nary(f, args, ctx): if z3_debug(): _z3_assert(len(args) > 0, "At least one argument expected") num = len(args) r = _to_probe(args[0], ctx) for i in range(num - 1): r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx) return r def _probe_and(args, ctx): return _probe_nary(Z3_probe_and, args, ctx) def _probe_or(args, ctx): return _probe_nary(Z3_probe_or, args, ctx) def FailIf(p, ctx=None): """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal. >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx) def When(p, t, ctx=None): """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. >>> t = When(Probe('size') > 2, Tactic('simplify')) >>> x, y = Ints('x y') >>> g = Goal() >>> g.add(x > 0) >>> g.add(y > 0) >>> t(g) [[x > 0, y > 0]] >>> g.add(x == y + 1) >>> t(g) [[Not(x <= 0), Not(y <= 0), x == 1 + y]] """ p = _to_probe(p, ctx) t = _to_tactic(t, ctx) return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx) def Cond(p, t1, t2, ctx=None): """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise. >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt')) """ p = _to_probe(p, ctx) t1 = _to_tactic(t1, ctx) t2 = _to_tactic(t2, ctx) return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx) ######################################### # # Utils # ######################################### def simplify(a, *arguments, **keywords): """Simplify the expression `a` using the given options. This function has many options. Use `help_simplify` to obtain the complete list. >>> x = Int('x') >>> y = Int('y') >>> simplify(x + 1 + y + x + 1) 2 + 2*x + y >>> simplify((x + 1)*(y + 1), som=True) 1 + x + y + x*y >>> simplify(Distinct(x, y, 1), blast_distinct=True) And(Not(x == y), Not(x == 1), Not(y == 1)) >>> simplify(And(x == 0, y == 1), elim_and=True) Not(Or(Not(x == 0), Not(y == 1))) """ if z3_debug(): _z3_assert(is_expr(a), "Z3 expression expected") if len(arguments) > 0 or len(keywords) > 0: p = args2params(arguments, keywords, a.ctx) return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx) else: return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx) def help_simplify(): """Return a string describing all options available for Z3 `simplify` procedure.""" print(Z3_simplify_get_help(main_ctx().ref())) def simplify_param_descrs(): """Return the set of parameter descriptions for Z3 `simplify` procedure.""" return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx()) def substitute(t, *m): """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to. >>> x = Int('x') >>> y = Int('y') >>> substitute(x + 1, (x, y + 1)) y + 1 + 1 >>> f = Function('f', IntSort(), IntSort()) >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1))) 1 + 1 """ if isinstance(m, tuple): m1 = _get_args(m) if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1): m = m1 if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.") num = len(m) _from = (Ast * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_ast() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx) def substitute_vars(t, *m): """Substitute the free variables in t with the expression in m. >>> v0 = Var(0, IntSort()) >>> v1 = Var(1, IntSort()) >>> x = Int('x') >>> f = Function('f', IntSort(), IntSort(), IntSort()) >>> # replace v0 with x+1 and v1 with x >>> substitute_vars(f(v0, v1), x + 1, x) f(x + 1, x) """ if z3_debug(): _z3_assert(is_expr(t), "Z3 expression expected") _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.") num = len(m) _to = (Ast * num)() for i in range(num): _to[i] = m[i].as_ast() return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx) def Sum(*args): """Create the sum of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Sum(a, b, c) a + b + c >>> Sum([a, b, c]) a + b + c >>> A = IntVector('a', 5) >>> Sum(A) a__0 + a__1 + a__2 + a__3 + a__4 """ args = _get_args(args) if len(args) == 0: return 0 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a + b, args, 0) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a + b, args, 0) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx) def Product(*args): """Create the product of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Product(a, b, c) a*b*c >>> Product([a, b, c]) a*b*c >>> A = IntVector('a', 5) >>> Product(A) a__0*a__1*a__2*a__3*a__4 """ args = _get_args(args) if len(args) == 0: return 1 ctx = _ctx_from_ast_arg_list(args) if ctx is None: return _reduce(lambda a, b: a * b, args, 1) args = _coerce_expr_list(args, ctx) if is_bv(args[0]): return _reduce(lambda a, b: a * b, args, 1) else: _args, sz = _to_ast_array(args) return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx) def AtMost(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtMost(a, b, c, 2) """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx) def AtLeast(*args): """Create an at-most Pseudo-Boolean k constraint. >>> a, b, c = Bools('a b c') >>> f = AtLeast(a, b, c, 2) """ args = _get_args(args) if z3_debug(): _z3_assert(len(args) > 1, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args1 = _coerce_expr_list(args[:-1], ctx) k = args[-1] _args, sz = _to_ast_array(args1) return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx) def _reorder_pb_arg(arg): a, b = arg if not _is_int(b) and _is_int(a): return b, a return arg def _pb_args_coeffs(args, default_ctx = None): args = _get_args_ast_list(args) if len(args) == 0: return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)() args = [_reorder_pb_arg(arg) for arg in args] args, coeffs = zip(*args) if z3_debug(): _z3_assert(len(args) > 0, "Non empty list of arguments expected") ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression") args = _coerce_expr_list(args, ctx) _args, sz = _to_ast_array(args) _coeffs = (ctypes.c_int * len(coeffs))() for i in range(len(coeffs)): _z3_check_cint_overflow(coeffs[i], "coefficient") _coeffs[i] = coeffs[i] return ctx, sz, _args, _coeffs def PbLe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbLe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs = _pb_args_coeffs(args) return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbGe(args, k): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbGe(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx) def PbEq(args, k, ctx = None): """Create a Pseudo-Boolean inequality k constraint. >>> a, b, c = Bools('a b c') >>> f = PbEq(((a,1),(b,3),(c,2)), 3) """ _z3_check_cint_overflow(k, "k") ctx, sz, _args, _coeffs = _pb_args_coeffs(args) return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx) def solve(*args, **keywords): """Solve the constraints `*args`. This is a simple function for creating demonstrations. It creates a solver, configure it using the options in `keywords`, adds the constraints in `args`, and invokes check. >>> a = Int('a') >>> solve(a > 0, a < 2) [a = 1] """ s = Solver() s.set(**keywords) s.add(*args) if keywords.get('show', False): print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: print(s.model()) def solve_using(s, *args, **keywords): """Solve the constraints `*args` using solver `s`. This is a simple function for creating demonstrations. It is similar to `solve`, but it uses the given solver `s`. It configures solver `s` using the options in `keywords`, adds the constraints in `args`, and invokes check. """ if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if keywords.get('show', False): print("Problem:") print(s) r = s.check() if r == unsat: print("no solution") elif r == unknown: print("failed to solve") try: print(s.model()) except Z3Exception: return else: if keywords.get('show', False): print("Solution:") print(s.model()) def prove(claim, **keywords): """Try to prove the given claim. This is a simple function for creating demonstrations. It tries to prove `claim` by showing the negation is unsatisfiable. >>> p, q = Bools('p q') >>> prove(Not(And(p, q)) == Or(Not(p), Not(q))) proved """ if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if keywords.get('show', False): print(s) r = s.check() if r == unsat: print("proved") elif r == unknown: print("failed to prove") print(s.model()) else: print("counterexample") print(s.model()) def _solve_html(*args, **keywords): """Version of function `solve` used in RiSE4Fun.""" s = Solver() s.set(**keywords) s.add(*args) if keywords.get('show', False): print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if keywords.get('show', False): print("<b>Solution:</b>") print(s.model()) def _solve_using_html(s, *args, **keywords): """Version of function `solve_using` used in RiSE4Fun.""" if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if keywords.get('show', False): print("<b>Problem:</b>") print(s) r = s.check() if r == unsat: print("<b>no solution</b>") elif r == unknown: print("<b>failed to solve</b>") try: print(s.model()) except Z3Exception: return else: if keywords.get('show', False): print("<b>Solution:</b>") print(s.model()) def _prove_html(claim, **keywords): """Version of function `prove` used in RiSE4Fun.""" if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if keywords.get('show', False): print(s) r = s.check() if r == unsat: print("<b>proved</b>") elif r == unknown: print("<b>failed to prove</b>") print(s.model()) else: print("<b>counterexample</b>") print(s.model()) def _dict2sarray(sorts, ctx): sz = len(sorts) _names = (Symbol * sz)() _sorts = (Sort * sz) () i = 0 for k in sorts: v = sorts[k] if z3_debug(): _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_sort(v), "Z3 sort expected") _names[i] = to_symbol(k, ctx) _sorts[i] = v.ast i = i + 1 return sz, _names, _sorts def _dict2darray(decls, ctx): sz = len(decls) _names = (Symbol * sz)() _decls = (FuncDecl * sz) () i = 0 for k in decls: v = decls[k] if z3_debug(): _z3_assert(isinstance(k, str), "String expected") _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected") _names[i] = to_symbol(k, ctx) if is_const(v): _decls[i] = v.decl().ast else: _decls[i] = v.ast i = i + 1 return sz, _names, _decls def parse_smt2_string(s, sorts={}, decls={}, ctx=None): """Parse a string in SMT 2.0 format using the given sorts and decls. The arguments sorts and decls are Python dictionaries used to initialize the symbol table used for the SMT 2.0 parser. >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))') [x > 0, x < 10] >>> x, y = Ints('x y') >>> f = Function('f', IntSort(), IntSort()) >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f}) [x + f(y) > 0] >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() }) [a > 0] """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) def parse_smt2_file(f, sorts={}, decls={}, ctx=None): """Parse a file in SMT 2.0 format using the given sorts and decls. This function is similar to parse_smt2_string(). """ ctx = _get_ctx(ctx) ssz, snames, ssorts = _dict2sarray(sorts, ctx) dsz, dnames, ddecls = _dict2darray(decls, ctx) return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) ######################################### # # Floating-Point Arithmetic # ######################################### # Global default rounding mode _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO _dflt_fpsort_ebits = 11 _dflt_fpsort_sbits = 53 def get_default_rounding_mode(ctx=None): """Retrieves the global default rounding mode.""" global _dflt_rounding_mode if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO: return RTZ(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE: return RTN(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE: return RTP(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: return RNE(ctx) elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: return RNA(ctx) def set_default_rounding_mode(rm, ctx=None): global _dflt_rounding_mode if is_fprm_value(rm): _dflt_rounding_mode = rm.decl().kind() else: _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY, "illegal rounding mode") _dflt_rounding_mode = rm def get_default_fp_sort(ctx=None): return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx) def set_default_fp_sort(ebits, sbits, ctx=None): global _dflt_fpsort_ebits global _dflt_fpsort_sbits _dflt_fpsort_ebits = ebits _dflt_fpsort_sbits = sbits def _dflt_rm(ctx=None): return get_default_rounding_mode(ctx) def _dflt_fps(ctx=None): return get_default_fp_sort(ctx) def _coerce_fp_expr_list(alist, ctx): first_fp_sort = None for a in alist: if is_fp(a): if first_fp_sort is None: first_fp_sort = a.sort() elif first_fp_sort == a.sort(): pass # OK, same as before else: # we saw at least 2 different float sorts; something will # throw a sort mismatch later, for now assume None. first_fp_sort = None break r = [] for i in range(len(alist)): a = alist[i] if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool): r.append(FPVal(a, None, first_fp_sort, ctx)) else: r.append(a) return _coerce_expr_list(r, ctx) ### FP Sorts class FPSortRef(SortRef): """Floating-point sort.""" def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast)) def sbits(self): """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast)) def cast(self, val): """Try to cast `val` as a floating-point expression. >>> b = FPSort(8, 24) >>> b.cast(1.0) 1 >>> b.cast(1.0).sexpr() '(fp #b0 #x7f #b00000000000000000000000)' """ if is_expr(val): if z3_debug(): _z3_assert(self.ctx == val.ctx, "Context mismatch") return val else: return FPVal(val, None, self, self.ctx) def Float16(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx) def FloatHalf(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx) def Float32(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx) def FloatSingle(ctx=None): """Floating-point 32-bit (single) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) def Float64(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx) def FloatDouble(ctx=None): """Floating-point 64-bit (double) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx) def Float128(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx) def FloatQuadruple(ctx=None): """Floating-point 128-bit (quadruple) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx) class FPRMSortRef(SortRef): """"Floating-point rounding mode sort.""" def is_fp_sort(s): """Return True if `s` is a Z3 floating-point sort. >>> is_fp_sort(FPSort(8, 24)) True >>> is_fp_sort(IntSort()) False """ return isinstance(s, FPSortRef) def is_fprm_sort(s): """Return True if `s` is a Z3 floating-point rounding mode sort. >>> is_fprm_sort(FPSort(8, 24)) False >>> is_fprm_sort(RNE().sort()) True """ return isinstance(s, FPRMSortRef) ### FP Expressions class FPRef(ExprRef): """Floating-point expressions.""" def sort(self): """Return the sort of the floating-point expression `self`. >>> x = FP('1.0', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sort() == FPSort(8, 24) True """ return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def ebits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.ebits() 8 """ return self.sort().ebits(); def sbits(self): """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`. >>> b = FPSort(8, 24) >>> b.sbits() 24 """ return self.sort().sbits(); def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return fpLEQ(self, other, self.ctx) def __lt__(self, other): return fpLT(self, other, self.ctx) def __ge__(self, other): return fpGEQ(self, other, self.ctx) def __gt__(self, other): return fpGT(self, other, self.ctx) def __add__(self, other): """Create the Z3 expression `self + other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x + y x + y >>> (x + y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __radd__(self, other): """Create the Z3 expression `other + self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 + x 1.25*(2**3) + x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpAdd(_dflt_rm(), a, b, self.ctx) def __sub__(self, other): """Create the Z3 expression `self - other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x - y x - y >>> (x - y).sort() FPSort(8, 24) """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __rsub__(self, other): """Create the Z3 expression `other - self`. >>> x = FP('x', FPSort(8, 24)) >>> 10 - x 1.25*(2**3) - x """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpSub(_dflt_rm(), a, b, self.ctx) def __mul__(self, other): """Create the Z3 expression `self * other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> (x * y).sort() FPSort(8, 24) >>> 10 * y 1.25*(2**3) * y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __rmul__(self, other): """Create the Z3 expression `other * self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x * y x * y >>> x * 10 x * 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpMul(_dflt_rm(), a, b, self.ctx) def __pos__(self): """Create the Z3 expression `+self`.""" return self def __neg__(self): """Create the Z3 expression `-self`. >>> x = FP('x', Float32()) >>> -x -x """ return fpNeg(self) def __div__(self, other): """Create the Z3 expression `self / other`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> (x / y).sort() FPSort(8, 24) >>> 10 / y 1.25*(2**3) / y """ [a, b] = _coerce_fp_expr_list([self, other], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __rdiv__(self, other): """Create the Z3 expression `other / self`. >>> x = FP('x', FPSort(8, 24)) >>> y = FP('y', FPSort(8, 24)) >>> x / y x / y >>> x / 10 x / 1.25*(2**3) """ [a, b] = _coerce_fp_expr_list([other, self], self.ctx) return fpDiv(_dflt_rm(), a, b, self.ctx) def __truediv__(self, other): """Create the Z3 expression division `self / other`.""" return self.__div__(other) def __rtruediv__(self, other): """Create the Z3 expression division `other / self`.""" return self.__rdiv__(other) def __mod__(self, other): """Create the Z3 expression mod `self % other`.""" return fpRem(self, other) def __rmod__(self, other): """Create the Z3 expression mod `other % self`.""" return fpRem(other, self) class FPRMRef(ExprRef): """Floating-point rounding mode expressions""" def as_string(self): """Return a Z3 floating point expression as a Python string.""" return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def RoundNearestTiesToEven(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RNE (ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) def RoundNearestTiesToAway(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RNA (ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) def RoundTowardPositive(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RTP(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) def RoundTowardNegative(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RTN(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) def RoundTowardZero(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def RTZ(ctx=None): ctx = _get_ctx(ctx) return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) def is_fprm(a): """Return `True` if `a` is a Z3 floating-point rounding mode expression. >>> rm = RNE() >>> is_fprm(rm) True >>> rm = 1.0 >>> is_fprm(rm) False """ return isinstance(a, FPRMRef) def is_fprm_value(a): """Return `True` if `a` is a Z3 floating-point rounding mode numeral value.""" return is_fprm(a) and _is_numeral(a.ctx, a.ast) ### FP Numerals class FPNumRef(FPRef): """The sign of the numeral. >>> x = FPVal(+1.0, FPSort(8, 24)) >>> x.sign() False >>> x = FPVal(-1.0, FPSort(8, 24)) >>> x.sign() True """ def sign(self): l = (ctypes.c_int)() if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False: raise Z3Exception("error retrieving the sign of a numeral.") return l.value != 0 """The sign of a floating-point numeral as a bit-vector expression. Remark: NaN's are invalid arguments. """ def sign_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The significand of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand() 1.25 """ def significand(self): return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast()) """The significand of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.significand_as_long() 1.25 """ def significand_as_long(self): ptr = (ctypes.c_ulonglong * 1)() if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr): raise Z3Exception("error retrieving the significand of a numeral.") return ptr[0] """The significand of the numeral as a bit-vector expression. Remark: NaN are invalid arguments. """ def significand_as_bv(self): return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx) """The exponent of the numeral. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent() 1 """ def exponent(self, biased=True): return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased) """The exponent of the numeral as a long. >>> x = FPVal(2.5, FPSort(8, 24)) >>> x.exponent_as_long() 1 """ def exponent_as_long(self, biased=True): ptr = (ctypes.c_longlong * 1)() if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased): raise Z3Exception("error retrieving the exponent of a numeral.") return ptr[0] """The exponent of the numeral as a bit-vector expression. Remark: NaNs are invalid arguments. """ def exponent_as_bv(self, biased=True): return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx) """Indicates whether the numeral is a NaN.""" def isNaN(self): return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +oo or -oo.""" def isInf(self): return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is +zero or -zero.""" def isZero(self): return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is normal.""" def isNormal(self): return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is subnormal.""" def isSubnormal(self): return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is positive.""" def isPositive(self): return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast()) """Indicates whether the numeral is negative.""" def isNegative(self): return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast()) """ The string representation of the numeral. >>> x = FPVal(20, FPSort(8, 24)) >>> x.as_string() 1.25*(2**4) """ def as_string(self): s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast()) return ("FPVal(%s, %s)" % (s, self.sort())) def is_fp(a): """Return `True` if `a` is a Z3 floating-point expression. >>> b = FP('b', FPSort(8, 24)) >>> is_fp(b) True >>> is_fp(b + 1.0) True >>> is_fp(Int('x')) False """ return isinstance(a, FPRef) def is_fp_value(a): """Return `True` if `a` is a Z3 floating-point numeral value. >>> b = FP('b', FPSort(8, 24)) >>> is_fp_value(b) False >>> b = FPVal(1.0, FPSort(8, 24)) >>> b 1 >>> is_fp_value(b) True """ return is_fp(a) and _is_numeral(a.ctx, a.ast) def FPSort(ebits, sbits, ctx=None): """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used. >>> Single = FPSort(8, 24) >>> Double = FPSort(11, 53) >>> Single FPSort(8, 24) >>> x = Const('x', Single) >>> eq(x, FP('x', FPSort(8, 24))) True """ ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx) def _to_float_str(val, exp=0): if isinstance(val, float): if math.isnan(val): res = "NaN" elif val == 0.0: sone = math.copysign(1.0, val) if sone < 0.0: return "-0.0" else: return "+0.0" elif val == float("+inf"): res = "+oo" elif val == float("-inf"): res = "-oo" else: v = val.as_integer_ratio() num = v[0] den = v[1] rvs = str(num) + '/' + str(den) res = rvs + 'p' + _to_int_str(exp) elif isinstance(val, bool): if val: res = "1.0" else: res = "0.0" elif _is_int(val): res = str(val) elif isinstance(val, str): inx = val.find('*(2**') if inx == -1: res = val elif val[-1] == ')': res = val[0:inx] exp = str(int(val[inx+5:-1]) + int(exp)) else: _z3_assert(False, "String does not have floating-point numeral form.") elif z3_debug(): _z3_assert(False, "Python value cannot be used to create floating-point numerals.") if exp == 0: return res else: return res + 'p' + exp def fpNaN(s): """Create a Z3 floating-point NaN term. >>> s = FPSort(8, 24) >>> set_fpa_pretty(True) >>> fpNaN(s) NaN >>> pb = get_fpa_pretty() >>> set_fpa_pretty(False) >>> fpNaN(s) fpNaN(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx) def fpPlusInfinity(s): """Create a Z3 floating-point +oo term. >>> s = FPSort(8, 24) >>> pb = get_fpa_pretty() >>> set_fpa_pretty(True) >>> fpPlusInfinity(s) +oo >>> set_fpa_pretty(False) >>> fpPlusInfinity(s) fpPlusInfinity(FPSort(8, 24)) >>> set_fpa_pretty(pb) """ _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusInfinity(s): """Create a Z3 floating-point -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx) def fpInfinity(s, negative): """Create a Z3 floating-point +oo or -oo term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx) def fpPlusZero(s): """Create a Z3 floating-point +0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx) def fpMinusZero(s): """Create a Z3 floating-point -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx) def fpZero(s, negative): """Create a Z3 floating-point +0.0 or -0.0 term.""" _z3_assert(isinstance(s, FPSortRef), "sort mismatch") _z3_assert(isinstance(negative, bool), "expected Boolean flag") return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx) def FPVal(sig, exp=None, fps=None, ctx=None): """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used. >>> v = FPVal(20.0, FPSort(8, 24)) >>> v 1.25*(2**4) >>> print("0x%.8x" % v.exponent_as_long(False)) 0x00000004 >>> v = FPVal(2.25, FPSort(8, 24)) >>> v 1.125*(2**1) >>> v = FPVal(-2.25, FPSort(8, 24)) >>> v -1.125*(2**1) >>> FPVal(-0.0, FPSort(8, 24)) -0.0 >>> FPVal(0.0, FPSort(8, 24)) +0.0 >>> FPVal(+0.0, FPSort(8, 24)) +0.0 """ ctx = _get_ctx(ctx) if is_fp_sort(exp): fps = exp exp = None elif fps is None: fps = _dflt_fps(ctx) _z3_assert(is_fp_sort(fps), "sort mismatch") if exp is None: exp = 0 val = _to_float_str(sig) if val == "NaN" or val == "nan": return fpNaN(fps) elif val == "-0.0": return fpMinusZero(fps) elif val == "0.0" or val == "+0.0": return fpPlusZero(fps) elif val == "+oo" or val == "+inf" or val == "+Inf": return fpPlusInfinity(fps) elif val == "-oo" or val == "-inf" or val == "-Inf": return fpMinusInfinity(fps) else: return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx) def FP(name, fpsort, ctx=None): """Return a floating-point constant named `name`. `fpsort` is the floating-point sort. If `ctx=None`, then the global context is used. >>> x = FP('x', FPSort(8, 24)) >>> is_fp(x) True >>> x.ebits() 8 >>> x.sort() FPSort(8, 24) >>> word = FPSort(8, 24) >>> x2 = FP('x', word) >>> eq(x, x2) True """ if isinstance(fpsort, FPSortRef) and ctx is None: ctx = fpsort.ctx else: ctx = _get_ctx(ctx) return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx) def FPs(names, fpsort, ctx=None): """Return an array of floating-point constants. >>> x, y, z = FPs('x y z', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sbits() 24 >>> x.ebits() 8 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z) fpMul(RNE(), fpAdd(RNE(), x, y), z) """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [FP(name, fpsort, ctx) for name in names] def fpAbs(a, ctx=None): """Create a Z3 floating-point absolute value expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FPVal(1.0, s) >>> fpAbs(x) fpAbs(1) >>> y = FPVal(-20.0, s) >>> y -1.25*(2**4) >>> fpAbs(y) fpAbs(-1.25*(2**4)) >>> fpAbs(-1.25*(2**4)) fpAbs(-1.25*(2**4)) >>> fpAbs(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx) def fpNeg(a, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> fpNeg(x) -x >>> fpNeg(x).sort() FPSort(8, 24) """ ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx) def _mk_fp_unary(f, rm, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx) def _mk_fp_unary_pred(f, a, ctx): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) if z3_debug(): _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast()), ctx) def _mk_fp_bin(f, rm, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_norm(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_bin_pred(f, a, b, ctx): ctx = _get_ctx(ctx) [a, b] = _coerce_fp_expr_list([a, b], ctx) if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx) def _mk_fp_tern(f, rm, a, b, c, ctx): ctx = _get_ctx(ctx) [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx) if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "Second, third or fourth argument must be a Z3 floating-point expression") return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx) def fpAdd(rm, a, b, ctx=None): """Create a Z3 floating-point addition expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpAdd(rm, x, y) fpAdd(RNE(), x, y) >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ x + y >>> fpAdd(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx) def fpSub(rm, a, b, ctx=None): """Create a Z3 floating-point subtraction expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpSub(rm, x, y) fpSub(RNE(), x, y) >>> fpSub(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx) def fpMul(rm, a, b, ctx=None): """Create a Z3 floating-point multiplication expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMul(rm, x, y) fpMul(RNE(), x, y) >>> fpMul(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx) def fpDiv(rm, a, b, ctx=None): """Create a Z3 floating-point division expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpDiv(rm, x, y) fpDiv(RNE(), x, y) >>> fpDiv(rm, x, y).sort() FPSort(8, 24) """ return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx) def fpRem(a, b, ctx=None): """Create a Z3 floating-point remainder expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpRem(x, y) fpRem(x, y) >>> fpRem(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx) def fpMin(a, b, ctx=None): """Create a Z3 floating-point minimum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMin(x, y) fpMin(x, y) >>> fpMin(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx) def fpMax(a, b, ctx=None): """Create a Z3 floating-point maximum expression. >>> s = FPSort(8, 24) >>> rm = RNE() >>> x = FP('x', s) >>> y = FP('y', s) >>> fpMax(x, y) fpMax(x, y) >>> fpMax(x, y).sort() FPSort(8, 24) """ return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx) def fpFMA(rm, a, b, c, ctx=None): """Create a Z3 floating-point fused multiply-add expression. """ return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx) def fpSqrt(rm, a, ctx=None): """Create a Z3 floating-point square root expression. """ return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx) def fpRoundToIntegral(rm, a, ctx=None): """Create a Z3 floating-point roundToIntegral expression. """ return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx) def fpIsNaN(a, ctx=None): """Create a Z3 floating-point isNaN expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> y = FP('y', s) >>> fpIsNaN(x) fpIsNaN(x) """ return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx) def fpIsInf(a, ctx=None): """Create a Z3 floating-point isInfinite expression. >>> s = FPSort(8, 24) >>> x = FP('x', s) >>> fpIsInf(x) fpIsInf(x) """ return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx) def fpIsZero(a, ctx=None): """Create a Z3 floating-point isZero expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx) def fpIsNormal(a, ctx=None): """Create a Z3 floating-point isNormal expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx) def fpIsSubnormal(a, ctx=None): """Create a Z3 floating-point isSubnormal expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx) def fpIsNegative(a, ctx=None): """Create a Z3 floating-point isNegative expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx) def fpIsPositive(a, ctx=None): """Create a Z3 floating-point isPositive expression. """ return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx) def _check_fp_args(a, b): if z3_debug(): _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression") def fpLT(a, b, ctx=None): """Create the Z3 floating-point expression `other < self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLT(x, y) x < y >>> (x < y).sexpr() '(fp.lt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx) def fpLEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other <= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpLEQ(x, y) x <= y >>> (x <= y).sexpr() '(fp.leq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx) def fpGT(a, b, ctx=None): """Create the Z3 floating-point expression `other > self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGT(x, y) x > y >>> (x > y).sexpr() '(fp.gt x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx) def fpGEQ(a, b, ctx=None): """Create the Z3 floating-point expression `other >= self`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpGEQ(x, y) x >= y >>> (x >= y).sexpr() '(fp.geq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx) def fpEQ(a, b, ctx=None): """Create the Z3 floating-point expression `fpEQ(other, self)`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpEQ(x, y) fpEQ(x, y) >>> fpEQ(x, y).sexpr() '(fp.eq x y)' """ return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx) def fpNEQ(a, b, ctx=None): """Create the Z3 floating-point expression `Not(fpEQ(other, self))`. >>> x, y = FPs('x y', FPSort(8, 24)) >>> fpNEQ(x, y) Not(fpEQ(x, y)) >>> (x != y).sexpr() '(distinct x y)' """ return Not(fpEQ(a, b, ctx)) def fpFP(sgn, exp, sig, ctx=None): """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp. >>> s = FPSort(8, 24) >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23)) >>> print(x) fpFP(1, 127, 4194304) >>> xv = FPVal(-1.5, s) >>> print(xv) -1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() sat >>> xv = FPVal(+1.5, s) >>> print(xv) 1.5 >>> slvr = Solver() >>> slvr.add(fpEQ(x, xv)) >>> slvr.check() unsat """ _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch") _z3_assert(sgn.sort().size() == 1, "sort mismatch") ctx = _get_ctx(ctx) _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch") return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx) def fpToFP(a1, a2=None, a3=None, ctx=None): """Create a Z3 floating-point conversion expression from other term sorts to floating-point. From a bit-vector term in IEEE 754-2008 format: >>> x = FPVal(1.0, Float32()) >>> x_bv = fpToIEEEBV(x) >>> simplify(fpToFP(x_bv, Float32())) 1 From a floating-point term with different precision: >>> x = FPVal(1.0, Float32()) >>> x_db = fpToFP(RNE(), x, Float64()) >>> x_db.sort() FPSort(11, 53) From a real term: >>> x_r = RealVal(1.5) >>> simplify(fpToFP(RNE(), x_r, Float32())) 1.5 From a signed bit-vector term: >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> simplify(fpToFP(RNE(), x_signed, Float32())) -1.25*(2**2) """ ctx = _get_ctx(ctx) if is_bv(a1) and is_fp_sort(a2): return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx) elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3): return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx) else: raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.") def fpBVToFP(v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a bit-vector term to a floating-point term. >>> x_bv = BitVecVal(0x3F800000, 32) >>> x_fp = fpBVToFP(x_bv, Float32()) >>> x_fp fpToFP(1065353216) >>> simplify(x_fp) 1 """ _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx) def fpFPToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a floating-point term to a floating-point term of different precision. >>> x_sgl = FPVal(1.0, Float32()) >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64()) >>> x_dbl fpToFP(RNE(), 1) >>> simplify(x_dbl) 1 >>> x_dbl.sort() FPSort(11, 53) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpRealToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a real term to a floating-point term. >>> x_r = RealVal(1.5) >>> x_fp = fpRealToFP(RNE(), x_r, Float32()) >>> x_fp fpToFP(RNE(), 3/2) >>> simplify(x_fp) 1.5 """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpSignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from a signed bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFP(RNE(), 4294967291) >>> simplify(x_fp) -1.25*(2**2) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpUnsignedToFP(rm, v, sort, ctx=None): """Create a Z3 floating-point conversion expression that represents the conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term. >>> x_signed = BitVecVal(-5, BitVecSort(32)) >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32()) >>> x_fp fpToFPUnsigned(RNE(), 4294967291) >>> simplify(x_fp) 1*(2**32) """ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.") _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx) def fpToFPUnsigned(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression.""" if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression") _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort") ctx = _get_ctx(ctx) return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx) def fpToSBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToSBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToUBV(rm, x, s, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToUBV(RTZ(), x, BitVecSort(32)) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx) def fpToReal(x, ctx=None): """Create a Z3 floating-point conversion expression, from floating-point expression to real. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToReal(x) >>> print(is_fp(x)) True >>> print(is_real(y)) True >>> print(is_fp(y)) False >>> print(is_real(x)) False """ if z3_debug(): _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx) def fpToIEEEBV(x, ctx=None): """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format. The size of the resulting bit-vector is automatically determined. Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion knows only one NaN and it will always produce the same bit-vector representation of that NaN. >>> x = FP('x', FPSort(8, 24)) >>> y = fpToIEEEBV(x) >>> print(is_fp(x)) True >>> print(is_bv(y)) True >>> print(is_fp(y)) False >>> print(is_bv(x)) False """ if z3_debug(): _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") ctx = _get_ctx(ctx) return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx) ######################################### # # Strings, Sequences and Regular expressions # ######################################### class SeqSortRef(SortRef): """Sequence sort.""" def is_string(self): """Determine if sort is a string >>> s = StringSort() >>> s.is_string() True >>> s = SeqSort(IntSort()) >>> s.is_string() False """ return Z3_is_string_sort(self.ctx_ref(), self.ast) def basis(self): return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx) def StringSort(ctx=None): """Create a string sort >>> s = StringSort() >>> print(s) String """ ctx = _get_ctx(ctx) return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx) def SeqSort(s): """Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True """ return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx) class SeqRef(ExprRef): """Sequence expression.""" def sort(self): return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) def __add__(self, other): return Concat(self, other) def __radd__(self, other): return Concat(other, self) def __getitem__(self, i): if _is_int(i): i = IntVal(i, self.ctx) return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def at(self, i): if _is_int(i): i = IntVal(i, self.ctx) return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx) def is_string(self): return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast())) def is_string_value(self): return Z3_is_string(self.ctx_ref(), self.as_ast()) def as_string(self): """Return a string representation of sequence expression.""" if self.is_string_value(): string_length = ctypes.c_uint() chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length)) return string_at(chars, size=string_length.value).decode('latin-1') return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def __le__(self, other): return SeqRef(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __lt__(self, other): return SeqRef(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __ge__(self, other): return SeqRef(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def __gt__(self, other): return SeqRef(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def _coerce_seq(s, ctx=None): if isinstance(s, str): ctx = _get_ctx(ctx) s = StringVal(s, ctx) if not is_expr(s): raise Z3Exception("Non-expression passed as a sequence") if not is_seq(s): raise Z3Exception("Non-sequence passed as a sequence") return s def _get_ctx2(a, b, ctx=None): if is_expr(a): return a.ctx if is_expr(b): return b.ctx if ctx is None: ctx = main_ctx() return ctx def is_seq(a): """Return `True` if `a` is a Z3 sequence expression. >>> print (is_seq(Unit(IntVal(0)))) True >>> print (is_seq(StringVal("abc"))) True """ return isinstance(a, SeqRef) def is_string(a): """Return `True` if `a` is a Z3 string expression. >>> print (is_string(StringVal("ab"))) True """ return isinstance(a, SeqRef) and a.is_string() def is_string_value(a): """return 'True' if 'a' is a Z3 string constant expression. >>> print (is_string_value(StringVal("a"))) True >>> print (is_string_value(StringVal("a") + StringVal("b"))) False """ return isinstance(a, SeqRef) and a.is_string_value() def StringVal(s, ctx=None): """create a string expression""" ctx = _get_ctx(ctx) return SeqRef(Z3_mk_lstring(ctx.ref(), len(s), s), ctx) def String(name, ctx=None): """Return a string constant named `name`. If `ctx=None`, then the global context is used. >>> x = String('x') """ ctx = _get_ctx(ctx) return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx) def Strings(names, ctx=None): """Return string constants""" ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [String(name, ctx) for name in names] def SubString(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def SubSeq(s, offset, length): """Extract substring or subsequence starting at offset""" return Extract(s, offset, length) def Strings(names, ctx=None): """Return a tuple of String constants. """ ctx = _get_ctx(ctx) if isinstance(names, str): names = names.split(" ") return [String(name, ctx) for name in names] def Empty(s): """Create the empty sequence of the given sort >>> e = Empty(StringSort()) >>> e2 = StringVal("") >>> print(e.eq(e2)) True >>> e3 = Empty(SeqSort(IntSort())) >>> print(e3) Empty(Seq(Int)) >>> e4 = Empty(ReSort(SeqSort(IntSort()))) >>> print(e4) Empty(ReSort(Seq(Int))) """ if isinstance(s, SeqSortRef): return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx) if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty") def Full(s): """Create the regular expression that accepts the universal language >>> e = Full(ReSort(SeqSort(IntSort()))) >>> print(e) Full(ReSort(Seq(Int))) >>> e1 = Full(ReSort(StringSort())) >>> print(e1) Full(ReSort(String)) """ if isinstance(s, ReSortRef): return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx) raise Z3Exception("Non-sequence, non-regular expression sort passed to Full") def Unit(a): """Create a singleton sequence""" return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx) def PrefixOf(a, b): """Check if 'a' is a prefix of 'b' >>> s1 = PrefixOf("ab", "abc") >>> simplify(s1) True >>> s2 = PrefixOf("bc", "abc") >>> simplify(s2) False """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def SuffixOf(a, b): """Check if 'a' is a suffix of 'b' >>> s1 = SuffixOf("ab", "abc") >>> simplify(s1) False >>> s2 = SuffixOf("bc", "abc") >>> simplify(s2) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Contains(a, b): """Check if 'a' contains 'b' >>> s1 = Contains("abc", "ab") >>> simplify(s1) True >>> s2 = Contains("abc", "bc") >>> simplify(s2) True >>> x, y, z = Strings('x y z') >>> s3 = Contains(Concat(x,y,z), y) >>> simplify(s3) True """ ctx = _get_ctx2(a, b) a = _coerce_seq(a, ctx) b = _coerce_seq(b, ctx) return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) def Replace(s, src, dst): """Replace the first occurrence of 'src' by 'dst' in 's' >>> r = Replace("aaa", "a", "b") >>> simplify(r) "baa" """ ctx = _get_ctx2(dst, s) if ctx is None and is_expr(src): ctx = src.ctx src = _coerce_seq(src, ctx) dst = _coerce_seq(dst, ctx) s = _coerce_seq(s, ctx) return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx) def IndexOf(s, substr): return IndexOf(s, substr, IntVal(0)) def IndexOf(s, substr, offset): """Retrieve the index of substring within a string starting at a specified offset. >>> simplify(IndexOf("abcabc", "bc", 0)) 1 >>> simplify(IndexOf("abcabc", "bc", 2)) 4 """ ctx = None if is_expr(offset): ctx = offset.ctx ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) if _is_int(offset): offset = IntVal(offset, ctx) return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx) def LastIndexOf(s, substr): """Retrieve the last index of substring within a string""" ctx = None ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx) def Length(s): """Obtain the length of a sequence 's' >>> l = Length(StringVal("abc")) >>> simplify(l) 3 """ s = _coerce_seq(s) return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx) def StrToInt(s): """Convert string expression to integer >>> a = StrToInt("1") >>> simplify(1 == a) True >>> b = StrToInt("2") >>> simplify(1 == b) False >>> c = StrToInt(IntToStr(2)) >>> simplify(1 == c) False """ s = _coerce_seq(s) return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx) def IntToStr(s): """Convert integer expression to string""" if not is_expr(s): s = _py2expr(s) return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx) def Re(s, ctx=None): """The regular expression that accepts sequence 's' >>> s1 = Re("ab") >>> s2 = Re(StringVal("ab")) >>> s3 = Re(Unit(BoolVal(True))) """ s = _coerce_seq(s, ctx) return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx) ## Regular expressions class ReSortRef(SortRef): """Regular expression sort.""" def basis(self): return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx) def ReSort(s): if is_ast(s): return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx) if s is None or isinstance(s, Context): ctx = _get_ctx(s) return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx) raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument") class ReRef(ExprRef): """Regular expressions.""" def __add__(self, other): return Union(self, other) def is_re(s): return isinstance(s, ReRef) def InRe(s, re): """Create regular expression membership test >>> re = Union(Re("a"),Re("b")) >>> print (simplify(InRe("a", re))) True >>> print (simplify(InRe("b", re))) True >>> print (simplify(InRe("c", re))) False """ s = _coerce_seq(s, re.ctx) return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx) def Union(*args): """Create union of regular expressions. >>> re = Union(Re("a"), Re("b"), Re("c")) >>> print (simplify(InRe("d", re))) False """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx) def Intersect(*args): """Create intersection of regular expressions. >>> re = Intersect(Re("a"), Re("b"), Re("c")) """ args = _get_args(args) sz = len(args) if z3_debug(): _z3_assert(sz > 0, "At least one argument expected.") _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.") if sz == 1: return args[0] ctx = args[0].ctx v = (Ast * sz)() for i in range(sz): v[i] = args[i].as_ast() return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx) def Plus(re): """Create the regular expression accepting one or more repetitions of argument. >>> re = Plus(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx) def Option(re): """Create the regular expression that optionally accepts the argument. >>> re = Option(Re("a")) >>> print(simplify(InRe("a", re))) True >>> print(simplify(InRe("", re))) True >>> print(simplify(InRe("aa", re))) False """ return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx) def Complement(re): """Create the complement regular expression.""" return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx) def Star(re): """Create the regular expression accepting zero or more repetitions of argument. >>> re = Star(Re("a")) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("ab", re))) False >>> print(simplify(InRe("", re))) True """ return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx) def Loop(re, lo, hi=0): """Create the regular expression accepting between a lower and upper bound repetitions >>> re = Loop(Re("a"), 1, 3) >>> print(simplify(InRe("aa", re))) True >>> print(simplify(InRe("aaaa", re))) False >>> print(simplify(InRe("", re))) False """ return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx) def Range(lo, hi, ctx = None): """Create the range regular expression over two sequences of length 1 >>> range = Range("a","z") >>> print(simplify(InRe("b", range))) True >>> print(simplify(InRe("bb", range))) False """ lo = _coerce_seq(lo, ctx) hi = _coerce_seq(hi, ctx) return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx) # Special Relations def PartialOrder(a, index): return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx); def LinearOrder(a, index): return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx); def TreeOrder(a, index): return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx); def PiecewiseLinearOrder(a, index): return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx); def TransitiveClosure(f): """Given a binary relation R, such that the two arguments have the same sort create the transitive closure relation R+. The transitive closure R+ is a new relation. """ return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3.py
z3.py
import sys, io, z3 from .z3consts import * from .z3core import * from ctypes import * def _z3_assert(cond, msg): if not cond: raise Z3Exception(msg) ############################## # # Configuration # ############################## # Z3 operator names to Z3Py _z3_op_to_str = { Z3_OP_TRUE : 'True', Z3_OP_FALSE : 'False', Z3_OP_EQ : '==', Z3_OP_DISTINCT : 'Distinct', Z3_OP_ITE : 'If', Z3_OP_AND : 'And', Z3_OP_OR : 'Or', Z3_OP_IFF : '==', Z3_OP_XOR : 'Xor', Z3_OP_NOT : 'Not', Z3_OP_IMPLIES : 'Implies', Z3_OP_IDIV : '/', Z3_OP_MOD : '%', Z3_OP_TO_REAL : 'ToReal', Z3_OP_TO_INT : 'ToInt', Z3_OP_POWER : '**', Z3_OP_IS_INT : 'IsInt', Z3_OP_BADD : '+', Z3_OP_BSUB : '-', Z3_OP_BMUL : '*', Z3_OP_BOR : '|', Z3_OP_BAND : '&', Z3_OP_BNOT : '~', Z3_OP_BXOR : '^', Z3_OP_BNEG : '-', Z3_OP_BUDIV : 'UDiv', Z3_OP_BSDIV : '/', Z3_OP_BSMOD : '%', Z3_OP_BSREM : 'SRem', Z3_OP_BUREM : 'URem', Z3_OP_EXT_ROTATE_LEFT : 'RotateLeft', Z3_OP_EXT_ROTATE_RIGHT : 'RotateRight', Z3_OP_SLEQ : '<=', Z3_OP_SLT : '<', Z3_OP_SGEQ : '>=', Z3_OP_SGT : '>', Z3_OP_ULEQ : 'ULE', Z3_OP_ULT : 'ULT', Z3_OP_UGEQ : 'UGE', Z3_OP_UGT : 'UGT', Z3_OP_SIGN_EXT : 'SignExt', Z3_OP_ZERO_EXT : 'ZeroExt', Z3_OP_REPEAT : 'RepeatBitVec', Z3_OP_BASHR : '>>', Z3_OP_BSHL : '<<', Z3_OP_BLSHR : 'LShR', Z3_OP_CONCAT : 'Concat', Z3_OP_EXTRACT : 'Extract', Z3_OP_BV2INT : 'BV2Int', Z3_OP_ARRAY_MAP : 'Map', Z3_OP_SELECT : 'Select', Z3_OP_STORE : 'Store', Z3_OP_CONST_ARRAY : 'K', Z3_OP_ARRAY_EXT : 'Ext', Z3_OP_PB_AT_MOST : 'AtMost', Z3_OP_PB_LE : 'PbLe', Z3_OP_PB_GE : 'PbGe', Z3_OP_PB_EQ : 'PbEq', Z3_OP_SEQ_CONCAT : 'Concat', Z3_OP_SEQ_PREFIX : 'PrefixOf', Z3_OP_SEQ_SUFFIX : 'SuffixOf', Z3_OP_SEQ_UNIT : 'Unit', Z3_OP_SEQ_CONTAINS : 'Contains' , Z3_OP_SEQ_REPLACE : 'Replace', Z3_OP_SEQ_AT : 'At', Z3_OP_SEQ_NTH : 'Nth', Z3_OP_SEQ_INDEX : 'IndexOf', Z3_OP_SEQ_LAST_INDEX : 'LastIndexOf', Z3_OP_SEQ_LENGTH : 'Length', Z3_OP_STR_TO_INT : 'StrToInt', Z3_OP_INT_TO_STR : 'IntToStr', Z3_OP_SEQ_IN_RE : 'InRe', Z3_OP_SEQ_TO_RE : 'Re', Z3_OP_RE_PLUS : 'Plus', Z3_OP_RE_STAR : 'Star', Z3_OP_RE_OPTION : 'Option', Z3_OP_RE_UNION : 'Union', Z3_OP_RE_RANGE : 'Range', Z3_OP_RE_INTERSECT : 'Intersect', Z3_OP_RE_COMPLEMENT : 'Complement', Z3_OP_FPA_IS_NAN : 'fpIsNaN', Z3_OP_FPA_IS_INF : 'fpIsInf', Z3_OP_FPA_IS_ZERO : 'fpIsZero', Z3_OP_FPA_IS_NORMAL : 'fpIsNormal', Z3_OP_FPA_IS_SUBNORMAL : 'fpIsSubnormal', Z3_OP_FPA_IS_NEGATIVE : 'fpIsNegative', Z3_OP_FPA_IS_POSITIVE : 'fpIsPositive', } # List of infix operators _z3_infix = [ Z3_OP_EQ, Z3_OP_IFF, Z3_OP_ADD, Z3_OP_SUB, Z3_OP_MUL, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_POWER, Z3_OP_LE, Z3_OP_LT, Z3_OP_GE, Z3_OP_GT, Z3_OP_BADD, Z3_OP_BSUB, Z3_OP_BMUL, Z3_OP_BSDIV, Z3_OP_BSMOD, Z3_OP_BOR, Z3_OP_BAND, Z3_OP_BXOR, Z3_OP_BSDIV, Z3_OP_SLEQ, Z3_OP_SLT, Z3_OP_SGEQ, Z3_OP_SGT, Z3_OP_BASHR, Z3_OP_BSHL ] _z3_unary = [ Z3_OP_UMINUS, Z3_OP_BNOT, Z3_OP_BNEG ] # Precedence _z3_precedence = { Z3_OP_POWER : 0, Z3_OP_UMINUS : 1, Z3_OP_BNEG : 1, Z3_OP_BNOT : 1, Z3_OP_MUL : 2, Z3_OP_DIV : 2, Z3_OP_IDIV : 2, Z3_OP_MOD : 2, Z3_OP_BMUL : 2, Z3_OP_BSDIV : 2, Z3_OP_BSMOD : 2, Z3_OP_ADD : 3, Z3_OP_SUB : 3, Z3_OP_BADD : 3, Z3_OP_BSUB : 3, Z3_OP_BASHR : 4, Z3_OP_BSHL : 4, Z3_OP_BAND : 5, Z3_OP_BXOR : 6, Z3_OP_BOR : 7, Z3_OP_LE : 8, Z3_OP_LT : 8, Z3_OP_GE : 8, Z3_OP_GT : 8, Z3_OP_EQ : 8, Z3_OP_SLEQ : 8, Z3_OP_SLT : 8, Z3_OP_SGEQ : 8, Z3_OP_SGT : 8, Z3_OP_IFF : 8, Z3_OP_FPA_NEG : 1, Z3_OP_FPA_MUL : 2, Z3_OP_FPA_DIV : 2, Z3_OP_FPA_REM : 2, Z3_OP_FPA_FMA : 2, Z3_OP_FPA_ADD: 3, Z3_OP_FPA_SUB : 3, Z3_OP_FPA_LE : 8, Z3_OP_FPA_LT : 8, Z3_OP_FPA_GE : 8, Z3_OP_FPA_GT : 8, Z3_OP_FPA_EQ : 8 } # FPA operators _z3_op_to_fpa_normal_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RoundNearestTiesToEven()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RoundNearestTiesToAway()', Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RoundTowardPositive()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RoundTowardNegative()', Z3_OP_FPA_RM_TOWARD_ZERO : 'RoundTowardZero()', Z3_OP_FPA_PLUS_INF : 'fpPlusInfinity', Z3_OP_FPA_MINUS_INF : 'fpMinusInfinity', Z3_OP_FPA_NAN : 'fpNaN', Z3_OP_FPA_PLUS_ZERO : 'fpPZero', Z3_OP_FPA_MINUS_ZERO : 'fpNZero', Z3_OP_FPA_ADD : 'fpAdd', Z3_OP_FPA_SUB : 'fpSub', Z3_OP_FPA_NEG : 'fpNeg', Z3_OP_FPA_MUL : 'fpMul', Z3_OP_FPA_DIV : 'fpDiv', Z3_OP_FPA_REM : 'fpRem', Z3_OP_FPA_ABS : 'fpAbs', Z3_OP_FPA_MIN : 'fpMin', Z3_OP_FPA_MAX : 'fpMax', Z3_OP_FPA_FMA : 'fpFMA', Z3_OP_FPA_SQRT : 'fpSqrt', Z3_OP_FPA_ROUND_TO_INTEGRAL : 'fpRoundToIntegral', Z3_OP_FPA_EQ : 'fpEQ', Z3_OP_FPA_LT : 'fpLT', Z3_OP_FPA_GT : 'fpGT', Z3_OP_FPA_LE : 'fpLEQ', Z3_OP_FPA_GE : 'fpGEQ', Z3_OP_FPA_FP : 'fpFP', Z3_OP_FPA_TO_FP : 'fpToFP', Z3_OP_FPA_TO_FP_UNSIGNED: 'fpToFPUnsigned', Z3_OP_FPA_TO_UBV : 'fpToUBV', Z3_OP_FPA_TO_SBV : 'fpToSBV', Z3_OP_FPA_TO_REAL: 'fpToReal', Z3_OP_FPA_TO_IEEE_BV : 'fpToIEEEBV' } _z3_op_to_fpa_pretty_str = { Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RNE()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RNA()', Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RTP()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RTN()', Z3_OP_FPA_RM_TOWARD_ZERO : 'RTZ()', Z3_OP_FPA_PLUS_INF : '+oo', Z3_OP_FPA_MINUS_INF : '-oo', Z3_OP_FPA_NAN : 'NaN', Z3_OP_FPA_PLUS_ZERO : '+0.0', Z3_OP_FPA_MINUS_ZERO : '-0.0', Z3_OP_FPA_ADD : '+', Z3_OP_FPA_SUB : '-', Z3_OP_FPA_MUL : '*', Z3_OP_FPA_DIV : '/', Z3_OP_FPA_REM : '%', Z3_OP_FPA_NEG : '-', Z3_OP_FPA_EQ : 'fpEQ', Z3_OP_FPA_LT : '<', Z3_OP_FPA_GT : '>', Z3_OP_FPA_LE : '<=', Z3_OP_FPA_GE : '>=' } _z3_fpa_infix = [ Z3_OP_FPA_ADD, Z3_OP_FPA_SUB, Z3_OP_FPA_MUL, Z3_OP_FPA_DIV, Z3_OP_FPA_REM, Z3_OP_FPA_LT, Z3_OP_FPA_GT, Z3_OP_FPA_LE, Z3_OP_FPA_GE ] def _is_assoc(k): return k == Z3_OP_BOR or k == Z3_OP_BXOR or k == Z3_OP_BAND or k == Z3_OP_ADD or k == Z3_OP_BADD or k == Z3_OP_MUL or k == Z3_OP_BMUL def _is_left_assoc(k): return _is_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_html_assoc(k): return k == Z3_OP_AND or k == Z3_OP_OR or k == Z3_OP_IFF or _is_assoc(k) def _is_html_left_assoc(k): return _is_html_assoc(k) or k == Z3_OP_SUB or k == Z3_OP_BSUB def _is_add(k): return k == Z3_OP_ADD or k == Z3_OP_BADD def _is_sub(k): return k == Z3_OP_SUB or k == Z3_OP_BSUB import sys if sys.version < '3': import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x _z3_infix_compact = [ Z3_OP_MUL, Z3_OP_BMUL, Z3_OP_POWER, Z3_OP_DIV, Z3_OP_IDIV, Z3_OP_MOD, Z3_OP_BSDIV, Z3_OP_BSMOD ] _ellipses = '...' _html_ellipses = '&hellip;' # Overwrite some of the operators for HTML _z3_pre_html_op_to_str = { Z3_OP_EQ : '=', Z3_OP_IFF : '=', Z3_OP_NOT : '&not;', Z3_OP_AND : '&and;', Z3_OP_OR : '&or;', Z3_OP_IMPLIES : '&rArr;', Z3_OP_LT : '&lt;', Z3_OP_GT : '&gt;', Z3_OP_LE : '&le;', Z3_OP_GE : '&ge;', Z3_OP_MUL : '&middot;', Z3_OP_SLEQ : '&le;', Z3_OP_SLT : '&lt;', Z3_OP_SGEQ : '&ge;', Z3_OP_SGT : '&gt;', Z3_OP_ULEQ : '&le;<sub>u</sub>', Z3_OP_ULT : '&lt;<sub>u</sub>', Z3_OP_UGEQ : '&ge;<sub>u</sub>', Z3_OP_UGT : '&gt;<sub>u</sub>', Z3_OP_BMUL : '&middot;', Z3_OP_BUDIV : '/<sub>u</sub>', Z3_OP_BUREM : '%<sub>u</sub>', Z3_OP_BASHR : '&gt;&gt;', Z3_OP_BSHL : '&lt;&lt;', Z3_OP_BLSHR : '&gt;&gt;<sub>u</sub>' } # Extra operators that are infix/unary for HTML _z3_html_infix = [ Z3_OP_AND, Z3_OP_OR, Z3_OP_IMPLIES, Z3_OP_ULEQ, Z3_OP_ULT, Z3_OP_UGEQ, Z3_OP_UGT, Z3_OP_BUDIV, Z3_OP_BUREM, Z3_OP_BLSHR ] _z3_html_unary = [ Z3_OP_NOT ] # Extra Precedence for HTML _z3_pre_html_precedence = { Z3_OP_BUDIV : 2, Z3_OP_BUREM : 2, Z3_OP_BLSHR : 4, Z3_OP_ULEQ : 8, Z3_OP_ULT : 8, Z3_OP_UGEQ : 8, Z3_OP_UGT : 8, Z3_OP_ULEQ : 8, Z3_OP_ULT : 8, Z3_OP_UGEQ : 8, Z3_OP_UGT : 8, Z3_OP_NOT : 1, Z3_OP_AND : 10, Z3_OP_OR : 11, Z3_OP_IMPLIES : 12 } ############################## # # End of Configuration # ############################## def _support_pp(a): return isinstance(a, z3.Z3PPObject) or isinstance(a, list) or isinstance(a, tuple) _infix_map = {} _unary_map = {} _infix_compact_map = {} for _k in _z3_infix: _infix_map[_k] = True for _k in _z3_unary: _unary_map[_k] = True for _k in _z3_infix_compact: _infix_compact_map[_k] = True def _is_infix(k): global _infix_map return _infix_map.get(k, False) def _is_infix_compact(k): global _infix_compact_map return _infix_compact_map.get(k, False) def _is_unary(k): global _unary_map return _unary_map.get(k, False) def _op_name(a): if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_op_to_str.get(k, None) if n == None: return f.name() else: return n def _get_precedence(k): global _z3_precedence return _z3_precedence.get(k, 100000) _z3_html_op_to_str = {} for _k in _z3_op_to_str: _v = _z3_op_to_str[_k] _z3_html_op_to_str[_k] = _v for _k in _z3_pre_html_op_to_str: _v = _z3_pre_html_op_to_str[_k] _z3_html_op_to_str[_k] = _v _z3_html_precedence = {} for _k in _z3_precedence: _v = _z3_precedence[_k] _z3_html_precedence[_k] = _v for _k in _z3_pre_html_precedence: _v = _z3_pre_html_precedence[_k] _z3_html_precedence[_k] = _v _html_infix_map = {} _html_unary_map = {} for _k in _z3_infix: _html_infix_map[_k] = True for _k in _z3_html_infix: _html_infix_map[_k] = True for _k in _z3_unary: _html_unary_map[_k] = True for _k in _z3_html_unary: _html_unary_map[_k] = True def _is_html_infix(k): global _html_infix_map return _html_infix_map.get(k, False) def _is_html_unary(k): global _html_unary_map return _html_unary_map.get(k, False) def _html_op_name(a): global _z3_html_op_to_str if isinstance(a, z3.FuncDeclRef): f = a else: f = a.decl() k = f.kind() n = _z3_html_op_to_str.get(k, None) if n == None: sym = Z3_get_decl_name(f.ctx_ref(), f.ast) if Z3_get_symbol_kind(f.ctx_ref(), sym) == Z3_INT_SYMBOL: return "&#950;<sub>%s</sub>" % Z3_get_symbol_int(f.ctx_ref(), sym) else: # Sanitize the string return f.name() else: return n def _get_html_precedence(k): global _z3_html_predence return _z3_html_precedence.get(k, 100000) class FormatObject: def is_compose(self): return False def is_choice(self): return False def is_indent(self): return False def is_string(self): return False def is_linebreak(self): return False def is_nil(self): return True def children(self): return [] def as_tuple(self): return None def space_upto_nl(self): return (0, False) def flat(self): return self class NAryFormatObject(FormatObject): def __init__(self, fs): assert all([isinstance(a, FormatObject) for a in fs]) self.children = fs def children(self): return self.children class ComposeFormatObject(NAryFormatObject): def is_compose(sef): return True def as_tuple(self): return ('compose', [ a.as_tuple() for a in self.children ]) def space_upto_nl(self): r = 0 for child in self.children: s, nl = child.space_upto_nl() r = r + s if nl: return (r, True) return (r, False) def flat(self): return compose([a.flat() for a in self.children ]) class ChoiceFormatObject(NAryFormatObject): def is_choice(sef): return True def as_tuple(self): return ('choice', [ a.as_tuple() for a in self.children ]) def space_upto_nl(self): return self.children[0].space_upto_nl() def flat(self): return self.children[0].flat() class IndentFormatObject(FormatObject): def __init__(self, indent, child): assert isinstance(child, FormatObject) self.indent = indent self.child = child def children(self): return [self.child] def as_tuple(self): return ('indent', self.indent, self.child.as_tuple()) def space_upto_nl(self): return self.child.space_upto_nl() def flat(self): return indent(self.indent, self.child.flat()) def is_indent(self): return True class LineBreakFormatObject(FormatObject): def __init__(self): self.space = ' ' def is_linebreak(self): return True def as_tuple(self): return '<line-break>' def space_upto_nl(self): return (0, True) def flat(self): return to_format(self.space) class StringFormatObject(FormatObject): def __init__(self, string): assert isinstance(string, str) self.string = string def is_string(self): return True def as_tuple(self): return self.string def space_upto_nl(self): return (getattr(self, 'size', len(self.string)), False) def fits(f, space_left): s, nl = f.space_upto_nl() return s <= space_left def to_format(arg, size=None): if isinstance(arg, FormatObject): return arg else: r = StringFormatObject(str(arg)) if size != None: r.size = size return r def compose(*args): if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)): args = args[0] return ComposeFormatObject(args) def indent(i, arg): return IndentFormatObject(i, arg) def group(arg): return ChoiceFormatObject([arg.flat(), arg]) def line_break(): return LineBreakFormatObject() def _len(a): if isinstance(a, StringFormatObject): return getattr(a, 'size', len(a.string)) else: return len(a) def seq(args, sep=',', space=True): nl = line_break() if not space: nl.space = '' r = [] r.append(args[0]) num = len(args) for i in range(num - 1): r.append(to_format(sep)) r.append(nl) r.append(args[i+1]) return compose(r) def seq1(header, args, lp='(', rp=')'): return group(compose(to_format(header), to_format(lp), indent(len(lp) + _len(header), seq(args)), to_format(rp))) def seq2(header, args, i=4, lp='(', rp=')'): if len(args) == 0: return compose(to_format(header), to_format(lp), to_format(rp)) else: return group(compose(indent(len(lp), compose(to_format(lp), to_format(header))), indent(i, compose(seq(args), to_format(rp))))) def seq3(args, lp='(', rp=')'): if len(args) == 0: return compose(to_format(lp), to_format(rp)) else: return group(indent(len(lp), compose(to_format(lp), seq(args), to_format(rp)))) class StopPPException(Exception): def __str__(self): return 'pp-interrupted' class PP: def __init__(self): self.max_lines = 200 self.max_width = 60 self.bounded = False self.max_indent = 40 def pp_string(self, f, indent): if not self.bounded or self.pos <= self.max_width: sz = _len(f) if self.bounded and self.pos + sz > self.max_width: self.out.write(u(_ellipses)) else: self.pos = self.pos + sz self.ribbon_pos = self.ribbon_pos + sz self.out.write(u(f.string)) def pp_compose(self, f, indent): for c in f.children: self.pp(c, indent) def pp_choice(self, f, indent): space_left = self.max_width - self.pos if space_left > 0 and fits(f.children[0], space_left): self.pp(f.children[0], indent) else: self.pp(f.children[1], indent) def pp_line_break(self, f, indent): self.pos = indent self.ribbon_pos = 0 self.line = self.line + 1 if self.line < self.max_lines: self.out.write(u('\n')) for i in range(indent): self.out.write(u(' ')) else: self.out.write(u('\n...')) raise StopPPException() def pp(self, f, indent): if isinstance(f, str): self.pp_string(f, indent) elif f.is_string(): self.pp_string(f, indent) elif f.is_indent(): self.pp(f.child, min(indent + f.indent, self.max_indent)) elif f.is_compose(): self.pp_compose(f, indent) elif f.is_choice(): self.pp_choice(f, indent) elif f.is_linebreak(): self.pp_line_break(f, indent) else: return def __call__(self, out, f): try: self.pos = 0 self.ribbon_pos = 0 self.line = 0 self.out = out self.pp(f, 0) except StopPPException: return class Formatter: def __init__(self): global _ellipses self.max_depth = 20 self.max_args = 128 self.rational_to_decimal = False self.precision = 10 self.ellipses = to_format(_ellipses) self.max_visited = 10000 self.fpa_pretty = True def pp_ellipses(self): return self.ellipses def pp_arrow(self): return ' ->' def pp_unknown(self): return '<unknown>' def pp_name(self, a): return to_format(_op_name(a)) def is_infix(self, a): return _is_infix(a) def is_unary(self, a): return _is_unary(a) def get_precedence(self, a): return _get_precedence(a) def is_infix_compact(self, a): return _is_infix_compact(a) def is_infix_unary(self, a): return self.is_infix(a) or self.is_unary(a) def add_paren(self, a): return compose(to_format('('), indent(1, a), to_format(')')) def pp_sort(self, s): if isinstance(s, z3.ArraySortRef): return seq1('Array', (self.pp_sort(s.domain()), self.pp_sort(s.range()))) elif isinstance(s, z3.BitVecSortRef): return seq1('BitVec', (to_format(s.size()), )) elif isinstance(s, z3.FPSortRef): return seq1('FPSort', (to_format(s.ebits()), to_format(s.sbits()))) elif isinstance(s, z3.ReSortRef): return seq1('ReSort', (self.pp_sort(s.basis()), )) elif isinstance(s, z3.SeqSortRef): if s.is_string(): return to_format("String") return seq1('Seq', (self.pp_sort(s.basis()), )) else: return to_format(s.name()) def pp_const(self, a): k = a.decl().kind() if k == Z3_OP_RE_EMPTY_SET: return self.pp_set("Empty", a) elif k == Z3_OP_SEQ_EMPTY: return self.pp_set("Empty", a) elif k == Z3_OP_RE_FULL_SET: return self.pp_set("Full", a) return self.pp_name(a) def pp_int(self, a): return to_format(a.as_string()) def pp_rational(self, a): if not self.rational_to_decimal: return to_format(a.as_string()) else: return to_format(a.as_decimal(self.precision)) def pp_algebraic(self, a): return to_format(a.as_decimal(self.precision)) def pp_string(self, a): return to_format("\"" + a.as_string() + "\"") def pp_bv(self, a): return to_format(a.as_string()) def pp_fd(self, a): return to_format(a.as_string()) def pp_fprm_value(self, a): _z3_assert(z3.is_fprm_value(a), 'expected FPRMNumRef') if self.fpa_pretty and (a.decl().kind() in _z3_op_to_fpa_pretty_str): return to_format(_z3_op_to_fpa_pretty_str.get(a.decl().kind())) else: return to_format(_z3_op_to_fpa_normal_str.get(a.decl().kind())) def pp_fp_value(self, a): _z3_assert(isinstance(a, z3.FPNumRef), 'type mismatch') if not self.fpa_pretty: r = [] if (a.isNaN()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_NAN])) r.append(to_format('(')) r.append(to_format(a.sort())) r.append(to_format(')')) return compose(r) elif (a.isInf()): if (a.isNegative()): r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_MINUS_INF])) else: r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_PLUS_INF])) r.append(to_format('(')) r.append(to_format(a.sort())) r.append(to_format(')')) return compose(r) elif (a.isZero()): if (a.isNegative()): return to_format('-zero') else: return to_format('+zero') else: _z3_assert(z3.is_fp_value(a), 'expecting FP num ast') r = [] sgn = c_int(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) r.append(to_format('FPVal(')) if sgnb and sgn.value != 0: r.append(to_format('-')) r.append(to_format(sig)) r.append(to_format('*(2**')) r.append(to_format(exp)) r.append(to_format(', ')) r.append(to_format(a.sort())) r.append(to_format('))')) return compose(r) else: if (a.isNaN()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_NAN]) elif (a.isInf()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_INF]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_INF]) elif (a.isZero()): if (a.isNegative()): return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_MINUS_ZERO]) else: return to_format(_z3_op_to_fpa_pretty_str[Z3_OP_FPA_PLUS_ZERO]) else: _z3_assert(z3.is_fp_value(a), 'expecting FP num ast') r = [] sgn = (ctypes.c_int)(0) sgnb = Z3_fpa_get_numeral_sign(a.ctx_ref(), a.ast, byref(sgn)) exp = Z3_fpa_get_numeral_exponent_string(a.ctx_ref(), a.ast, False) sig = Z3_fpa_get_numeral_significand_string(a.ctx_ref(), a.ast) if sgnb and sgn.value != 0: r.append(to_format('-')) r.append(to_format(sig)) if (exp != '0'): r.append(to_format('*(2**')) r.append(to_format(exp)) r.append(to_format(')')) return compose(r) def pp_fp(self, a, d, xs): _z3_assert(isinstance(a, z3.FPRef), "type mismatch") k = a.decl().kind() op = '?' if (self.fpa_pretty and k in _z3_op_to_fpa_pretty_str): op = _z3_op_to_fpa_pretty_str[k] elif k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] elif k in _z3_op_to_str: op = _z3_op_to_str[k] n = a.num_args() if self.fpa_pretty: if self.is_infix(k) and n >= 3: rm = a.arg(0) if z3.is_fprm_value(rm) and z3.get_default_rounding_mode(a.ctx).eq(rm): arg1 = to_format(self.pp_expr(a.arg(1), d+1, xs)) arg2 = to_format(self.pp_expr(a.arg(2), d+1, xs)) r = [] r.append(arg1) r.append(to_format(' ')) r.append(to_format(op)) r.append(to_format(' ')) r.append(arg2) return compose(r) elif k == Z3_OP_FPA_NEG: return compose([to_format('-') , to_format(self.pp_expr(a.arg(0), d+1, xs))]) if k in _z3_op_to_fpa_normal_str: op = _z3_op_to_fpa_normal_str[k] r = [] r.append(to_format(op)) if not z3.is_const(a): r.append(to_format('(')) first = True for c in a.children(): if first: first = False else: r.append(to_format(', ')) r.append(self.pp_expr(c, d+1, xs)) r.append(to_format(')')) return compose(r) else: return to_format(a.as_string()) def pp_prefix(self, a, d, xs): r = [] sz = 0 for child in a.children(): r.append(self.pp_expr(child, d+1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def is_assoc(self, k): return _is_assoc(k) def is_left_assoc(self, k): return _is_left_assoc(k) def infix_args_core(self, a, d, xs, r): sz = len(r) k = a.decl().kind() p = self.get_precedence(k) first = True for child in a.children(): child_pp = self.pp_expr(child, d+1, xs) child_k = None if z3.is_app(child): child_k = child.decl().kind() if k == child_k and (self.is_assoc(k) or (first and self.is_left_assoc(k))): self.infix_args_core(child, d, xs, r) sz = len(r) if sz > self.max_args: return elif self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p > child_p or (_is_add(k) and _is_sub(child_k)) or (_is_sub(k) and first and _is_add(child_k)): r.append(child_pp) else: r.append(self.add_paren(child_pp)) sz = sz + 1 elif z3.is_quantifier(child): r.append(self.add_paren(child_pp)) else: r.append(child_pp) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) return first = False def infix_args(self, a, d, xs): r = [] self.infix_args_core(a, d, xs, r) return r def pp_infix(self, a, d, xs): k = a.decl().kind() if self.is_infix_compact(k): op = self.pp_name(a) return group(seq(self.infix_args(a, d, xs), op, False)) else: op = self.pp_name(a) sz = _len(op) op.string = ' ' + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) def pp_unary(self, a, d, xs): k = a.decl().kind() p = self.get_precedence(k) child = a.children()[0] child_k = None if z3.is_app(child): child_k = child.decl().kind() child_pp = self.pp_expr(child, d+1, xs) if k != child_k and self.is_infix_unary(child_k): child_p = self.get_precedence(child_k) if p <= child_p: child_pp = self.add_paren(child_pp) if z3.is_quantifier(child): child_pp = self.add_paren(child_pp) name = self.pp_name(a) return compose(to_format(name), indent(_len(name), child_pp)) def pp_power_arg(self, arg, d, xs): r = self.pp_expr(arg, d+1, xs) k = None if z3.is_app(arg): k = arg.decl().kind() if self.is_infix_unary(k) or (z3.is_rational_value(arg) and arg.denominator_as_long() != 1): return self.add_paren(r) else: return r def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d+1, xs) arg2_pp = self.pp_power_arg(a.arg(1), d+1, xs) return group(seq((arg1_pp, arg2_pp), '**', False)) def pp_neq(self): return to_format("!=") def pp_distinct(self, a, d, xs): if a.num_args() == 2: op = self.pp_neq() sz = _len(op) op.string = ' ' + op.string op.size = sz + 1 return group(seq(self.infix_args(a, d, xs), op)) else: return self.pp_prefix(a, d, xs) def pp_select(self, a, d, xs): if a.num_args() != 2: return self.pp_prefix(a, d, xs) else: arg1_pp = self.pp_expr(a.arg(0), d+1, xs) arg2_pp = self.pp_expr(a.arg(1), d+1, xs) return compose(arg1_pp, indent(2, compose(to_format('['), arg2_pp, to_format(']')))) def pp_unary_param(self, a, d, xs): p = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d+1, xs) return seq1(self.pp_name(a), [ to_format(p), arg ]) def pp_extract(self, a, d, xs): h = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) l = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) arg = self.pp_expr(a.arg(0), d+1, xs) return seq1(self.pp_name(a), [ to_format(h), to_format(l), arg ]) def pp_loop(self, a, d, xs): l = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) arg = self.pp_expr(a.arg(0), d+1, xs) if Z3_get_decl_num_parameters(a.ctx_ref(), a.decl().ast) > 1: h = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) return seq1("Loop", [ arg, to_format(l), to_format(h) ]) return seq1("Loop", [ arg, to_format(l) ]) def pp_set(self, id, a): return seq1(id, [self.pp_sort(a.sort())]) def pp_pattern(self, a, d, xs): if a.num_args() == 1: return self.pp_expr(a.arg(0), d, xs) else: return seq1('MultiPattern', [ self.pp_expr(arg, d+1, xs) for arg in a.children() ]) def pp_is(self, a, d, xs): f = a.params()[0] return self.pp_fdecl(f, a, d, xs) def pp_map(self, a, d, xs): f = z3.get_map_func(a) return self.pp_fdecl(f, a, d, xs) def pp_fdecl(self, f, a, d, xs): r = [] sz = 0 r.append(to_format(f.name())) for child in a.children(): r.append(self.pp_expr(child, d+1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq1(self.pp_name(a), r) def pp_K(self, a, d, xs): return seq1(self.pp_name(a), [ self.pp_sort(a.domain()), self.pp_expr(a.arg(0), d+1, xs) ]) def pp_atmost(self, a, d, f, xs): k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) return seq1(self.pp_name(a), [seq3([ self.pp_expr(ch, d+1, xs) for ch in a.children()]), to_format(k)]) def pp_pbcmp(self, a, d, f, xs): chs = a.children() rchs = range(len(chs)) k = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) ks = [Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, i+1) for i in rchs] ls = [ seq3([self.pp_expr(chs[i], d+1,xs), to_format(ks[i])]) for i in rchs] return seq1(self.pp_name(a), [seq3(ls), to_format(k)]) def pp_app(self, a, d, xs): if z3.is_int_value(a): return self.pp_int(a) elif z3.is_rational_value(a): return self.pp_rational(a) elif z3.is_algebraic_value(a): return self.pp_algebraic(a) elif z3.is_bv_value(a): return self.pp_bv(a) elif z3.is_finite_domain_value(a): return self.pp_fd(a) elif z3.is_fprm_value(a): return self.pp_fprm_value(a) elif z3.is_fp_value(a): return self.pp_fp_value(a) elif z3.is_fp(a): return self.pp_fp(a, d, xs) elif z3.is_string_value(a): return self.pp_string(a) elif z3.is_const(a): return self.pp_const(a) else: f = a.decl() k = f.kind() if k == Z3_OP_POWER: return self.pp_power(a, d, xs) elif k == Z3_OP_DISTINCT: return self.pp_distinct(a, d, xs) elif k == Z3_OP_SELECT: return self.pp_select(a, d, xs) elif k == Z3_OP_SIGN_EXT or k == Z3_OP_ZERO_EXT or k == Z3_OP_REPEAT: return self.pp_unary_param(a, d, xs) elif k == Z3_OP_EXTRACT: return self.pp_extract(a, d, xs) elif k == Z3_OP_RE_LOOP: return self.pp_loop(a, d, xs) elif k == Z3_OP_DT_IS: return self.pp_is(a, d, xs) elif k == Z3_OP_ARRAY_MAP: return self.pp_map(a, d, xs) elif k == Z3_OP_CONST_ARRAY: return self.pp_K(a, d, xs) elif k == Z3_OP_PB_AT_MOST: return self.pp_atmost(a, d, f, xs) elif k == Z3_OP_PB_LE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_GE: return self.pp_pbcmp(a, d, f, xs) elif k == Z3_OP_PB_EQ: return self.pp_pbcmp(a, d, f, xs) elif z3.is_pattern(a): return self.pp_pattern(a, d, xs) elif self.is_infix(k): return self.pp_infix(a, d, xs) elif self.is_unary(k): return self.pp_unary(a, d, xs) else: return self.pp_prefix(a, d, xs) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: return seq1('Var', (to_format(idx),)) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [ to_format(a.var_name(i)) for i in range(a.num_vars()) ] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d+1, new_xs) if len(ys) == 1: ys_pp = ys[0] else: ys_pp = seq3(ys, '[', ']') if a.is_forall(): header = 'ForAll' elif a.is_exists(): header = 'Exists' else: header = 'Lambda' return seq1(header, (ys_pp, body_pp)) def pp_expr(self, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() if z3.is_app(a): return self.pp_app(a, d, xs) elif z3.is_quantifier(a): return self.pp_quantifier(a, d, xs) elif z3.is_var(a): return self.pp_var(a, d, xs) else: return to_format(self.pp_unknown()) def pp_decl(self, f): k = f.kind() if k == Z3_OP_DT_IS or k == Z3_OP_ARRAY_MAP: g = f.params()[0] r = [ to_format(g.name()) ] return seq1(self.pp_name(f), r) return self.pp_name(f) def pp_seq_core(self, f, a, d, xs): self.visited = self.visited + 1 if d > self.max_depth or self.visited > self.max_visited: return self.pp_ellipses() r = [] sz = 0 for elem in a: r.append(f(elem, d+1, xs)) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, '[', ']') def pp_seq(self, a, d, xs): return self.pp_seq_core(self.pp_expr, a, d, xs) def pp_seq_seq(self, a, d, xs): return self.pp_seq_core(self.pp_seq, a, d, xs) def pp_model(self, m): r = [] sz = 0 for d in m: i = m[d] if isinstance(i, z3.FuncInterp): i_pp = self.pp_func_interp(i) else: i_pp = self.pp_expr(i, 0, []) name = self.pp_name(d) r.append(compose(name, to_format(' = '), indent(_len(name) + 3, i_pp))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break return seq3(r, '[', ']') def pp_func_entry(self, e): num = e.num_args() if num > 1: args = [] for i in range(num): args.append(self.pp_expr(e.arg_value(i), 0, [])) args_pp = group(seq3(args)) else: args_pp = self.pp_expr(e.arg_value(0), 0, []) value_pp = self.pp_expr(e.value(), 0, []) return group(seq((args_pp, value_pp), self.pp_arrow())) def pp_func_interp(self, f): r = [] sz = 0 num = f.num_entries() for i in range(num): r.append(self.pp_func_entry(f.entry(i))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if sz <= self.max_args: else_val = f.else_value() if else_val == None: else_pp = to_format('#unspecified') else: else_pp = self.pp_expr(else_val, 0, []) r.append(group(seq((to_format('else'), else_pp), self.pp_arrow()))) return seq3(r, '[', ']') def pp_list(self, a): r = [] sz = 0 for elem in a: if _support_pp(elem): r.append(self.main(elem)) else: r.append(to_format(str(elem))) sz = sz + 1 if sz > self.max_args: r.append(self.pp_ellipses()) break if isinstance(a, tuple): return seq3(r) else: return seq3(r, '[', ']') def main(self, a): if z3.is_expr(a): return self.pp_expr(a, 0, []) elif z3.is_sort(a): return self.pp_sort(a) elif z3.is_func_decl(a): return self.pp_decl(a) elif isinstance(a, z3.Goal) or isinstance(a, z3.AstVector): return self.pp_seq(a, 0, []) elif isinstance(a, z3.Solver): return self.pp_seq(a.assertions(), 0, []) elif isinstance(a, z3.Fixedpoint): return a.sexpr() elif isinstance(a, z3.Optimize): return a.sexpr() elif isinstance(a, z3.ApplyResult): return self.pp_seq_seq(a, 0, []) elif isinstance(a, z3.ModelRef): return self.pp_model(a) elif isinstance(a, z3.FuncInterp): return self.pp_func_interp(a) elif isinstance(a, list) or isinstance(a, tuple): return self.pp_list(a) else: return to_format(self.pp_unknown()) def __call__(self, a): self.visited = 0 return self.main(a) class HTMLFormatter(Formatter): def __init__(self): Formatter.__init__(self) global _html_ellipses self.ellipses = to_format(_html_ellipses) def pp_arrow(self): return to_format(' &rarr;', 1) def pp_unknown(self): return '<b>unknown</b>' def pp_name(self, a): r = _html_op_name(a) if r[0] == '&' or r[0] == '/' or r[0] == '%': return to_format(r, 1) else: pos = r.find('__') if pos == -1 or pos == 0: return to_format(r) else: sz = len(r) if pos + 2 == sz: return to_format(r) else: return to_format('%s<sub>%s</sub>' % (r[0:pos], r[pos+2:sz]), sz - 2) def is_assoc(self, k): return _is_html_assoc(k) def is_left_assoc(self, k): return _is_html_left_assoc(k) def is_infix(self, a): return _is_html_infix(a) def is_unary(self, a): return _is_html_unary(a) def get_precedence(self, a): return _get_html_precedence(a) def pp_neq(self): return to_format("&ne;") def pp_power(self, a, d, xs): arg1_pp = self.pp_power_arg(a.arg(0), d+1, xs) arg2_pp = self.pp_expr(a.arg(1), d+1, xs) return compose(arg1_pp, to_format('<sup>', 1), arg2_pp, to_format('</sup>', 1)) def pp_var(self, a, d, xs): idx = z3.get_var_index(a) sz = len(xs) if idx >= sz: # 957 is the greek letter nu return to_format('&#957;<sub>%s</sub>' % idx, 1) else: return to_format(xs[sz - idx - 1]) def pp_quantifier(self, a, d, xs): ys = [ to_format(a.var_name(i)) for i in range(a.num_vars()) ] new_xs = xs + ys body_pp = self.pp_expr(a.body(), d+1, new_xs) ys_pp = group(seq(ys)) if a.is_forall(): header = '&forall;' else: header = '&exist;' return group(compose(to_format(header, 1), indent(1, compose(ys_pp, to_format(' :'), line_break(), body_pp)))) _PP = PP() _Formatter = Formatter() def set_pp_option(k, v): if k == 'html_mode': if v: set_html_mode(True) else: set_html_mode(False) return True if k == 'fpa_pretty': if v: set_fpa_pretty(True) else: set_fpa_pretty(False) return True val = getattr(_PP, k, None) if val != None: _z3_assert(type(v) == type(val), "Invalid pretty print option value") setattr(_PP, k, v) return True val = getattr(_Formatter, k, None) if val != None: _z3_assert(type(v) == type(val), "Invalid pretty print option value") setattr(_Formatter, k, v) return True return False def obj_to_string(a): out = io.StringIO() _PP(out, _Formatter(a)) return out.getvalue() _html_out = None def set_html_mode(flag=True): global _Formatter if flag: _Formatter = HTMLFormatter() else: _Formatter = Formatter() def set_fpa_pretty(flag=True): global _Formatter global _z3_op_to_str _Formatter.fpa_pretty = flag if flag: for (_k,_v) in _z3_op_to_fpa_pretty_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = True else: for (_k,_v) in _z3_op_to_fpa_normal_str.items(): _z3_op_to_str[_k] = _v for _k in _z3_fpa_infix: _infix_map[_k] = False set_fpa_pretty(True) def get_fpa_pretty(): global Formatter return _Formatter.fpa_pretty def in_html_mode(): return isinstance(_Formatter, HTMLFormatter) def pp(a): if _support_pp(a): print(obj_to_string(a)) else: print(a) def print_matrix(m): _z3_assert(isinstance(m, list) or isinstance(m, tuple), "matrix expected") if not in_html_mode(): print(obj_to_string(m)) else: print('<table cellpadding="2", cellspacing="0", border="1">') for r in m: _z3_assert(isinstance(r, list) or isinstance(r, tuple), "matrix expected") print('<tr>') for c in r: print('<td>%s</td>' % c) print('</tr>') print('</table>') def insert_line_breaks(s, width): """Break s in lines of size width (approx)""" sz = len(s) if sz <= width: return s new_str = io.StringIO() w = 0 for i in range(sz): if w > width and s[i] == ' ': new_str.write(u('<br />')) w = 0 else: new_str.write(u(s[i])) w = w + 1 return new_str.getvalue()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3printer.py
z3printer.py
from .z3 import * from .z3core import * from .z3printer import * from fractions import Fraction from .z3 import _get_ctx def _to_numeral(num, ctx=None): if isinstance(num, Numeral): return num else: return Numeral(num, ctx) class Numeral: """ A Z3 numeral can be used to perform computations over arbitrary precision integers, rationals and real algebraic numbers. It also automatically converts python numeric values. >>> Numeral(2) 2 >>> Numeral("3/2") + 1 5/2 >>> Numeral(Sqrt(2)) 1.4142135623? >>> Numeral(Sqrt(2)) + 2 3.4142135623? >>> Numeral(Sqrt(2)) + Numeral(Sqrt(3)) 3.1462643699? Z3 numerals can be used to perform computations with values in a Z3 model. >>> s = Solver() >>> x = Real('x') >>> s.add(x*x == 2) >>> s.add(x > 0) >>> s.check() sat >>> m = s.model() >>> m[x] 1.4142135623? >>> m[x] + 1 1.4142135623? + 1 The previous result is a Z3 expression. >>> (m[x] + 1).sexpr() '(+ (root-obj (+ (^ x 2) (- 2)) 2) 1.0)' >>> Numeral(m[x]) + 1 2.4142135623? >>> Numeral(m[x]).is_pos() True >>> Numeral(m[x])**2 2 We can also isolate the roots of polynomials. >>> x0, x1, x2 = RealVarVector(3) >>> r0 = isolate_roots(x0**5 - x0 - 1) >>> r0 [1.1673039782?] In the following example, we are isolating the roots of a univariate polynomial (on x1) obtained after substituting x0 -> r0[0] >>> r1 = isolate_roots(x1**2 - x0 + 1, [ r0[0] ]) >>> r1 [-0.4090280898?, 0.4090280898?] Similarly, in the next example we isolate the roots of a univariate polynomial (on x2) obtained after substituting x0 -> r0[0] and x1 -> r1[0] >>> isolate_roots(x1*x2 + x0, [ r0[0], r1[0] ]) [2.8538479564?] """ def __init__(self, num, ctx=None): if isinstance(num, Ast): self.ast = num self.ctx = _get_ctx(ctx) elif isinstance(num, RatNumRef) or isinstance(num, AlgebraicNumRef): self.ast = num.ast self.ctx = num.ctx elif isinstance(num, ArithRef): r = simplify(num) self.ast = r.ast self.ctx = r.ctx else: v = RealVal(num, ctx) self.ast = v.ast self.ctx = v.ctx Z3_inc_ref(self.ctx_ref(), self.as_ast()) assert Z3_algebraic_is_value(self.ctx_ref(), self.ast) def __del__(self): Z3_dec_ref(self.ctx_ref(), self.as_ast()) def is_integer(self): """ Return True if the numeral is integer. >>> Numeral(2).is_integer() True >>> (Numeral(Sqrt(2)) * Numeral(Sqrt(2))).is_integer() True >>> Numeral(Sqrt(2)).is_integer() False >>> Numeral("2/3").is_integer() False """ return self.is_rational() and self.denominator() == 1 def is_rational(self): """ Return True if the numeral is rational. >>> Numeral(2).is_rational() True >>> Numeral("2/3").is_rational() True >>> Numeral(Sqrt(2)).is_rational() False """ return Z3_get_ast_kind(self.ctx_ref(), self.as_ast()) == Z3_NUMERAL_AST def denominator(self): """ Return the denominator if `self` is rational. >>> Numeral("2/3").denominator() 3 """ assert(self.is_rational()) return Numeral(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) def numerator(self): """ Return the numerator if `self` is rational. >>> Numeral("2/3").numerator() 2 """ assert(self.is_rational()) return Numeral(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) def is_irrational(self): """ Return True if the numeral is irrational. >>> Numeral(2).is_irrational() False >>> Numeral("2/3").is_irrational() False >>> Numeral(Sqrt(2)).is_irrational() True """ return not self.is_rational() def as_long(self): """ Return a numeral (that is an integer) as a Python long. """ assert(self.is_integer()) if sys.version_info[0] >= 3: return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) else: return long(Z3_get_numeral_string(self.ctx_ref(), self.as_ast())) def as_fraction(self): """ Return a numeral (that is a rational) as a Python Fraction. >>> Numeral("1/5").as_fraction() Fraction(1, 5) """ assert(self.is_rational()) return Fraction(self.numerator().as_long(), self.denominator().as_long()) def approx(self, precision=10): """Return a numeral that approximates the numeral `self`. The result `r` is such that |r - self| <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.approx(20) 6838717160008073720548335/4835703278458516698824704 >>> x.approx(5) 2965821/2097152 >>> Numeral(2).approx(10) 2 """ return self.upper(precision) def upper(self, precision=10): """Return a upper bound that approximates the numeral `self`. The result `r` is such that r - self <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.upper(20) 6838717160008073720548335/4835703278458516698824704 >>> x.upper(5) 2965821/2097152 >>> Numeral(2).upper(10) 2 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) def lower(self, precision=10): """Return a lower bound that approximates the numeral `self`. The result `r` is such that self - r <= 1/10^precision If `self` is rational, then the result is `self`. >>> x = Numeral(2).root(2) >>> x.lower(20) 1709679290002018430137083/1208925819614629174706176 >>> Numeral("2/3").lower(10) 2/3 """ if self.is_rational(): return self else: return Numeral(Z3_get_algebraic_number_lower(self.ctx_ref(), self.as_ast(), precision), self.ctx) def sign(self): """ Return the sign of the numeral. >>> Numeral(2).sign() 1 >>> Numeral(-3).sign() -1 >>> Numeral(0).sign() 0 """ return Z3_algebraic_sign(self.ctx_ref(), self.ast) def is_pos(self): """ Return True if the numeral is positive. >>> Numeral(2).is_pos() True >>> Numeral(-3).is_pos() False >>> Numeral(0).is_pos() False """ return Z3_algebraic_is_pos(self.ctx_ref(), self.ast) def is_neg(self): """ Return True if the numeral is negative. >>> Numeral(2).is_neg() False >>> Numeral(-3).is_neg() True >>> Numeral(0).is_neg() False """ return Z3_algebraic_is_neg(self.ctx_ref(), self.ast) def is_zero(self): """ Return True if the numeral is zero. >>> Numeral(2).is_zero() False >>> Numeral(-3).is_zero() False >>> Numeral(0).is_zero() True >>> sqrt2 = Numeral(2).root(2) >>> sqrt2.is_zero() False >>> (sqrt2 - sqrt2).is_zero() True """ return Z3_algebraic_is_zero(self.ctx_ref(), self.ast) def __add__(self, other): """ Return the numeral `self + other`. >>> Numeral(2) + 3 5 >>> Numeral(2) + Numeral(4) 6 >>> Numeral("2/3") + 1 5/3 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __radd__(self, other): """ Return the numeral `other + self`. >>> 3 + Numeral(2) 5 """ return Numeral(Z3_algebraic_add(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __sub__(self, other): """ Return the numeral `self - other`. >>> Numeral(2) - 3 -1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rsub__(self, other): """ Return the numeral `other - self`. >>> 3 - Numeral(2) 1 """ return Numeral(Z3_algebraic_sub(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __mul__(self, other): """ Return the numeral `self * other`. >>> Numeral(2) * 3 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __rmul__(self, other): """ Return the numeral `other * mul`. >>> 3 * Numeral(2) 6 """ return Numeral(Z3_algebraic_mul(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __div__(self, other): """ Return the numeral `self / other`. >>> Numeral(2) / 3 2/3 >>> Numeral(2).root(2) / 3 0.4714045207? >>> Numeral(Sqrt(2)) / Numeral(Sqrt(3)) 0.8164965809? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast), self.ctx) def __truediv__(self, other): return self.__div__(other) def __rdiv__(self, other): """ Return the numeral `other / self`. >>> 3 / Numeral(2) 3/2 >>> 3 / Numeral(2).root(2) 2.1213203435? """ return Numeral(Z3_algebraic_div(self.ctx_ref(), _to_numeral(other, self.ctx).ast, self.ast), self.ctx) def __rtruediv__(self, other): return self.__rdiv__(other) def root(self, k): """ Return the numeral `self^(1/k)`. >>> sqrt2 = Numeral(2).root(2) >>> sqrt2 1.4142135623? >>> sqrt2 * sqrt2 2 >>> sqrt2 * 2 + 1 3.8284271247? >>> (sqrt2 * 2 + 1).sexpr() '(root-obj (+ (^ x 2) (* (- 2) x) (- 7)) 2)' """ return Numeral(Z3_algebraic_root(self.ctx_ref(), self.ast, k), self.ctx) def power(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3.power(2) 3 """ return Numeral(Z3_algebraic_power(self.ctx_ref(), self.ast, k), self.ctx) def __pow__(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3**2 3 """ return self.power(k) def __lt__(self, other): """ Return True if `self < other`. >>> Numeral(Sqrt(2)) < 2 True >>> Numeral(Sqrt(3)) < Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) < Numeral(Sqrt(2)) False """ return Z3_algebraic_lt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rlt__(self, other): """ Return True if `other < self`. >>> 2 < Numeral(Sqrt(2)) False """ return self > other def __gt__(self, other): """ Return True if `self > other`. >>> Numeral(Sqrt(2)) > 2 False >>> Numeral(Sqrt(3)) > Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) > Numeral(Sqrt(2)) False """ return Z3_algebraic_gt(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rgt__(self, other): """ Return True if `other > self`. >>> 2 > Numeral(Sqrt(2)) True """ return self < other def __le__(self, other): """ Return True if `self <= other`. >>> Numeral(Sqrt(2)) <= 2 True >>> Numeral(Sqrt(3)) <= Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) <= Numeral(Sqrt(2)) True """ return Z3_algebraic_le(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rle__(self, other): """ Return True if `other <= self`. >>> 2 <= Numeral(Sqrt(2)) False """ return self >= other def __ge__(self, other): """ Return True if `self >= other`. >>> Numeral(Sqrt(2)) >= 2 False >>> Numeral(Sqrt(3)) >= Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) >= Numeral(Sqrt(2)) True """ return Z3_algebraic_ge(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __rge__(self, other): """ Return True if `other >= self`. >>> 2 >= Numeral(Sqrt(2)) True """ return self <= other def __eq__(self, other): """ Return True if `self == other`. >>> Numeral(Sqrt(2)) == 2 False >>> Numeral(Sqrt(3)) == Numeral(Sqrt(2)) False >>> Numeral(Sqrt(2)) == Numeral(Sqrt(2)) True """ return Z3_algebraic_eq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __ne__(self, other): """ Return True if `self != other`. >>> Numeral(Sqrt(2)) != 2 True >>> Numeral(Sqrt(3)) != Numeral(Sqrt(2)) True >>> Numeral(Sqrt(2)) != Numeral(Sqrt(2)) False """ return Z3_algebraic_neq(self.ctx_ref(), self.ast, _to_numeral(other, self.ctx).ast) def __str__(self): if Z3_is_numeral_ast(self.ctx_ref(), self.ast): return str(RatNumRef(self.ast, self.ctx)) else: return str(AlgebraicNumRef(self.ast, self.ctx)) def __repr__(self): return self.__str__() def sexpr(self): return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) def as_ast(self): return self.ast def ctx_ref(self): return self.ctx.ref() def eval_sign_at(p, vs): """ Evaluate the sign of the polynomial `p` at `vs`. `p` is a Z3 Expression containing arithmetic operators: +, -, *, ^k where k is an integer; and free variables x that is_var(x) is True. Moreover, all variables must be real. The result is 1 if the polynomial is positive at the given point, -1 if negative, and 0 if zero. >>> x0, x1, x2 = RealVarVector(3) >>> eval_sign_at(x0**2 + x1*x2 + 1, (Numeral(0), Numeral(1), Numeral(2))) 1 >>> eval_sign_at(x0**2 - 2, [ Numeral(Sqrt(2)) ]) 0 >>> eval_sign_at((x0 + x1)*(x0 + x2), (Numeral(0), Numeral(Sqrt(2)), Numeral(Sqrt(3)))) 1 """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast return Z3_algebraic_eval(p.ctx_ref(), p.as_ast(), num, _vs) def isolate_roots(p, vs=[]): """ Given a multivariate polynomial p(x_0, ..., x_{n-1}, x_n), returns the roots of the univariate polynomial p(vs[0], ..., vs[len(vs)-1], x_n). Remarks: * p is a Z3 expression that contains only arithmetic terms and free variables. * forall i in [0, n) vs is a numeral. The result is a list of numerals >>> x0 = RealVar(0) >>> isolate_roots(x0**5 - x0 - 1) [1.1673039782?] >>> x1 = RealVar(1) >>> isolate_roots(x0**2 - x1**4 - 1, [ Numeral(Sqrt(3)) ]) [-1.1892071150?, 1.1892071150?] >>> x2 = RealVar(2) >>> isolate_roots(x2**2 + x0 - x1, [ Numeral(Sqrt(3)), Numeral(Sqrt(2)) ]) [] """ num = len(vs) _vs = (Ast * num)() for i in range(num): _vs[i] = vs[i].ast _roots = AstVector(Z3_algebraic_roots(p.ctx_ref(), p.as_ast(), num, _vs), p.ctx) return [ Numeral(r) for r in _roots ]
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3num.py
z3num.py
from .z3 import * def vset(seq, idfun=None, as_list=True): # This functions preserves the order of arguments while removing duplicates. # This function is from https://code.google.com/p/common-python-vu/source/browse/vu_common.py # (Thanhu's personal code). It has been copied here to avoid a dependency on vu_common.py. """ order preserving >>> vset([[11,2],1, [10,['9',1]],2, 1, [11,2],[3,3],[10,99],1,[10,['9',1]]],idfun=repr) [[11, 2], 1, [10, ['9', 1]], 2, [3, 3], [10, 99]] """ def _uniq_normal(seq): d_ = {} for s in seq: if s not in d_: d_[s] = None yield s def _uniq_idfun(seq,idfun): d_ = {} for s in seq: h_ = idfun(s) if h_ not in d_: d_[h_] = None yield s if idfun is None: res = _uniq_normal(seq) else: res = _uniq_idfun(seq,idfun) return list(res) if as_list else res def get_z3_version(as_str=False): major = ctypes.c_uint(0) minor = ctypes.c_uint(0) build = ctypes.c_uint(0) rev = ctypes.c_uint(0) Z3_get_version(major,minor,build,rev) rs = map(int,(major.value,minor.value,build.value,rev.value)) if as_str: return "{}.{}.{}.{}".format(*rs) else: return rs def ehash(v): """ Returns a 'stronger' hash value than the default hash() method. The result from hash() is not enough to distinguish between 2 z3 expressions in some cases. Note: the following doctests will fail with Python 2.x as the default formatting doesn't match that of 3.x. >>> x1 = Bool('x'); x2 = Bool('x'); x3 = Int('x') >>> print(x1.hash(),x2.hash(),x3.hash()) #BAD: all same hash values 783810685 783810685 783810685 >>> print(ehash(x1), ehash(x2), ehash(x3)) x_783810685_1 x_783810685_1 x_783810685_2 """ if z3_debug(): assert is_expr(v) return "{}_{}_{}".format(str(v),v.hash(),v.sort_kind()) """ In Z3, variables are called *uninterpreted* consts and variables are *interpreted* consts. """ def is_expr_var(v): """ EXAMPLES: >>> is_expr_var(Int('7')) True >>> is_expr_var(IntVal('7')) False >>> is_expr_var(Bool('y')) True >>> is_expr_var(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_var(LOnOff) False >>> is_expr_var(On) False >>> is_expr_var(Block) True >>> is_expr_var(SafetyInjection) True """ return is_const(v) and v.decl().kind()==Z3_OP_UNINTERPRETED def is_expr_val(v): """ EXAMPLES: >>> is_expr_val(Int('7')) False >>> is_expr_val(IntVal('7')) True >>> is_expr_val(Bool('y')) False >>> is_expr_val(Int('x') + 7 == Int('y')) False >>> LOnOff, (On,Off) = EnumSort("LOnOff",['On','Off']) >>> Block,Reset,SafetyInjection=Consts("Block Reset SafetyInjection",LOnOff) >>> is_expr_val(LOnOff) False >>> is_expr_val(On) True >>> is_expr_val(Block) False >>> is_expr_val(SafetyInjection) False """ return is_const(v) and v.decl().kind()!=Z3_OP_UNINTERPRETED def get_vars(f,rs=[]): """ >>> x,y = Ints('x y') >>> a,b = Bools('a b') >>> get_vars(Implies(And(x+y==0,x*2==10),Or(a,Implies(a,b==False)))) [x, y, a, b] """ if z3_debug(): assert is_expr(f) if is_const(f): if is_expr_val(f): return rs else: #variable return vset(rs + [f],str) else: for f_ in f.children(): rs = get_vars(f_,rs) return vset(rs,str) def mk_var(name,vsort): if vsort.kind() == Z3_INT_SORT: v = Int(name) elif vsort.kind() == Z3_REAL_SORT: v = Real(name) elif vsort.kind() == Z3_BOOL_SORT: v = Bool(name) elif vsort.kind() == Z3_DATATYPE_SORT: v = Const(name,vsort) else: assert False, 'Cannot handle this sort (s: %sid: %d)'\ %(vsort,vsort.kind()) return v def prove(claim,assume=None,verbose=0): """ >>> r,m = prove(BoolVal(True),verbose=0); r,model_str(m,as_str=False) (True, None) #infinite counter example when proving contradiction >>> r,m = prove(BoolVal(False)); r,model_str(m,as_str=False) (False, []) >>> x,y,z=Bools('x y z') >>> r,m = prove(And(x,Not(x))); r,model_str(m,as_str=True) (False, '[]') >>> r,m = prove(True,assume=And(x,Not(x)),verbose=0) Traceback (most recent call last): ... AssertionError: Assumption is always False! >>> r,m = prove(Implies(x,x),assume=y,verbose=2); r,model_str(m,as_str=False) assume: y claim: Implies(x, x) to_prove: Implies(y, Implies(x, x)) (True, None) >>> r,m = prove(And(x,True),assume=y,verbose=0); r,model_str(m,as_str=False) (False, [(x, False), (y, True)]) >>> r,m = prove(And(x,y),assume=y,verbose=0) >>> print(r) False >>> print(model_str(m,as_str=True)) x = False y = True >>> a,b = Ints('a b') >>> r,m = prove(a**b == b**a,assume=None,verbose=0) E: cannot solve ! >>> r is None and m is None True """ if z3_debug(): assert not assume or is_expr(assume) to_prove = claim if assume: if z3_debug(): is_proved,_ = prove(Not(assume)) def _f(): emsg = "Assumption is always False!" if verbose >= 2: emsg = "{}\n{}".format(assume,emsg) return emsg assert is_proved==False, _f() to_prove = Implies(assume,to_prove) if verbose >= 2: print('assume: ') print(assume) print('claim: ') print(claim) print('to_prove: ') print(to_prove) f = Not(to_prove) models = get_models(f,k=1) if models is None: #unknown print('E: cannot solve !') return None, None elif models == False: #unsat return True,None else: #sat if z3_debug(): assert isinstance(models,list) if models: return False, models[0] #the first counterexample else: return False, [] #infinite counterexample,models def get_models(f,k): """ Returns the first k models satisfiying f. If f is not satisfiable, returns False. If f cannot be solved, returns None If f is satisfiable, returns the first k models Note that if f is a tautology, e.g.\ True, then the result is [] Based on http://stackoverflow.com/questions/11867611/z3py-checking-all-solutions-for-equation EXAMPLES: >>> x, y = Ints('x y') >>> len(get_models(And(0<=x,x <= 4),k=11)) 5 >>> get_models(And(0<=x**y,x <= 1),k=2) is None True >>> get_models(And(0<=x,x <= -1),k=2) False >>> len(get_models(x+y==7,5)) 5 >>> len(get_models(And(x<=5,x>=1),7)) 5 >>> get_models(And(x<=0,x>=5),7) False >>> x = Bool('x') >>> get_models(And(x,Not(x)),k=1) False >>> get_models(Implies(x,x),k=1) [] >>> get_models(BoolVal(True),k=1) [] """ if z3_debug(): assert is_expr(f) assert k>=1 s = Solver() s.add(f) models = [] i = 0 while s.check() == sat and i < k: i = i + 1 m = s.model() if not m: #if m == [] break models.append(m) #create new constraint to block the current model block = Not(And([v() == m[v] for v in m])) s.add(block) if s.check() == unknown: return None elif s.check() == unsat and i==0: return False else: return models def is_tautology(claim,verbose=0): """ >>> is_tautology(Implies(Bool('x'),Bool('x'))) True >>> is_tautology(Implies(Bool('x'),Bool('y'))) False >>> is_tautology(BoolVal(True)) True >>> is_tautology(BoolVal(False)) False """ return prove(claim=claim,assume=None,verbose=verbose)[0] def is_contradiction(claim,verbose=0): """ >>> x,y=Bools('x y') >>> is_contradiction(BoolVal(False)) True >>> is_contradiction(BoolVal(True)) False >>> is_contradiction(x) False >>> is_contradiction(Implies(x,y)) False >>> is_contradiction(Implies(x,x)) False >>> is_contradiction(And(x,Not(x))) True """ return prove(claim=Not(claim),assume=None,verbose=verbose)[0] def exact_one_model(f): """ return True if f has exactly 1 model, False otherwise. EXAMPLES: >>> x, y = Ints('x y') >>> exact_one_model(And(0<=x**y,x <= 0)) False >>> exact_one_model(And(0<=x,x <= 0)) True >>> exact_one_model(And(0<=x,x <= 1)) False >>> exact_one_model(And(0<=x,x <= -1)) False """ models = get_models(f,k=2) if isinstance(models,list): return len(models)==1 else: return False def myBinOp(op,*L): """ >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd(*[Bool('x'),None]) x >>> myAnd(*[Bool('x')]) x >>> myAnd(*[]) >>> myAnd(Bool('x'),Bool('y')) And(x, y) >>> myAnd(*[Bool('x'),Bool('y')]) And(x, y) >>> myAnd([Bool('x'),Bool('y')]) And(x, y) >>> myAnd((Bool('x'),Bool('y'))) And(x, y) >>> myAnd(*[Bool('x'),Bool('y'),True]) Traceback (most recent call last): ... AssertionError """ if z3_debug(): assert op == Z3_OP_OR or op == Z3_OP_AND or op == Z3_OP_IMPLIES if len(L)==1 and (isinstance(L[0],list) or isinstance(L[0],tuple)): L = L[0] if z3_debug(): assert all(not isinstance(l,bool) for l in L) L = [l for l in L if is_expr(l)] if L: if len(L)==1: return L[0] else: if op == Z3_OP_OR: return Or(L) elif op == Z3_OP_AND: return And(L) else: #IMPLIES return Implies(L[0],L[1]) else: return None def myAnd(*L): return myBinOp(Z3_OP_AND,*L) def myOr(*L): return myBinOp(Z3_OP_OR,*L) def myImplies(a,b):return myBinOp(Z3_OP_IMPLIES,[a,b]) Iff = lambda f: And(Implies(f[0],f[1]),Implies(f[1],f[0])) def model_str(m,as_str=True): """ Returned a 'sorted' model (so that it's easier to see) The model is sorted by its key, e.g. if the model is y = 3 , x = 10, then the result is x = 10, y = 3 EXAMPLES: see doctest exampels from function prove() """ if z3_debug(): assert m is None or m == [] or isinstance(m,ModelRef) if m : vs = [(v,m[v]) for v in m] vs = sorted(vs,key=lambda a,_: str(a)) if as_str: return '\n'.join(['{} = {}'.format(k,v) for (k,v) in vs]) else: return vs else: return str(m) if as_str else m
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3util.py
z3util.py
import ctypes class Z3Exception(Exception): def __init__(self, value): self.value = value def __str__(self): return str(self.value) class ContextObj(ctypes.c_void_p): def __init__(self, context): self._as_parameter_ = context def from_param(obj): return obj class Config(ctypes.c_void_p): def __init__(self, config): self._as_parameter_ = config def from_param(obj): return obj class Symbol(ctypes.c_void_p): def __init__(self, symbol): self._as_parameter_ = symbol def from_param(obj): return obj class Sort(ctypes.c_void_p): def __init__(self, sort): self._as_parameter_ = sort def from_param(obj): return obj class FuncDecl(ctypes.c_void_p): def __init__(self, decl): self._as_parameter_ = decl def from_param(obj): return obj class Ast(ctypes.c_void_p): def __init__(self, ast): self._as_parameter_ = ast def from_param(obj): return obj class Pattern(ctypes.c_void_p): def __init__(self, pattern): self._as_parameter_ = pattern def from_param(obj): return obj class Model(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class Literals(ctypes.c_void_p): def __init__(self, literals): self._as_parameter_ = literals def from_param(obj): return obj class Constructor(ctypes.c_void_p): def __init__(self, constructor): self._as_parameter_ = constructor def from_param(obj): return obj class ConstructorList(ctypes.c_void_p): def __init__(self, constructor_list): self._as_parameter_ = constructor_list def from_param(obj): return obj class GoalObj(ctypes.c_void_p): def __init__(self, goal): self._as_parameter_ = goal def from_param(obj): return obj class TacticObj(ctypes.c_void_p): def __init__(self, tactic): self._as_parameter_ = tactic def from_param(obj): return obj class ProbeObj(ctypes.c_void_p): def __init__(self, probe): self._as_parameter_ = probe def from_param(obj): return obj class ApplyResultObj(ctypes.c_void_p): def __init__(self, obj): self._as_parameter_ = obj def from_param(obj): return obj class StatsObj(ctypes.c_void_p): def __init__(self, statistics): self._as_parameter_ = statistics def from_param(obj): return obj class SolverObj(ctypes.c_void_p): def __init__(self, solver): self._as_parameter_ = solver def from_param(obj): return obj class FixedpointObj(ctypes.c_void_p): def __init__(self, fixedpoint): self._as_parameter_ = fixedpoint def from_param(obj): return obj class OptimizeObj(ctypes.c_void_p): def __init__(self, optimize): self._as_parameter_ = optimize def from_param(obj): return obj class ModelObj(ctypes.c_void_p): def __init__(self, model): self._as_parameter_ = model def from_param(obj): return obj class AstVectorObj(ctypes.c_void_p): def __init__(self, vector): self._as_parameter_ = vector def from_param(obj): return obj class AstMapObj(ctypes.c_void_p): def __init__(self, ast_map): self._as_parameter_ = ast_map def from_param(obj): return obj class Params(ctypes.c_void_p): def __init__(self, params): self._as_parameter_ = params def from_param(obj): return obj class ParamDescrs(ctypes.c_void_p): def __init__(self, paramdescrs): self._as_parameter_ = paramdescrs def from_param(obj): return obj class FuncInterpObj(ctypes.c_void_p): def __init__(self, f): self._as_parameter_ = f def from_param(obj): return obj class FuncEntryObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj class RCFNumObj(ctypes.c_void_p): def __init__(self, e): self._as_parameter_ = e def from_param(obj): return obj
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/z3/z3types.py
z3types.py
from z3 import * import heapq # Simplistic (and fragile) converter from # a class of Horn clauses corresponding to # a transition system into a transition system # representation as <init, trans, goal> # It assumes it is given three Horn clauses # of the form: # init(x) => Invariant(x) # Invariant(x) and trans(x,x') => Invariant(x') # Invariant(x) and goal(x) => Goal(x) # where Invariant and Goal are uninterpreted predicates class Horn2Transitions: def __init__(self): self.trans = True self.init = True self.inputs = [] self.goal = True self.index = 0 def parse(self, file): fp = Fixedpoint() goals = fp.parse_file(file) for r in fp.get_rules(): if not is_quantifier(r): continue b = r.body() if not is_implies(b): continue f = b.arg(0) g = b.arg(1) if self.is_goal(f, g): continue if self.is_transition(f, g): continue if self.is_init(f, g): continue def is_pred(self, p, name): return is_app(p) and p.decl().name() == name def is_goal(self, body, head): if not self.is_pred(head, "Goal"): return False pred, inv = self.is_body(body) if pred is None: return False self.goal = self.subst_vars("x", inv, pred) self.goal = self.subst_vars("i", self.goal, self.goal) self.inputs += self.vars self.inputs = list(set(self.inputs)) return True def is_body(self, body): if not is_and(body): return None, None fmls = [f for f in body.children() if self.is_inv(f) is None] inv = None for f in body.children(): if self.is_inv(f) is not None: inv = f; break return And(fmls), inv def is_inv(self, f): if self.is_pred(f, "Invariant"): return f return None def is_transition(self, body, head): pred, inv0 = self.is_body(body) if pred is None: return False inv1 = self.is_inv(head) if inv1 is None: return False pred = self.subst_vars("x", inv0, pred) self.xs = self.vars pred = self.subst_vars("xn", inv1, pred) self.xns = self.vars pred = self.subst_vars("i", pred, pred) self.inputs += self.vars self.inputs = list(set(self.inputs)) self.trans = pred return True def is_init(self, body, head): for f in body.children(): if self.is_inv(f) is not None: return False inv = self.is_inv(head) if inv is None: return False self.init = self.subst_vars("x", inv, body) return True def subst_vars(self, prefix, inv, fml): subst = self.mk_subst(prefix, inv) self.vars = [ v for (k,v) in subst ] return substitute(fml, subst) def mk_subst(self, prefix, inv): self.index = 0 if self.is_inv(inv) is not None: return [(f, self.mk_bool(prefix)) for f in inv.children()] else: vars = self.get_vars(inv) return [(f, self.mk_bool(prefix)) for f in vars] def mk_bool(self, prefix): self.index += 1 return Bool("%s%d" % (prefix, self.index)) def get_vars(self, f, rs=[]): if is_var(f): return z3util.vset(rs + [f], str) else: for f_ in f.children(): rs = self.get_vars(f_, rs) return z3util.vset(rs, str) # Produce a finite domain solver. # The theory QF_FD covers bit-vector formulas # and pseudo-Boolean constraints. # By default cardinality and pseudo-Boolean # constraints are converted to clauses. To override # this default for cardinality constraints # we set sat.cardinality.solver to True def fd_solver(): s = SolverFor("QF_FD") s.set("sat.cardinality.solver", True) return s # negate, avoid double negation def negate(f): if is_not(f): return f.arg(0) else: return Not(f) def cube2clause(cube): return Or([negate(f) for f in cube]) class State: def __init__(self, s): self.R = set([]) self.solver = s def add(self, clause): if clause not in self.R: self.R |= { clause } self.solver.add(clause) class Goal: def __init__(self, cube, parent, level): self.level = level self.cube = cube self.parent = parent def is_seq(f): return isinstance(f, list) or isinstance(f, tuple) or isinstance(f, AstVector) # Check if the initial state is bad def check_disjoint(a, b): s = fd_solver() s.add(a) s.add(b) return unsat == s.check() # Remove clauses that are subsumed def prune(R): removed = set([]) s = fd_solver() for f1 in R: s.push() for f2 in R: if f2 not in removed: s.add(Not(f2) if f1.eq(f2) else f2) if s.check() == unsat: removed |= { f1 } s.pop() return R - removed class MiniIC3: def __init__(self, init, trans, goal, x0, inputs, xn): self.x0 = x0 self.inputs = inputs self.xn = xn self.init = init self.bad = goal self.trans = trans self.min_cube_solver = fd_solver() self.min_cube_solver.add(Not(trans)) self.goals = [] s = State(fd_solver()) s.add(init) s.solver.add(trans) self.states = [s] self.s_bad = fd_solver() self.s_good = fd_solver() self.s_bad.add(self.bad) self.s_good.add(Not(self.bad)) def next(self, f): if is_seq(f): return [self.next(f1) for f1 in f] return substitute(f, zip(self.x0, self.xn)) def prev(self, f): if is_seq(f): return [self.prev(f1) for f1 in f] return substitute(f, zip(self.xn, self.x0)) def add_solver(self): s = fd_solver() s.add(self.trans) self.states += [State(s)] def R(self, i): return And(self.states[i].R) # Check if there are two states next to each other that have the same clauses. def is_valid(self): i = 1 while i + 1 < len(self.states): if not (self.states[i].R - self.states[i+1].R): return And(prune(self.states[i].R)) i += 1 return None def value2literal(self, m, x): value = m.eval(x) if is_true(value): return x if is_false(value): return Not(x) return None def values2literals(self, m, xs): p = [self.value2literal(m, x) for x in xs] return [x for x in p if x is not None] def project0(self, m): return self.values2literals(m, self.x0) def projectI(self, m): return self.values2literals(m, self.inputs) def projectN(self, m): return self.values2literals(m, self.xn) # Determine if there is a cube for the current state # that is potentially reachable. def unfold(self): core = [] self.s_bad.push() R = self.R(len(self.states)-1) self.s_bad.add(R) is_sat = self.s_bad.check() if is_sat == sat: m = self.s_bad.model() cube = self.project0(m) props = cube + self.projectI(m) self.s_good.push() self.s_good.add(R) is_sat2 = self.s_good.check(props) assert is_sat2 == unsat core = self.s_good.unsat_core() core = [c for c in core if c in set(cube)] self.s_good.pop() self.s_bad.pop() return is_sat, core # Block a cube by asserting the clause corresponding to its negation def block_cube(self, i, cube): self.assert_clause(i, cube2clause(cube)) # Add a clause to levels 0 until i def assert_clause(self, i, clause): for j in range(i + 1): self.states[j].add(clause) # minimize cube that is core of Dual solver. # this assumes that props & cube => Trans def minimize_cube(self, cube, inputs, lits): is_sat = self.min_cube_solver.check(lits + [c for c in cube] + [i for i in inputs]) assert is_sat == unsat core = self.min_cube_solver.unsat_core() assert core return [c for c in core if c in set(cube)] # push a goal on a heap def push_heap(self, goal): heapq.heappush(self.goals, (goal.level, goal)) # A state s0 and level f0 such that # not(s0) is f0-1 inductive def ic3_blocked(self, s0, f0): self.push_heap(Goal(self.next(s0), None, f0)) while self.goals: f, g = heapq.heappop(self.goals) sys.stdout.write("%d." % f) sys.stdout.flush() # Not(g.cube) is f-1 invariant if f == 0: print("") return g cube, f, is_sat = self.is_inductive(f, g.cube) if is_sat == unsat: self.block_cube(f, self.prev(cube)) if f < f0: self.push_heap(Goal(g.cube, g.parent, f + 1)) elif is_sat == sat: self.push_heap(Goal(cube, g, f - 1)) self.push_heap(g) else: return is_sat print("") return None # Rudimentary generalization: # If the cube is already unsat with respect to transition relation # extract a core (not necessarily minimal) # otherwise, just return the cube. def generalize(self, cube, f): s = self.states[f - 1].solver if unsat == s.check(cube): core = s.unsat_core() if not check_disjoint(self.init, self.prev(And(core))): return core, f return cube, f # Check if the negation of cube is inductive at level f def is_inductive(self, f, cube): s = self.states[f - 1].solver s.push() s.add(self.prev(Not(And(cube)))) is_sat = s.check(cube) if is_sat == sat: m = s.model() s.pop() if is_sat == sat: cube = self.next(self.minimize_cube(self.project0(m), self.projectI(m), self.projectN(m))) elif is_sat == unsat: cube, f = self.generalize(cube, f) return cube, f, is_sat def run(self): if not check_disjoint(self.init, self.bad): return "goal is reached in initial state" level = 0 while True: inv = self.is_valid() if inv is not None: return inv is_sat, cube = self.unfold() if is_sat == unsat: level += 1 print("Unfold %d" % level) sys.stdout.flush() self.add_solver() elif is_sat == sat: cex = self.ic3_blocked(cube, level) if cex is not None: return cex else: return is_sat def test(file): h2t = Horn2Transitions() h2t.parse(file) mp = MiniIC3(h2t.init, h2t.trans, h2t.goal, h2t.xs, h2t.inputs, h2t.xns) result = mp.run() if isinstance(result, Goal): g = result print("Trace") while g: print(g.level, g.cube) g = g.parent return if isinstance(result, ExprRef): print("Invariant:\n%s " % result) return print(result) test("data/horn1.smt2") test("data/horn2.smt2") test("data/horn3.smt2") test("data/horn4.smt2") test("data/horn5.smt2") # test("data/horn6.smt2") # takes long time to finish
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/mini_ic3.py
mini_ic3.py
from z3 import * from z3 import * def tt(s, f): return is_true(s.model().eval(f)) def add(Ws, f, w): Ws[f] = w + (Ws[f] if f in Ws else 0) def sub(Ws, f, w): w1 = Ws[f] if w1 > w: Ws[f] = w1 - w else: del(Ws[f]) class RC2: def __init__(self, s): self.bounds = {} self.names = {} self.solver = s self.solver.set("sat.cardinality.solver", True) self.solver.set("sat.core.minimize", True) self.solver.set("sat.core.minimize_partial", True) def at_most(self, S, k): fml = simplify(AtMost(S + [k])) if fml in self.names: return self.names[fml] name = Bool("%s" % fml) self.solver.add(Implies(name, fml)) self.bounds[name] = (S, k) self.names[fml] = name return name def print_cost(self): print("cost [", self.min_cost, ":", self.max_cost, "]") def update_max_cost(self): self.max_cost = min(self.max_cost, self.get_cost()) self.print_cost() # sort W, and incrementally add elements of W # in sorted order to prefer cores with high weight. def check(self, Ws): def compare(fw): f, w = fw return -w ws = sorted([(k,Ws[k]) for k in Ws], key = compare) i = 0 while i < len(ws): j = i # increment j until making 5% progress or exhausting equal weight entries while (j < len(ws) and ws[j][1] == ws[i][1]) or (i > 0 and (j - i)*20 < len(ws)): j += 1 i = j r = self.solver.check([ws[j][0] for j in range(i)]) if r == sat: self.update_max_cost() else: return r return sat def get_cost(self): return sum(self.Ws0[c] for c in self.Ws0 if not tt(self.solver, c)) # Retrieve independent cores from Ws def get_cores(self, Ws): cores = [] while unsat == self.check(Ws): core = list(self.solver.unsat_core()) print (self.solver.statistics()) if not core: return unsat w = min([Ws[c] for c in core]) for f in core: sub(Ws, f, w) cores += [(core, w)] self.update_max_cost() return cores # Add new soft constraints to replace core # with weight w. Allow to weaken at most # one element of core. Elements that are # cardinality constraints are weakened by # increasing their bounds. Non-cardinality # constraints are weakened to "true". They # correspond to the constraint Not(s) <= 0, # so weakening produces Not(s) <= 1, which # is a tautology. def update_bounds(self, Ws, core, w): for f in core: if f in self.bounds: S, k = self.bounds[f] if k + 1 < len(S): add(Ws, self.at_most(S, k + 1), w) add(Ws, self.at_most([mk_not(f) for f in core], 1), w) # Ws are weighted soft constraints # Whenever there is an unsatisfiable core over ws # increase the limit of each soft constraint from a bound # and create a soft constraint that limits the number of # increased bounds to be at most one. def maxsat(self, Ws): self.min_cost = 0 self.max_cost = sum(Ws[c] for c in Ws) self.Ws0 = Ws.copy() while True: cores = self.get_cores(Ws) if not cores: break if cores == unsat: return unsat for (core, w) in cores: self.min_cost += w self.print_cost() self.update_bounds(Ws, core, w) return self.min_cost, { f for f in self.Ws0 if not tt(self.solver, f) } def from_file(self, file): opt = Optimize() opt.from_file(file) self.solver.add(opt.assertions()) obj = opt.objectives()[0] Ws = {} for f in obj.children(): assert(f.arg(1).as_long() == 0) add(Ws, f.arg(0), f.arg(2).as_long()) return self.maxsat(Ws) def from_formulas(self, hard, soft): self.solver.add(hard) Ws = {} for f, cost in soft: add(Ws, f, cost) return self.maxsat(Ws) def main(file): s = SolverFor("QF_FD") rc2 = RC2(s) set_param(verbose=0) cost, falses = rc2.from_file(file) print(cost) print(s.statistics()) if len(sys.argv) > 1: main(sys.argv[1]) # main(<myfile>)
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/rc2.py
rc2.py
from __future__ import print_function from z3 import * import time set_option("sat.gc.burst", False) # disable GC at every search. It is wasteful for these small queries. def diff_at_j_is_i(xs, j, i): assert(0 <= j and j + 1 < len(xs)) assert(1 <= i and i < len(xs)) return Or([ And(xs[j][k], xs[j+1][k-i]) for k in range(i,len(xs))] + [ And(xs[j][k], xs[j+1][k+i]) for k in range(0,len(xs)-i)]) def ais(n): xij = [ [ Bool("x_%d_%d" % (i,j)) for j in range(n)] for i in range(n) ] s = SolverFor("QF_FD") # Optionally replace by (slower) default solver if using # more then just finite domains (Booleans, Bit-vectors, enumeration types # and bounded integers) # s = Solver() for i in range(n): s.add(AtMost(xij[i] + [1])) s.add(Or(xij[i])) for j in range(n): xi = [ xij[i][j] for i in range(n) ] s.add(AtMost(xi + [1])) s.add(Or(xi)) dji = [ [ diff_at_j_is_i(xij, j, i + 1) for i in range(n-1)] for j in range(n-1) ] for j in range(n-1): s.add(AtMost(dji[j] + [1])) s.add(Or(dji[j])) for i in range(n-1): dj = [dji[j][i] for j in range(n-1)] s.add(AtMost(dj + [1])) s.add(Or(dj)) return s, xij def process_model(s, xij, n): # x_ij integer i is at position j # d_ij difference between integer at position j, j+1 is i # sum_j d_ij = 1 i = 1,...,n-1 # sum_j x_ij = 1 # sum_i x_ij = 1 m = s.model() block = [] values = [] for i in range(n): k = -1 for j in range(n): if is_true(m.eval(xij[i][j])): assert(k == -1) block += [xij[i][j]] k = j values += [k] print(values) sys.stdout.flush() return block def all_models(n): count = 0 s, xij = ais(n) start = time.clock() while sat == s.check(): block = process_model(s, xij, n) s.add(Not(And(block))) count += 1 print(s.statistics()) print(time.clock() - start) print(count) set_option(verbose=1) all_models(12)
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/all_interval_series.py
all_interval_series.py
from z3 import * class Car(): def __init__(self, is_vertical, base_pos, length, start, color): self.is_vertical = is_vertical self.base = base_pos self.length = length self.start = start self.color = color def __eq__(self, other): return self.color == other.color def __ne__(self, other): return self.color != other.color dimension = 6 red_car = Car(False, 2, 2, 3, "red") cars = [ Car(True, 0, 3, 0, 'yellow'), Car(False, 3, 3, 0, 'blue'), Car(False, 5, 2, 0, "brown"), Car(False, 0, 2, 1, "lgreen"), Car(True, 1, 2, 1, "light blue"), Car(True, 2, 2, 1, "pink"), Car(True, 2, 2, 4, "dark green"), red_car, Car(True, 3, 2, 3, "purple"), Car(False, 5, 2, 3, "light yellow"), Car(True, 4, 2, 0, "orange"), Car(False, 4, 2, 4, "black"), Car(True, 5, 3, 1, "light purple") ] num_cars = len(cars) B = BoolSort() bv3 = BitVecSort(3) state = Function('state', [ bv3 for c in cars] + [B]) def num(i): return BitVecVal(i,bv3) def bound(i): return Const(cars[i].color, bv3) fp = Fixedpoint() fp.set("fp.engine","datalog") fp.set("datalog.generate_explanations",True) fp.declare_var([bound(i) for i in range(num_cars)]) fp.register_relation(state) def mk_state(car, value): return state([ (num(value) if (cars[i] == car) else bound(i)) for i in range(num_cars)]) def mk_transition(row, col, i0, j, car0): body = [mk_state(car0, i0)] for index in range(num_cars): car = cars[index] if car0 != car: if car.is_vertical and car.base == col: for i in range(dimension): if i <= row and row < i + car.length and i + car.length <= dimension: body += [bound(index) != num(i)] if car.base == row and not car.is_vertical: for i in range(dimension): if i <= col and col < i + car.length and i + car.length <= dimension: body += [bound(index) != num(i)] s = "%s %d->%d" % (car0.color, i0, j) fp.rule(mk_state(car0, j), body, s) def move_down(i, car): free_row = i + car.length if free_row < dimension: mk_transition(free_row, car.base, i, i + 1, car) def move_up(i, car): free_row = i - 1 if 0 <= free_row and i + car.length <= dimension: mk_transition(free_row, car.base, i, i - 1, car) def move_left(i, car): free_col = i - 1; if 0 <= free_col and i + car.length <= dimension: mk_transition(car.base, free_col, i, i - 1, car) def move_right(i, car): free_col = car.length + i if free_col < dimension: mk_transition(car.base, free_col, i, i + 1, car) # Initial state: fp.fact(state([num(cars[i].start) for i in range(num_cars)])) # Transitions: for car in cars: for i in range(dimension): if car.is_vertical: move_down(i, car) move_up(i, car) else: move_left(i, car) move_right(i, car) def get_instructions(ans): lastAnd = ans.arg(0).children()[-1] trace = lastAnd.children()[1] while trace.num_args() > 0: print(trace.decl()) trace = trace.children()[-1] goal = state([ (num(4) if cars[i] == red_car else bound(i)) for i in range(num_cars)]) fp.query(goal) get_instructions(fp.get_answer()) del goal del state del fp
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/trafficjam.py
trafficjam.py
from z3 import * import heapq import numpy import time import random verbose = True # Simplistic (and fragile) converter from # a class of Horn clauses corresponding to # a transition system into a transition system # representation as <init, trans, goal> # It assumes it is given three Horn clauses # of the form: # init(x) => Invariant(x) # Invariant(x) and trans(x,x') => Invariant(x') # Invariant(x) and goal(x) => Goal(x) # where Invariant and Goal are uninterpreted predicates class Horn2Transitions: def __init__(self): self.trans = True self.init = True self.inputs = [] self.goal = True self.index = 0 def parse(self, file): fp = Fixedpoint() goals = fp.parse_file(file) for r in fp.get_rules(): if not is_quantifier(r): continue b = r.body() if not is_implies(b): continue f = b.arg(0) g = b.arg(1) if self.is_goal(f, g): continue if self.is_transition(f, g): continue if self.is_init(f, g): continue def is_pred(self, p, name): return is_app(p) and p.decl().name() == name def is_goal(self, body, head): if not self.is_pred(head, "Goal"): return False pred, inv = self.is_body(body) if pred is None: return False self.goal = self.subst_vars("x", inv, pred) self.goal = self.subst_vars("i", self.goal, self.goal) self.inputs += self.vars self.inputs = list(set(self.inputs)) return True def is_body(self, body): if not is_and(body): return None, None fmls = [f for f in body.children() if self.is_inv(f) is None] inv = None for f in body.children(): if self.is_inv(f) is not None: inv = f; break return And(fmls), inv def is_inv(self, f): if self.is_pred(f, "Invariant"): return f return None def is_transition(self, body, head): pred, inv0 = self.is_body(body) if pred is None: return False inv1 = self.is_inv(head) if inv1 is None: return False pred = self.subst_vars("x", inv0, pred) self.xs = self.vars pred = self.subst_vars("xn", inv1, pred) self.xns = self.vars pred = self.subst_vars("i", pred, pred) self.inputs += self.vars self.inputs = list(set(self.inputs)) self.trans = pred return True def is_init(self, body, head): for f in body.children(): if self.is_inv(f) is not None: return False inv = self.is_inv(head) if inv is None: return False self.init = self.subst_vars("x", inv, body) return True def subst_vars(self, prefix, inv, fml): subst = self.mk_subst(prefix, inv) self.vars = [ v for (k,v) in subst ] return substitute(fml, subst) def mk_subst(self, prefix, inv): self.index = 0 if self.is_inv(inv) is not None: return [(f, self.mk_bool(prefix)) for f in inv.children()] else: vars = self.get_vars(inv) return [(f, self.mk_bool(prefix)) for f in vars] def mk_bool(self, prefix): self.index += 1 return Bool("%s%d" % (prefix, self.index)) def get_vars(self, f, rs=[]): if is_var(f): return z3util.vset(rs + [f], str) else: for f_ in f.children(): rs = self.get_vars(f_, rs) return z3util.vset(rs, str) # Produce a finite domain solver. # The theory QF_FD covers bit-vector formulas # and pseudo-Boolean constraints. # By default cardinality and pseudo-Boolean # constraints are converted to clauses. To override # this default for cardinality constraints # we set sat.cardinality.solver to True def fd_solver(): s = SolverFor("QF_FD") s.set("sat.cardinality.solver", True) return s # negate, avoid double negation def negate(f): if is_not(f): return f.arg(0) else: return Not(f) def cube2clause(cube): return Or([negate(f) for f in cube]) class State: def __init__(self, s): self.R = set([]) self.solver = s def add(self, clause): if clause not in self.R: self.R |= { clause } self.solver.add(clause) def is_seq(f): return isinstance(f, list) or isinstance(f, tuple) or isinstance(f, AstVector) # Check if the initial state is bad def check_disjoint(a, b): s = fd_solver() s.add(a) s.add(b) return unsat == s.check() # Remove clauses that are subsumed def prune(R): removed = set([]) s = fd_solver() for f1 in R: s.push() for f2 in R: if f2 not in removed: s.add(Not(f2) if f1.eq(f2) else f2) if s.check() == unsat: removed |= { f1 } s.pop() return R - removed # Quip variant of IC3 must = True may = False class QLemma: def __init__(self, c): self.cube = c self.clause = cube2clause(c) self.bad = False def __hash__(self): return hash(tuple(set(self.cube))) def __eq__(self, qlemma2): if set(self.cube) == set(qlemma2.cube) and self.bad == qlemma2.bad: return True else: return False def __ne__(): if not self.__eq__(self, qlemma2): return True else: return False class QGoal: def __init__(self, cube, parent, level, must, encounter): self.level = level self.cube = cube self.parent = parent self.must = must def __lt__(self, other): return self.level < other.level class QReach: # it is assumed that there is a single initial state # with all latches set to 0 in hardware design, so # here init will always give a state where all variable are set to 0 def __init__(self, init, xs): self.xs = xs self.constant_xs = [Not(x) for x in self.xs] s = fd_solver() s.add(init) is_sat = s.check() assert is_sat == sat m = s.model() # xs is a list, "for" will keep the order when iterating self.states = numpy.array([[False for x in self.xs]]) # all set to False assert not numpy.max(self.states) # since all element is False, so maximum should be False # check if new state exists def is_exist(self, state): if state in self.states: return True return False def enumerate(self, i, state_b, state): while i < len(state) and state[i] not in self.xs: i += 1 if i >= len(state): if state_b.tolist() not in self.states.tolist(): self.states = numpy.append(self.states, [state_b], axis = 0) return state_b else: return None state_b[i] = False if self.enumerate(i+1, state_b, state) is not None: return state_b else: state_b[i] = True return self.enumerate(i+1, state_b, state) def is_full_state(self, state): for i in range(len(self.xs)): if state[i] in self.xs: return False return True def add(self, cube): state = self.cube2partial_state(cube) assert len(state) == len(self.xs) if not self.is_exist(state): return None if self.is_full_state(state): self.states = numpy.append(self.states, [state], axis = 0) else: # state[i] is instance, state_b[i] is boolean state_b = numpy.array(state) for i in range(len(state)): # state is of same length as self.xs # i-th literal in state hasn't been assigned value # init un-assigned literals in state_b as True # make state_b only contain boolean value if state[i] in self.xs: state_b[i] = True else: state_b[i] = is_true(state[i]) if self.enumerate(0, state_b, state) is not None: lits_to_remove = set([negate(f) for f in list(set(cube) - set(self.constant_xs))]) self.constant_xs = list(set(self.constant_xs) - lits_to_remove) return state return None def cube2partial_state(self, cube): s = fd_solver() s.add(And(cube)) is_sat = s.check() assert is_sat == sat m = s.model() state = numpy.array([m.eval(x) for x in self.xs]) return state def state2cube(self, s): result = copy.deepcopy(self.xs) # x1, x2, ... for i in range(len(self.xs)): if not s[i]: result[i] = Not(result[i]) return result def intersect(self, cube): state = self.cube2partial_state(cube) mask = True for i in range(len(self.xs)): if is_true(state[i]) or is_false(state[i]): mask = (self.states[:, i] == state[i]) & mask intersects = numpy.reshape(self.states[mask], (-1, len(self.xs))) if intersects.size > 0: return And(self.state2cube(intersects[0])) # only need to return one single intersect return None class Quip: def __init__(self, init, trans, goal, x0, inputs, xn): self.x0 = x0 self.inputs = inputs self.xn = xn self.init = init self.bad = goal self.trans = trans self.min_cube_solver = fd_solver() self.min_cube_solver.add(Not(trans)) self.goals = [] s = State(fd_solver()) s.add(init) s.solver.add(trans) # check if a bad state can be reached in one step from current level self.states = [s] self.s_bad = fd_solver() self.s_good = fd_solver() self.s_bad.add(self.bad) self.s_good.add(Not(self.bad)) self.reachable = QReach(self.init, x0) self.frames = [] # frames is a 2d list, each row (representing level) is a set containing several (clause, bad) pairs self.count_may = 0 def next(self, f): if is_seq(f): return [self.next(f1) for f1 in f] return substitute(f, zip(self.x0, self.xn)) def prev(self, f): if is_seq(f): return [self.prev(f1) for f1 in f] return substitute(f, zip(self.xn, self.x0)) def add_solver(self): s = fd_solver() s.add(self.trans) self.states += [State(s)] def R(self, i): return And(self.states[i].R) def value2literal(self, m, x): value = m.eval(x) if is_true(value): return x if is_false(value): return Not(x) return None def values2literals(self, m, xs): p = [self.value2literal(m, x) for x in xs] return [x for x in p if x is not None] def project0(self, m): return self.values2literals(m, self.x0) def projectI(self, m): return self.values2literals(m, self.inputs) def projectN(self, m): return self.values2literals(m, self.xn) # Block a cube by asserting the clause corresponding to its negation def block_cube(self, i, cube): self.assert_clause(i, cube2clause(cube)) # Add a clause to levels 1 until i def assert_clause(self, i, clause): for j in range(1, i + 1): self.states[j].add(clause) assert str(self.states[j].solver) != str([False]) # minimize cube that is core of Dual solver. # this assumes that props & cube => Trans # which means props & cube can only give us a Tr in Trans, # and it will never make !Trans sat def minimize_cube(self, cube, inputs, lits): # min_cube_solver has !Trans (min_cube.solver.add(!Trans)) is_sat = self.min_cube_solver.check(lits + [c for c in cube] + [i for i in inputs]) assert is_sat == unsat # unsat_core gives us some lits which make Tr sat, # so that we can ignore other lits and include more states core = self.min_cube_solver.unsat_core() assert core return [c for c in core if c in set(cube)] # push a goal on a heap def push_heap(self, goal): heapq.heappush(self.goals, (goal.level, goal)) # make sure cube to be blocked excludes all reachable states def check_reachable(self, cube): s = fd_solver() for state in self.reachable.states: s.push() r = self.reachable.state2cube(state) s.add(And(self.prev(r))) s.add(self.prev(cube)) is_sat = s.check() s.pop() if is_sat == sat: # if sat, it means the cube to be blocked contains reachable states # so it is an invalid cube return False # if all fail, is_sat will be unsat return True # Rudimentary generalization: # If the cube is already unsat with respect to transition relation # extract a core (not necessarily minimal) # otherwise, just return the cube. def generalize(self, cube, f): s = self.states[f - 1].solver if unsat == s.check(cube): core = s.unsat_core() if self.check_reachable(core): return core, f return cube, f def valid_reachable(self, level): s = fd_solver() s.add(self.init) for i in range(level): s.add(self.trans) for state in self.reachable.states: s.push() s.add(And(self.next(self.reachable.state2cube(state)))) print self.reachable.state2cube(state) print s.check() s.pop() def lemmas(self, level): return [(l.clause, l.bad) for l in self.frames[level]] # whenever a new reachable state is found, we use it to mark some existing lemmas as bad lemmas def mark_bad_lemmas(self, new): s = fd_solver() reset = False for frame in self.frames: for lemma in frame: s.push() s.add(lemma.clause) is_sat = s.check(new) if is_sat == unsat: reset = True lemma.bad = True s.pop() if reset: self.states = [self.states[0]] for i in range(1, len(self.frames)): self.add_solver() for lemma in self.frames[i]: if not lemma.bad: self.states[i].add(lemma.clause) # prev & tras -> r', such that r' intersects with cube def add_reachable(self, prev, cube): s = fd_solver() s.add(self.trans) s.add(prev) s.add(self.next(And(cube))) is_sat = s.check() assert is_sat == sat m = s.model() new = self.projectN(m) state = self.reachable.add(self.prev(new)) # always add as non-primed if state is not None: # if self.states do not have new state yet self.mark_bad_lemmas(self.prev(new)) # Check if the negation of cube is inductive at level f def is_inductive(self, f, cube): s = self.states[f - 1].solver s.push() s.add(self.prev(Not(And(cube)))) is_sat = s.check(cube) if is_sat == sat: m = s.model() s.pop() if is_sat == sat: cube = self.next(self.minimize_cube(self.project0(m), self.projectI(m), self.projectN(m))) elif is_sat == unsat: cube, f = self.generalize(cube, f) cube = self.next(cube) return cube, f, is_sat # Determine if there is a cube for the current state # that is potentially reachable. def unfold(self, level): core = [] self.s_bad.push() R = self.R(level) self.s_bad.add(R) # check if current frame intersects with bad states, no trans is_sat = self.s_bad.check() if is_sat == sat: m = self.s_bad.model() cube = self.project0(m) props = cube + self.projectI(m) self.s_good.push() self.s_good.add(R) is_sat2 = self.s_good.check(props) assert is_sat2 == unsat core = self.s_good.unsat_core() assert core core = [c for c in core if c in set(cube)] self.s_good.pop() self.s_bad.pop() return is_sat, core # A state s0 and level f0 such that # not(s0) is f0-1 inductive def quip_blocked(self, s0, f0): self.push_heap(QGoal(self.next(s0), None, f0, must, 0)) while self.goals: f, g = heapq.heappop(self.goals) sys.stdout.write("%d." % f) if not g.must: self.count_may -= 1 sys.stdout.flush() if f == 0: if g.must: s = fd_solver() s.add(self.init) s.add(self.prev(g.cube)) # since init is a complete assignment, so g.cube must equal to init in sat solver assert is_sat == s.check() if verbose: print("") return g self.add_reachable(self.init, g.parent.cube) continue r0 = self.reachable.intersect(self.prev(g.cube)) if r0 is not None: if g.must: if verbose: print "" s = fd_solver() s.add(self.trans) # make it as a concrete reachable state # intersect returns an And(...), so use children to get cube list g.cube = r0.children() while True: is_sat = s.check(self.next(g.cube)) assert is_sat == sat r = self.next(self.project0(s.model())) r = self.reachable.intersect(self.prev(r)) child = QGoal(self.next(r.children()), g, 0, g.must, 0) g = child if not check_disjoint(self.init, self.prev(g.cube)): # g is init, break the loop break init = g while g.parent is not None: g.parent.level = g.level + 1 g = g.parent return init if g.parent is not None: self.add_reachable(r0, g.parent.cube) continue cube = None is_sat = sat f_1 = len(self.frames) - 1 while f_1 >= f: for l in self.frames[f_1]: if not l.bad and len(l.cube) > 0 and set(l.cube).issubset(g.cube): cube = l.cube is_sat == unsat break f_1 -= 1 if cube is None: cube, f_1, is_sat = self.is_inductive(f, g.cube) if is_sat == unsat: self.frames[f_1].add(QLemma(self.prev(cube))) self.block_cube(f_1, self.prev(cube)) if f_1 < f0: # learned clause might also be able to block same bad states in higher level if set(list(cube)) != set(list(g.cube)): self.push_heap(QGoal(cube, None, f_1 + 1, may, 0)) self.count_may += 1 else: # re-queue g.cube in higher level, here g.parent is simply for tracking down the trace when output. self.push_heap(QGoal(g.cube, g.parent, f_1 + 1, g.must, 0)) if not g.must: self.count_may += 1 else: # qcube is a predecessor of g qcube = QGoal(cube, g, f_1 - 1, g.must, 0) if not g.must: self.count_may += 1 self.push_heap(qcube) if verbose: print("") return None # Check if there are two states next to each other that have the same clauses. def is_valid(self): i = 1 inv = None while True: # self.states[].R contains full lemmas # self.frames[] contains delta-encoded lemmas while len(self.states) <= i+1: self.add_solver() while len(self.frames) <= i+1: self.frames.append(set()) duplicates = set([]) for l in self.frames[i+1]: if l in self.frames[i]: duplicates |= {l} self.frames[i] = self.frames[i] - duplicates pushed = set([]) for l in (self.frames[i] - self.frames[i+1]): if not l.bad: s = self.states[i].solver s.push() s.add(self.next(Not(l.clause))) s.add(l.clause) is_sat = s.check() s.pop() if is_sat == unsat: self.frames[i+1].add(l) self.states[i+1].add(l.clause) pushed |= {l} self.frames[i] = self.frames[i] - pushed if (not (self.states[i].R - self.states[i+1].R) and len(self.states[i].R) != 0): inv = prune(self.states[i].R) F_inf = self.frames[i] j = i + 1 while j < len(self.states): for l in F_inf: self.states[j].add(l.clause) j += 1 self.frames[len(self.states)-1] = F_inf self.frames[i] = set([]) break elif (len(self.states[i].R) == 0 and len(self.states[i+1].R) == 0): break i += 1 if inv is not None: self.s_bad.push() self.s_bad.add(And(inv)) is_sat = self.s_bad.check() if is_sat == unsat: self.s_bad.pop() return And(inv) self.s_bad.pop() return None def run(self): if not check_disjoint(self.init, self.bad): return "goal is reached in initial state" level = 0 while True: inv = self.is_valid() # self.add_solver() here if inv is not None: return inv is_sat, cube = self.unfold(level) if is_sat == unsat: level += 1 if verbose: print("Unfold %d" % level) sys.stdout.flush() elif is_sat == sat: cex = self.quip_blocked(cube, level) if cex is not None: return cex else: return is_sat def test(file): h2t = Horn2Transitions() h2t.parse(file) if verbose: print("Test file: %s") % file mp = Quip(h2t.init, h2t.trans, h2t.goal, h2t.xs, h2t.inputs, h2t.xns) start_time = time.time() result = mp.run() end_time = time.time() if isinstance(result, QGoal): g = result if verbose: print("Trace") while g: if verbose: print(g.level, g.cube) g = g.parent print("--- used %.3f seconds ---" % (end_time - start_time)) validate(mp, result, mp.trans) return if isinstance(result, ExprRef): if verbose: print("Invariant:\n%s " % result) print("--- used %.3f seconds ---" % (end_time - start_time)) validate(mp, result, mp.trans) return print(result) def validate(var, result, trans): if isinstance(result, QGoal): g = result s = fd_solver() s.add(trans) while g.parent is not None: s.push() s.add(var.prev(g.cube)) s.add(var.next(g.parent.cube)) assert sat == s.check() s.pop() g = g.parent if verbose: print "--- validation succeed ----" return if isinstance(result, ExprRef): inv = result s = fd_solver() s.add(trans) s.push() s.add(var.prev(inv)) s.add(Not(var.next(inv))) assert unsat == s.check() s.pop() cube = var.prev(var.init) step = 0 while True: step += 1 # too many steps to reach invariant if step > 1000: if verbose: print "--- validation failed --" return if not check_disjoint(var.prev(cube), var.prev(inv)): # reach invariant break s.push() s.add(cube) assert s.check() == sat cube = var.projectN(s.model()) s.pop() if verbose: print "--- validation succeed ----" return test("data/horn1.smt2") test("data/horn2.smt2") test("data/horn3.smt2") test("data/horn4.smt2") test("data/horn5.smt2") # test("data/horn6.smt2") # not able to finish
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/mini_quip.py
mini_quip.py
# Strategies High-performance solvers, such as Z3, contain many tightly integrated, handcrafted heuristic combinations of algorithmic proof methods. While these heuristic combinations tend to be highly tuned for known classes of problems, they may easily perform very badly on new classes of problems. This issue is becoming increasingly pressing as solvers begin to gain the attention of practitioners in diverse areas of science and engineering. In many cases, changes to the solver heuristics can make a tremendous difference. More information on Z3 is available from https://github.com/z3prover/z3.git ## Introduction Z3 implements a methodology for orchestrating reasoning engines where "big" symbolic reasoning steps are represented as functions known as tactics, and tactics are composed using combinators known as tacticals. Tactics process sets of formulas called Goals. When a tactic is applied to some goal G, four different outcomes are possible. The tactic succeeds in showing G to be satisfiable (i.e., feasible); succeeds in showing G to be unsatisfiable (i.e., infeasible); produces a sequence of subgoals; or fails. When reducing a goal G to a sequence of subgoals G1, ..., Gn, we face the problem of model conversion. A model converter construct a model for G using a model for some subgoal Gi. In the following example, we create a goal g consisting of three formulas, and a tactic t composed of two built-in tactics: simplify and solve-eqs. The tactic simplify apply transformations equivalent to the ones found in the command simplify. The tactic solver-eqs eliminate variables using Gaussian elimination. Actually, solve-eqs is not restricted only to linear arithmetic. It can also eliminate arbitrary variables. Then, combinator Then applies simplify to the input goal and solve-eqs to each subgoal produced by simplify. In this example, only one subgoal is produced. ``` !pip install "z3-solver" from z3 import * x, y = Reals('x y') g = Goal() g.add(x > 0, y > 0, x == y + 2) print(g) t1 = Tactic('simplify') t2 = Tactic('solve-eqs') t = Then(t1, t2) print(t(g)) ``` In the example above, variable x is eliminated, and is not present the resultant goal. In Z3, we say a clause is any constraint of the form Or(f_1, ..., f_n). The tactic split-clause will select a clause Or(f_1, ..., f_n) in the input goal, and split it n subgoals. One for each subformula f_i. ``` x, y = Reals('x y') g = Goal() g.add(Or(x < 0, x > 0), x == y + 1, y < 0) t = Tactic('split-clause') r = t(g) for g in r: print(g) ``` Tactics Z3 comes equipped with many built-in tactics. The command describe_tactics() provides a short description of all built-in tactics. describe_tactics() Z3Py comes equipped with the following tactic combinators (aka tacticals): * Then(t, s) applies t to the input goal and s to every subgoal produced by t. * OrElse(t, s) first applies t to the given goal, if it fails then returns the result of s applied to the given goal. * Repeat(t) Keep applying the given tactic until no subgoal is modified by it. * Repeat(t, n) Keep applying the given tactic until no subgoal is modified by it, or the number of iterations is greater than n. * TryFor(t, ms) Apply tactic t to the input goal, if it does not return in ms milliseconds, it fails. * With(t, params) Apply the given tactic using the given parameters. The following example demonstrate how to use these combinators. ``` x, y, z = Reals('x y z') g = Goal() g.add(Or(x == 0, x == 1), Or(y == 0, y == 1), Or(z == 0, z == 1), x + y + z > 2) # Split all clauses" split_all = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) print(split_all(g)) split_at_most_2 = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')), 1) print(split_at_most_2(g)) # Split all clauses and solve equations split_solve = Then(Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))), Tactic('solve-eqs')) print(split_solve(g)) ``` In the tactic split_solver, the tactic solve-eqs discharges all but one goal. Note that, this tactic generates one goal: the empty goal which is trivially satisfiable (i.e., feasible) The list of subgoals can be easily traversed using the Python for statement. ``` x, y, z = Reals('x y z') g = Goal() g.add(Or(x == 0, x == 1), Or(y == 0, y == 1), Or(z == 0, z == 1), x + y + z > 2) # Split all clauses" split_all = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) for s in split_all(g): print(s) ``` A tactic can be converted into a solver object using the method solver(). If the tactic produces the empty goal, then the associated solver returns sat. If the tactic produces a single goal containing False, then the solver returns unsat. Otherwise, it returns unknown. ``` bv_solver = Then('simplify', 'solve-eqs', 'bit-blast', 'sat').solver() x, y = BitVecs('x y', 16) solve_using(bv_solver, x | y == 13, x > y) ``` In the example above, the tactic bv_solver implements a basic bit-vector solver using equation solving, bit-blasting, and a propositional SAT solver. Note that, the command Tactic is suppressed. All Z3Py combinators automatically invoke Tactic command if the argument is a string. Finally, the command solve_using is a variant of the solve command where the first argument specifies the solver to be used. In the following example, we use the solver API directly instead of the command solve_using. We use the combinator With to configure our little solver. We also include the tactic aig which tries to compress Boolean formulas using And-Inverted Graphs. ``` bv_solver = Then(With('simplify', mul2concat=True), 'solve-eqs', 'bit-blast', 'aig', 'sat').solver() x, y = BitVecs('x y', 16) bv_solver.add(x*32 + y == 13, x & y < 10, y > -100) print(bv_solver.check()) m = bv_solver.model() print(m) print(x*32 + y, "==", m.evaluate(x*32 + y)) print(x & y, "==", m.evaluate(x & y)) ``` The tactic smt wraps the main solver in Z3 as a tactic. ``` x, y = Ints('x y') s = Tactic('smt').solver() s.add(x > y + 1) print(s.check()) print(s.model()) ``` Now, we show how to implement a solver for integer arithmetic using SAT. The solver is complete only for problems where every variable has a lower and upper bound. ``` s = Then(With('simplify', arith_lhs=True, som=True), 'normalize-bounds', 'lia2pb', 'pb2bv', 'bit-blast', 'sat').solver() x, y, z = Ints('x y z') solve_using(s, x > 0, x < 10, y > 0, y < 10, z > 0, z < 10, 3*y + 2*x == z) # It fails on the next example (it is unbounded) s.reset() solve_using(s, 3*y + 2*x == z) ``` Tactics can be combined with solvers. For example, we can apply a tactic to a goal, produced a set of subgoals, then select one of the subgoals and solve it using a solver. The next example demonstrates how to do that, and how to use model converters to convert a model for a subgoal into a model for the original goal. ``` t = Then('simplify', 'normalize-bounds', 'solve-eqs') x, y, z = Ints('x y z') g = Goal() g.add(x > 10, y == x + 3, z > y) r = t(g) # r contains only one subgoal print(r) s = Solver() s.add(r[0]) print(s.check()) # Model for the subgoal print(s.model()) # Model for the original goal print(r[0].convert_model(s.model())) ``` ## Probes Probes (aka formula measures) are evaluated over goals. Boolean expressions over them can be built using relational operators and Boolean connectives. The tactic FailIf(cond) fails if the given goal does not satisfy the condition cond. Many numeric and Boolean measures are available in Z3Py. The command describe_probes() provides the list of all built-in probes. ``` describe_probes() ``` In the following example, we build a simple tactic using FailIf. It also shows that a probe can be applied directly to a goal. ``` x, y, z = Reals('x y z') g = Goal() g.add(x + y + z > 0) p = Probe('num-consts') print("num-consts:", p(g)) t = FailIf(p > 2) try: t(g) except Z3Exception: print("tactic failed") print("trying again...") g = Goal() g.add(x + y > 0) print(t(g)) ``` Z3Py also provides the combinator (tactical) If(p, t1, t2) which is a shorthand for: OrElse(Then(FailIf(Not(p)), t1), t2) The combinator When(p, t) is a shorthand for: If(p, t, 'skip') The tactic skip just returns the input goal. The following example demonstrates how to use the If combinator. ``` x, y, z = Reals('x y z') g = Goal() g.add(x**2 - y**2 >= 0) p = Probe('num-consts') t = If(p > 2, 'simplify', 'factor') print(t(g)) g = Goal() g.add(x + x + y + z >= 0, x**2 - y**2 >= 0) print(t(g)) ```
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/tutorial/jupyter/strategies.ipynb
strategies.ipynb
# Z3 API in Python Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silicon analysis), and geometrical problems. This tutorial demonstrates the main capabilities of Z3Py: the Z3 API in Python. No Python background is needed to read this tutorial. However, it is useful to learn Python (a fun language!) at some point, and there are many excellent free resources for doing so (Python Tutorial). The Z3 distribution also contains the C, C++, .Net, Java and OCaml APIs. The source code of Z3Py is available in the Z3 distribution on https://github.com/z3prover/z3.git where you are invited to download, use and update the code, add pull requests and file issues on usability, bugs and features. ## First things first Import Z3 ``` from z3 import * ``` # Getting Started Let us start with the following simple example: ``` x = Int('x') y = Int('y') solve(x > 2, y < 10, x + 2*y == 7) ``` The function Int('x') creates an integer variable in Z3 named x. The solve function solves a system of constraints. The example above uses two variables x and y, and three constraints. Z3Py like Python uses = for assignment. The operators <, <=, >, >=, == and != for comparison. In the example above, the expression x + 2*y == 7 is a Z3 constraint. Z3 can solve and crunch formulas. The next examples show how to use the Z3 formula/expression simplifier. ``` x = Int('x') y = Int('y') print(simplify(x + y + 2*x + 3)) print(simplify(x < y + x + 2)) print(simplify(And(x + 1 >= 3, x**2 + x**2 + y**2 + 2 >= 5))) ``` By default, Z3Py (for the web) displays formulas and expressions using mathematical notation. As usual, ∧ is the logical and, ∨ is the logical or, and so on. The command set_option(html_mode=False) makes all formulas and expressions to be displayed in Z3Py notation. This is also the default mode for the offline version of Z3Py that comes with the Z3 distribution. ``` x = Int('x') y = Int('y') print(x**2 + y**2 >= 1) set_option(html_mode=False) print(x**2 + y**2 >= 1) ``` ### html mode: use copy paste into a markdown-cell After execution ``` set_option(html_mode=True) print(x**2 + y**2 >= 1) ``` ### copied from the printed result: x<sup>2</sup> + y<sup>2</sup> &ge; 1 Z3 provides functions for traversing expressions. ``` x = Int('x') y = Int('y') n = x + y >= 3 print("num args: ", n.num_args()) print("children: ", n.children()) print("1st child:", n.arg(0)) print("2nd child:", n.arg(1)) print("operator: ", n.decl()) print("op name: ", n.decl().name()) ``` Z3 provides all basic mathematical operations. Z3Py uses the same operator precedence of the Python language. Like Python, ** is the power operator. Z3 can solve nonlinear polynomial constraints. ``` x = Real('x') y = Real('y') solve(x**2 + 0.12 * y**2 > 3, x**3 + y < 5) ``` The procedure Real('x') creates the real variable x. Z3Py can represent arbitrarily large integers, rational numbers (like in the example above), and irrational algebraic numbers. An irrational algebraic number is a root of a polynomial with integer coefficients. Internally, Z3 represents all these numbers precisely. The irrational numbers are displayed in decimal notation for making it easy to read the results. ``` x = Real('x') y = Real('y') solve(x**2 + y**2 == 3, x**3 == 2) set_option(precision=30) print("Solving, and displaying result with 30 decimal places") solve(x**2 + y**2 == 3, x**3 == 2) ``` # The procedure <font color='green'>set_option</font> is used to configure the Z3 environment. It is used to set global configuration options such as how the result is displayed. The option set_option(precision=30) sets the number of decimal places used when displaying results. The <font color='red' size=18>?</font> mark in 1.259921049894873164767210607278? indicates the output is truncated. The following example demonstrates a common mistake. The expression 3/2 is a Python integer and not a Z3 rational number. The example also shows different ways to create rational numbers in Z3Py. The procedure Q(num, den) creates a Z3 rational where num is the numerator and den is the denominator. The RealVal(1) creates a Z3 real number representing the number 1. ``` print(1/3) print(RealVal(1)/3) x = Real('x') print(x + 1/3) print(x + "1/3") print(x + 0.25) ``` Rational numbers can also be displayed in decimal notation. ``` x = Real('x') solve(3*x == 1) set_option(rational_to_decimal=True) solve(3*x == 1) set_option(precision=20) solve(3*x == 1) set_option(rational_to_decimal=False) solve(6*x == 37) ``` A system of constraints may not have a solution. In this case, we say the system is unsatisfiable. ``` x = Real('x') solve(x > 4, x < 0) ``` Like in Python, comments begin with the hash character # and are terminated by the end of line. Z3Py does not support comments that span more than one line. Boolean Logic ``` set_option(html_mode=False) # This is a comment x = Real('x') # comment: creating x print(x**2 + 2*x + 2) # comment: printing polynomial) ``` # Boolean Logic Z3 supports Boolean operators: And, Or, Not, Implies (implication), If (if-then-else). Bi-implications are represented using equality ==. The following example shows how to solve a simple set of Boolean constraints. ``` p = Bool('p') q = Bool('q') r = Bool('r') solve(Implies(p, q), r == Not(q), Or(Not(p), r)) ``` The Python Boolean constants True and False can be used to build Z3 Boolean expressions. ``` p = Bool('p') q = Bool('q') print(And(p, q, True)) print(simplify(And(p, q, True))) print(simplify(And(p, False))) ``` The following example uses a combination of polynomial and Boolean constraints. ``` p = Bool('p') x = Real('x') solve(Or(x < 5, x > 10), Or(p, x**2 == 2), Not(p)) ``` # Solvers Z3 provides different solvers. The command solve, used in the previous examples, is implemented using the Z3 solver API. The implementation can be found in the file z3.py in the Z3 distribution. The following example demonstrates the basic Solver API. ``` x = Int('x') y = Int('y') s = Solver() print(s) s.add(x > 10, y == x + 2) print(s) print("Solving constraints in the solver s ...") print(s.check()) print("Create a new scope...") s.push() s.add(y < 11) print(s) print("Solving updated set of constraints...") print(s.check()) print("Restoring state...") s.pop() print(s) print("Solving restored set of constraints...") print(s.check()) ``` # Info ... The command Solver() creates a general purpose solver. Constraints can be added using the method add. We say the constraints have been asserted in the solver. The method check() solves the asserted constraints. The result is sat (satisfiable) if a solution was found. The result is unsat (unsatisfiable) if no solution exists. We may also say the system of asserted constraints is infeasible. Finally, a solver may fail to solve a system of constraints and unknown is returned. In some applications, we want to explore several similar problems that share several constraints. We can use the commands push and pop for doing that. Each solver maintains a stack of assertions. The command push creates a new scope by saving the current stack size. The command pop removes any assertion performed between it and the matching push. The check method always operates on the content of solver assertion stack. The following example shows an example that Z3 cannot solve. The solver returns unknown in this case. Recall that Z3 can solve nonlinear polynomial constraints, but 2**x is not a polynomial. ``` x = Real('x') s = Solver() s.add(2**x == 3) print(s.check()) ``` The following example shows how to traverse the constraints asserted into a solver, and how to collect performance statistics for the check method. ``` x = Real('x') y = Real('y') s = Solver() s.add(x > 1, y > 1, Or(x + y > 3, x - y < 2)) print("asserted constraints...") for c in s.assertions(): print(c) print(s.check()) print("statistics for the last check method...") print(s.statistics()) # Traversing statistics for k, v in s.statistics(): print("%s : %s" % (k, v)) ``` The command check returns sat when Z3 finds a solution for the set of asserted constraints. We say Z3 satisfied the set of constraints. We say the solution is a model for the set of asserted constraints. A model is an interpretation that makes each asserted constraint true. ### The following example shows the basic methods for inspecting models. ``` x, y, z = Reals('x y z') s = Solver() s.add(x > 1, y > 1, x + y > 3, z - x < 10) print(s.check()) m = s.model() print("x = %s" % m[x]) print("traversing model...") for d in m.decls(): print("%s = %s" % (d.name(), m[d])) ``` In the example above, the function Reals('x y z') creates the variables. x, y and z. It is shorthand for: ``` x = Real('x') y = Real('y') z = Real('z') ``` The expression m[x] returns the interpretation of x in the model m. The expression "%s = %s" % (d.name(), m[d]) returns a string where the first %s is replaced with the name of d (i.e., d.name()), and the second %s with a textual representation of the interpretation of d (i.e., m[d]). Z3Py automatically converts Z3 objects into a textual representation when needed. # Arithmetic Z3 supports real and integer variables. They can be mixed in a single problem. Like most programming languages, Z3Py will automatically add coercions converting integer expressions to real ones when needed. The following example demonstrates different ways to declare integer and real variables. ``` x = Real('x') y = Int('y') a, b, c = Reals('a b c') s, r = Ints('s r') print(x + y + 1 + (a + s)) print(ToReal(y) + c) ``` The function ToReal casts an integer expression into a real expression. Z3Py supports all basic arithmetic operations. ``` a, b, c = Ints('a b c') d, e = Reals('d e') solve(a > b + 2, a == 2*c + 10, c + b <= 1000, d >= e) ``` The command simplify applies simple transformations on Z3 expressions. ``` x, y = Reals('x y') # Put expression in sum-of-monomials form t = simplify((x + y)**3, som=True) print(t) # Use power operator t = simplify(t, mul_to_power=True) print(t) ``` The command help_simplify() prints all available options. Z3Py allows users to write option in two styles. The Z3 internal option names start with : and words are separated by -. These options can be used in Z3Py. Z3Py also supports Python-like names, where : is suppressed and - is replaced with _. The following example demonstrates how to use both styles. ``` x, y = Reals('x y') # Using Z3 native option names print(simplify(x == y + 2, ':arith-lhs', True)) # Using Z3Py option names print(simplify(x == y + 2, arith_lhs=True)) print("\nAll available options:") help_simplify() ``` # large numbers Z3Py supports arbitrarily large numbers. The following example demonstrates how to perform basic arithmetic using larger integer, rational and irrational numbers. Z3Py only supports algebraic irrational numbers. Algebraic irrational numbers are sufficient for presenting the solutions of systems of polynomial constraints. Z3Py will always display irrational numbers in decimal notation since it is more convenient to read. The internal representation can be extracted using the method sexpr(). It displays Z3 internal representation for mathematical formulas and expressions in s-expression (Lisp-like) notation. ``` x, y = Reals('x y') solve(x + 10000000000000000000000 == y, y > 20000000000000000) print(Sqrt(2) + Sqrt(3)) print(simplify(Sqrt(2) + Sqrt(3))) print(simplify(Sqrt(2) + Sqrt(3)).sexpr()) # The sexpr() method is available for any Z3 expression print((x + Sqrt(y) * 2).sexpr()) ``` # Machine Arithmetic Modern CPUs and main-stream programming languages use arithmetic over fixed-size bit-vectors. Machine arithmetic is available in Z3Py as Bit-Vectors. They implement the precise semantics of unsigned and of signed two-complements arithmetic. The following example demonstrates how to create bit-vector variables and constants. The function BitVec('x', 16) creates a bit-vector variable in Z3 named x with 16 bits. For convenience, integer constants can be used to create bit-vector expressions in Z3Py. The function BitVecVal(10, 32) creates a bit-vector of size 32 containing the value 10. ``` x = BitVec('x', 16) y = BitVec('y', 16) print(x + 2) # Internal representation print((x + 2).sexpr()) # -1 is equal to 65535 for 16-bit integers print(simplify(x + y - 1)) # Creating bit-vector constants a = BitVecVal(-1, 16) b = BitVecVal(65535, 16) print(simplify(a == b)) a = BitVecVal(-1, 32) b = BitVecVal(65535, 32) # -1 is not equal to 65535 for 32-bit integers print(simplify(a == b)) ``` # In contrast to programming languages, such as C, C++, C#, Java, there is no distinction between signed and unsigned bit-vectors as numbers. Instead, Z3 provides special signed versions of arithmetical operations where it makes a difference whether the bit-vector is treated as signed or unsigned. In Z3Py, the operators <, <=, >, >=, /, % and >> correspond to the signed versions. The corresponding unsigned operators are ULT, ULE, UGT, UGE, UDiv, URem and LShR. ``` # Create to bit-vectors of size 32 x, y = BitVecs('x y', 32) solve(x + y == 2, x > 0, y > 0) # Bit-wise operators # & bit-wise and # | bit-wise or # ~ bit-wise not solve(x & y == ~y) solve(x < 0) # using unsigned version of < solve(ULT(x, 0)) ``` The operator >> is the arithmetic shift right, and << is the shift left. The logical shift right is the operator LShR. ``` # Create to bit-vectors of size 32 x, y = BitVecs('x y', 32) solve(x >> 2 == 3) solve(x << 2 == 3) solve(x << 2 == 24) ``` # Functions Unlike programming languages, where functions have side-effects, can throw exceptions, or never return, functions in Z3 have no side-effects and are total. That is, they are defined on all input values. This includes functions, such as division. Z3 is based on first-order logic. Given a constraints such as x + y > 3, we have been saying that x and y are variables. In many textbooks, x and y are called uninterpreted constants. That is, they allow any interpretation that is consistent with the constraint x + y > 3. More precisely, function and constant symbols in pure first-order logic are uninterpreted or free, which means that no a priori interpretation is attached. This is in contrast to functions belonging to the signature of theories, such as arithmetic where the function + has a fixed standard interpretation (it adds two numbers). Uninterpreted functions and constants are maximally flexible; they allow any interpretation that is consistent with the constraints over the function or constant. To illustrate uninterpreted functions and constants let us the uninterpreted integer constants (aka variables) x, y. Finally let f be an uninterpreted function that takes one argument of type (aka sort) integer and results in an integer value. The example illustrates how one can force an interpretation where f applied twice to x results in x again, but f applied once to x is different from x. ``` x = Int('x') y = Int('y') f = Function('f', IntSort(), IntSort()) solve(f(f(x)) == x, f(x) == y, x != y) ``` The solution (interpretation) for f should be read as f(0) is 1, f(1) is 0, and f(a) is 1 for all a different from 0 and 1. In Z3, we can also evaluate expressions in the model for a system of constraints. The following example shows how to use the evaluate method. ``` x = Int('x') y = Int('y') f = Function('f', IntSort(), IntSort()) s = Solver() s.add(f(f(x)) == x, f(x) == y, x != y) print(s.check()) m = s.model() print("f(f(x)) =", m.evaluate(f(f(x)))) print("f(x) =", m.evaluate(f(x))) #In Z3, we can also evaluate expressions in the model for a system of constraints. The following example shows how to use the evaluate method. x = Int('x') y = Int('y') f = Function('f', IntSort(), IntSort()) s = Solver() s.add(f(f(x)) == x, f(x) == y, x != y) print(s.check()) m = s.model() print("f(f(x)) =", m.evaluate(f(f(x)))) print("f(x) =", m.evaluate(f(x))) ``` # Satisfiability and Validity A formula/constraint F is valid if F always evaluates to true for any assignment of appropriate values to its uninterpreted symbols. A formula/constraint F is satisfiable if there is some assignment of appropriate values to its uninterpreted symbols under which F evaluates to true. Validity is about finding a proof of a statement; satisfiability is about finding a solution to a set of constraints. Consider a formula F containing a and b. We can ask whether F is valid, that is whether it is always true for any combination of values for a and b. If F is always true, then Not(F) is always false, and then Not(F) will not have any satisfying assignment (i.e., solution); that is, Not(F) is unsatisfiable. That is, F is valid precisely when Not(F) is not satisfiable (is unsatisfiable). Alternately, F is satisfiable if and only if Not(F) is not valid (is invalid). The following example proves the deMorgan's law. The following example redefines the Z3Py function prove that receives a formula as a parameter. This function creates a solver, adds/asserts the negation of the formula, and check if the negation is unsatisfiable. The implementation of this function is a simpler version of the Z3Py command prove. ``` p, q = Bools('p q') demorgan = And(p, q) == Not(Or(Not(p), Not(q))) print(demorgan) def prove(f): s = Solver() s.add(Not(f)) if s.check() == unsat: print("proved") else: print("failed to prove") print("Proving demorgan...") prove(demorgan) ``` # List comprehension Python supports list comprehensions. List comprehensions provide a concise way to create lists. They can be used to create Z3 expressions and problems in Z3Py. The following example demonstrates how to use Python list comprehensions in Z3Py. ``` # Create list [1, ..., 5] print([ x + 1 for x in range(5) ]) # Create two lists containing 5 integer variables X = [ Int('x%s' % i) for i in range(5) ] Y = [ Int('y%s' % i) for i in range(5) ] print(X) # Create a list containing X[i]+Y[i] X_plus_Y = [ X[i] + Y[i] for i in range(5) ] print(X_plus_Y) # Create a list containing X[i] > Y[i] X_gt_Y = [ X[i] > Y[i] for i in range(5) ] print(X_gt_Y) print(And(X_gt_Y)) # Create a 3x3 "matrix" (list of lists) of integer variables X = [ [ Int("x_%s_%s" % (i+1, j+1)) for j in range(3) ] for i in range(3) ] pp(X) ``` In the example above, the expression "x%s" % i returns a string where %s is replaced with the value of i. The command pp is similar to print, but it uses Z3Py formatter for lists and tuples instead of Python's formatter. Z3Py also provides functions for creating vectors of Boolean, Integer and Real variables. These functions are implemented using list comprehensions. ``` X = IntVector('x', 5) Y = RealVector('y', 5) P = BoolVector('p', 5) print(X) print(Y) print(P) print([ y**2 for y in Y ]) print(Sum([ y**2 for y in Y ])) ``` # Kinematic equations In high school, students learn the kinematic equations. These equations describe the mathematical relationship between displacement (d), time (t), acceleration (a), initial velocity (v_i) and final velocity (v_f). In Z3Py notation, we can write these equations as: ``` a, t ,v_i, v_f = Reals('a t v__i v__f') #missing in HTML? d == v_i * t + (a*t**2)/2, v_f == v_i + a*t v_f ``` ## Problem 1 Ima Hurryin is approaching a stoplight moving with a velocity of 30.0 m/s. The light turns yellow, and Ima applies the brakes and skids to a stop. If Ima's acceleration is -8.00 m/s2, then determine the displacement of the car during the skidding process. ``` d, a, t, v_i, v_f = Reals('d a t v__i v__f') equations = [ d == v_i * t + (a*t**2)/2, v_f == v_i + a*t, ] print("Kinematic equations:") print(equations) # Given v_i, v_f and a, find d problem = [ v_i == 30, v_f == 0, a == -8 ] print("Problem:") print(problem) print("Solution:") solve(equations + problem) ``` ## Problem 2 Ben Rushin is waiting at a stoplight. When it finally turns green, Ben accelerated from rest at a rate of a 6.00 m/s2 for a time of 4.10 seconds. Determine the displacement of Ben's car during this time period. ``` d, a, t, v_i, v_f = Reals('d a t v__i v__f') equations = [ d == v_i * t + (a*t**2)/2, v_f == v_i + a*t, ] # Given v_i, t and a, find d problem = [ v_i == 0, t == 4.10, a == 6 ] solve(equations + problem) # Display rationals in decimal notation set_option(rational_to_decimal=True) solve(equations + problem) ``` # Bit Tricks Some low level hacks are very popular with C programmers. We use some of these hacks in the Z3 implementation. Power of two This hack is frequently used in C programs (Z3 included) to test whether a machine integer is a power of two. We can use Z3 to prove it really works. The claim is that x != 0 && !(x & (x - 1)) is true if and only if x is a power of two. ``` x = BitVec('x', 32) powers = [ 2**i for i in range(32) ] fast = And(x != 0, x & (x - 1) == 0) slow = Or([ x == p for p in powers ]) print(fast) prove(fast == slow) print("trying to prove buggy version...") fast = x & (x - 1) == 0 prove(fast == slow) ``` # Opposite signs The following simple hack can be used to test whether two machine integers have opposite signs. ``` x = BitVec('x', 32) y = BitVec('y', 32) # Claim: (x ^ y) < 0 iff x and y have opposite signs trick = (x ^ y) < 0 # Naive way to check if x and y have opposite signs opposite = Or(And(x < 0, y >= 0), And(x >= 0, y < 0)) prove(trick == opposite) ``` # Puzzles ## Dog, Cat and Mouse Consider the following puzzle. Spend exactly 100 dollars and buy exactly 100 animals. Dogs cost 15 dollars, cats cost 1 dollar, and mice cost 25 cents each. You have to buy at least one of each. How many of each should you buy? ``` # Create 3 integer variables dog, cat, mouse = Ints('dog cat mouse') solve(dog >= 1, # at least one dog cat >= 1, # at least one cat mouse >= 1, # at least one mouse # we want to buy 100 animals dog + cat + mouse == 100, # We have 100 dollars (10000 cents): # dogs cost 15 dollars (1500 cents), # cats cost 1 dollar (100 cents), and # mice cost 25 cents 1500 * dog + 100 * cat + 25 * mouse == 10000) ``` ## Sodoku <p><a target="_blank" href="http://www.dailysudoku.com/sudoku/">Sudoku</a>is a very popular puzzle. The goal is to insert the numbers in the boxes to satisfy only one condition: each row, column and 3x3 box must contain the digits 1 through 9 exactly once. ![sudoku.png](attachment:sudoku.png) The following example encodes the sudoku problem in Z3. Different sudoku instances can be solved by modifying the matrix instance. This example makes heavy use of list comprehensions available in the Python programming language. ``` # 9x9 matrix of integer variables X = [ [ Int("x_%s_%s" % (i+1, j+1)) for j in range(9) ] for i in range(9) ] # each cell contains a value in {1, ..., 9} cells_c = [ And(1 <= X[i][j], X[i][j] <= 9) for i in range(9) for j in range(9) ] # each row contains a digit at most once rows_c = [ Distinct(X[i]) for i in range(9) ] # each column contains a digit at most once cols_c = [ Distinct([ X[i][j] for i in range(9) ]) for j in range(9) ] # each 3x3 square contains a digit at most once sq_c = [ Distinct([ X[3*i0 + i][3*j0 + j] for i in range(3) for j in range(3) ]) for i0 in range(3) for j0 in range(3) ] sudoku_c = cells_c + rows_c + cols_c + sq_c # sudoku instance, we use '0' for empty cells instance = ((0,0,0,0,9,4,0,3,0), (0,0,0,5,1,0,0,0,7), (0,8,9,0,0,0,0,4,0), (0,0,0,0,0,0,2,0,8), (0,6,0,2,0,1,0,5,0), (1,0,2,0,0,0,0,0,0), (0,7,0,0,0,0,5,2,0), (9,0,0,0,6,5,0,0,0), (0,4,0,9,7,0,0,0,0)) instance_c = [ If(instance[i][j] == 0, True, X[i][j] == instance[i][j]) for i in range(9) for j in range(9) ] s = Solver() s.add(sudoku_c + instance_c) if s.check() == sat: m = s.model() r = [ [ m.evaluate(X[i][j]) for j in range(9) ] for i in range(9) ] print_matrix(r) else: print("failed to solve") # Let us remove 9 from the first row and see if there is more than one solution instance = ((0,0,0,0,0,4,0,3,0), (0,0,0,5,1,0,0,0,7), (0,8,9,0,0,0,0,4,0), (0,0,0,0,0,0,2,0,8), (0,6,0,2,0,1,0,5,0), (1,0,2,0,0,0,0,0,0), (0,7,0,0,0,0,5,2,0), (9,0,0,0,6,5,0,0,0), (0,4,0,9,7,0,0,0,0)) instance_c = [ If(instance[i][j] == 0, True, X[i][j] == instance[i][j]) for i in range(9) for j in range(9) ] def n_solutions(n): s = Solver() s.add(sudoku_c + instance_c) i = 0 while s.check() == sat and i < n: m = s.model() print([[ m.evaluate(X[i][j]) for j in range(9)] for i in range(9)]) fml = And([X[i][j] == m.evaluate(X[i][j]) for i in range(9) for j in range(9)]) s.add(Not(fml)) i += 1 n_solutions(10) ``` ## Eight queens The eight queens puzzle is the problem of placing eight chess queens on an 8x8 chessboard so that no two queens attack each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. ![queens.png](attachment:queens.png) ``` # We know each queen must be in a different row. # So, we represent each queen by a single integer: the column position Queens = [ Int('Q_%i' % (i + 1)) for i in range(8) ] # Each queen is in a column {1, ... 8 } val_c = [ And(1 <= Queens[i], Queens[i] <= 8) for i in range(8) ] # At most one queen per column col_c = [ Distinct(Queens) ] # Diagonal constraint diag_c = [ If(i == j, True, And(Queens[i] - Queens[j] != i - j, Queens[i] - Queens[j] != j - i)) for i in range(8) for j in range(i) ] solve(val_c + col_c + diag_c) ``` # Application: Install Problem The install problem consists of determining whether a new set of packages can be installed in a system. This application is based on the article OPIUM: Optimal Package Install/Uninstall Manager. Many packages depend on other packages to provide some functionality. Each distribution contains a meta-data file that explicates the requirements of each package of the distribution. The meta-data contains details like the name, version, etc. More importantly, it contains depends and conflicts clauses that stipulate which other packages should be on the system. The depends clauses stipulate which other packages must be present. The conflicts clauses stipulate which other packages must not be present. The install problem can be easily solved using Z3. The idea is to define a Boolean variable for each package. This variable is true if the package must be in the system. If package a depends on packages b, c and z, we write: ``` a, b, c, d, e, f, g, z = Bools('a b c d e f g z') #DependsOn(a, [b, c, z]) #DependsOn is a simple Python function that creates Z3 constraints that capture the depends clause semantics. def DependsOn(pack, deps): return And([ Implies(pack, dep) for dep in deps ]) #Thus, DependsOn(a, [b, c, z]) generates the constraint # And(Implies(a, b), Implies(a, c), Implies(a, z)) print(DependsOn(a, [b, c, z])) #That is, if users install package a, they must also install packages b, c and z. #If package d conflicts with package e, we write Conflict(d, e). Conflict is also a simple Python function. def Conflict(p1, p2): return Or(Not(p1), Not(p2)) # Conflict(d, e) generates the constraint Or(Not(d), Not(e)). # With these two functions, we can easily encode the example # in the Opium article (Section 2) in Z3Py as: def DependsOn(pack, deps): return And([ Implies(pack, dep) for dep in deps ]) def Conflict(p1, p2): return Or(Not(p1), Not(p2)) solve(DependsOn(a, [b, c, z]), DependsOn(b, [d]), DependsOn(c, [Or(d, e), Or(f, g)]), Conflict(d, e), a, z) def DependsOn(pack, deps): return And([ Implies(pack, dep) for dep in deps ]) def Conflict(p1, p2): return Or(Not(p1), Not(p2)) a, b, c, d, e, f, g, z = Bools('a b c d e f g z') solve(DependsOn(a, [b, c, z]), DependsOn(b, [d]), DependsOn(c, [Or(d, e), Or(f, g)]), Conflict(d, e), a, z) def install_check(*problem): s = Solver() s.add(*problem) if s.check() == sat: m = s.model() r = [] for x in m: if is_true(m[x]): # x is a Z3 declaration # x() returns the Z3 expression # x.name() returns a string r.append(x()) print(r) else: print("invalid installation profile") print("Check 1") install_check(DependsOn(a, [b, c, z]), DependsOn(b, [d]), DependsOn(c, [Or(d, e), Or(f, g)]), Conflict(d, e), Conflict(d, g), a, z) print("Check 2") install_check(DependsOn(a, [b, c, z]), #DependsOn(b, d), DependsOn(b, [d]), DependsOn(c, [Or(d, e), Or(f, g)]), Conflict(d, e), Conflict(d, g), a, z, g) ``` Special thanks to Peter Gragert for porting the original web-based guide to the jupyter notebook format. ``` ```
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/tutorial/jupyter/guide.ipynb
guide.ipynb
# Advanced Topics More information on Z3 is available from https://github.com/z3prover/z3.git ## Expressions, Sorts and Declarations In Z3, expressions, sorts and declarations are called ASTs. ASTs are directed acyclic graphs. Every expression has a sort (aka type). The method sort() retrieves the sort of an expression. ``` !pip install "z3-solver" from z3 import * x = Int('x') y = Real('y') print ((x + 1).sort()) print ((y + 1).sort()) print ((x >= 2).sort()) ``` The function eq(n1, n2) returns True if n1 and n2 are the same AST. This is a structural test. ``` x, y = Ints('x y') print (eq(x + y, x + y)) print (eq(x + y, y + x)) n = x + y print (eq(n, x + y)) # x2 is eq to x x2 = Int('x') print (eq(x, x2)) # the integer variable x is not equal to # the real variable x print (eq(Int('x'), Real('x'))) ``` The method hash() returns a hashcode for an AST node. If eq(n1, n2) returns True, then n1.hash() is equal to n2.hash(). ``` x = Int('x') print ((x + 1).hash()) print ((1 + x).hash()) print (x.sort().hash()) ``` Z3 expressions can be divided in three basic groups: applications, quantifiers and bound/free variables. Applications are all you need if your problems do not contain universal/existential quantifiers. Although we say Int('x') is an integer "variable", it is technically an integer constant, and internally is represented as a function application with 0 arguments. Every application is associated with a declaration and contains 0 or more arguments. The method decl() returns the declaration associated with an application. The method num_args() returns the number of arguments of an application, and arg(i) one of the arguments. The function is_expr(n) returns True if n is an expression. Similarly is_app(n) (is_func_decl(n)) returns True if n is an application (declaration). ``` x = Int('x') print ("is expression: ", is_expr(x)) n = x + 1 print ("is application:", is_app(n)) print ("decl: ", n.decl()) print ("num args: ", n.num_args()) for i in range(n.num_args()): print ("arg(", i, ") ->", n.arg(i)) ``` Declarations have names, they are retrieved using the method name(). A (function) declaration has an arity, a domain and range sorts. ``` x = Int('x') x_d = x.decl() print ("is_expr(x_d): ", is_expr(x_d)) print ("is_func_decl(x_d):", is_func_decl(x_d)) print ("x_d.name(): ", x_d.name()) print ("x_d.range(): ", x_d.range()) print ("x_d.arity(): ", x_d.arity()) # x_d() creates an application with 0 arguments using x_d. print ("eq(x_d(), x): ", eq(x_d(), x)) print ("\n") # f is a function from (Int, Real) to Bool f = Function('f', IntSort(), RealSort(), BoolSort()) print ("f.name(): ", f.name()) print ("f.range(): ", f.range()) print ("f.arity(): ", f.arity()) for i in range(f.arity()): print ("domain(", i, "): ", f.domain(i)) # f(x, x) creates an application with 2 arguments using f. print (f(x, x)) print (eq(f(x, x).decl(), f)) ``` The built-in declarations are identified using their kind. The kind is retrieved using the method kind(). The complete list of built-in declarations can be found in the file z3consts.py (z3_api.h) in the Z3 distribution. ``` x, y = Ints('x y') print ((x + y).decl().kind() == Z3_OP_ADD) print ((x + y).decl().kind() == Z3_OP_SUB) ``` The following example demonstrates how to substitute sub-expressions in Z3 expressions. ``` x, y = Ints('x y') f = Function('f', IntSort(), IntSort(), IntSort()) g = Function('g', IntSort(), IntSort()) n = f(f(g(x), g(g(x))), g(g(y))) print (n) # substitute g(g(x)) with y and g(y) with x + 1 print (substitute(n, (g(g(x)), y), (g(y), x + 1))) ``` The function Const(name, sort) declares a constant (aka variable) of the given sort. For example, the functions Int(name) and Real(name) are shorthands for Const(name, IntSort()) and Const(name, RealSort()). ``` x = Const('x', IntSort()) print (eq(x, Int('x'))) a, b = Consts('a b', BoolSort()) print (And(a, b)) ``` ## Arrays As part of formulating a programme of a mathematical theory of computation McCarthy proposed a basic theory of arrays as characterized by the select-store axioms. The expression Select(a, i) returns the value stored at position i of the array a; and Store(a, i, v) returns a new array identical to a, but on position i it contains the value v. In Z3Py, we can also write Select(a, i) as a[i]. ``` # Use I as an alias for IntSort() I = IntSort() # A is an array from integer to integer A = Array('A', I, I) x = Int('x') print (A[x]) print (Select(A, x)) print (Store(A, x, 10)) print (simplify(Select(Store(A, 2, x+1), 2))) ``` By default, Z3 assumes that arrays are extensional over select. In other words, Z3 also enforces that if two arrays agree on all positions, then the arrays are equal. Z3 also contains various extensions for operations on arrays that remain decidable and amenable to efficient saturation procedures (here efficient means, with an NP-complete satisfiability complexity). We describe these extensions in the following using a collection of examples. Additional background on these extensions is available in the paper [Generalized and Efficient Array Decision Procedures](http://research.microsoft.com/en-us/um/people/leonardo/fmcad09.pdf). Arrays in Z3 are used to model unbounded or very large arrays. Arrays should not be used to model small finite collections of values. It is usually much more efficient to create different variables using list comprehensions. ``` # We want an array with 3 elements. # 1. Bad solution X = Array('x', IntSort(), IntSort()) # Example using the array print (X[0] + X[1] + X[2] >=0) # 2. More efficient solution X = IntVector('x', 3) print (X[0] + X[1] + X[2] >= 0) print (Sum(X) >= 0) ``` ### Select and Store Let us first check a basic property of arrays. Suppose A is an array of integers, then the constraints A[x] == x, Store(A, x, y) == A are satisfiable for an array that contains an index x that maps to x, and when x == y. We can solve these constraints. ``` A = Array('A', IntSort(), IntSort()) x, y = Ints('x y') solve(A[x] == x, Store(A, x, y) == A) ``` The interpretation/solution for array variables is very similar to the one used for functions. The problem becomes unsatisfiable/infeasible if we add the constraint x != y. ``` A = Array('A', IntSort(), IntSort()) x, y = Ints('x y') solve(A[x] == x, Store(A, x, y) == A, x != y) ``` ### Constant arrays The array that maps all indices to some fixed value can be specified in Z3Py using the K(s, v) construct where s is a sort/type and v is an expression. K(s, v) returns a array that maps any value of s into v. The following example defines a constant array containing only ones. ``` AllOne = K(IntSort(), 1) a, i = Ints('a i') solve(a == AllOne[i]) # The following constraints do not have a solution solve(a == AllOne[i], a != 1) ``` ## Datatypes Algebraic datatypes, known from programming languages such as ML, offer a convenient way for specifying common data structures. Records and tuples are special cases of algebraic datatypes, and so are scalars (enumeration types). But algebraic datatypes are more general. They can be used to specify finite lists, trees and other recursive structures. The following example demonstrates how to declare a List in Z3Py. It is more verbose than using the SMT 2.0 front-end, but much simpler than using the Z3 C API. It consists of two phases. First, we have to declare the new datatype, its constructors and accessors. The function Datatype('List') declares a "placeholder" that will contain the constructors and accessors declarations. The method declare(cname, (aname, sort)+) declares a constructor named cname with the given accessors. Each accessor has an associated sort or a reference to the datatypes being declared. For example, declare('cons', ('car', IntSort()), ('cdr', List)) declares the constructor named cons that builds a new List using an integer and a List. It also declares the accessors car and cdr. The accessor car extracts the integer of a cons cell, and cdr the list of a cons cell. After all constructors were declared, we use the method create() to create the actual datatype in Z3. Z3Py makes the new Z3 declarations and constants available as slots of the new object. ``` # Declare a List of integers List = Datatype('List') # Constructor cons: (Int, List) -> List List.declare('cons', ('car', IntSort()), ('cdr', List)) # Constructor nil: List List.declare('nil') # Create the datatype List = List.create() print (is_sort(List)) cons = List.cons car = List.car cdr = List.cdr nil = List.nil # cons, car and cdr are function declarations, and nil a constant print (is_func_decl(cons)) print (is_expr(nil)) l1 = cons(10, cons(20, nil)) print (l1) print (simplify(cdr(l1))) print (simplify(car(l1))) print (simplify(l1 == nil)) ``` The following example demonstrates how to define a Python function that given a sort creates a list of the given sort. ``` def DeclareList(sort): List = Datatype('List_of_%s' % sort.name()) List.declare('cons', ('car', sort), ('cdr', List)) List.declare('nil') return List.create() IntList = DeclareList(IntSort()) RealList = DeclareList(RealSort()) IntListList = DeclareList(IntList) l1 = IntList.cons(10, IntList.nil) print (l1) print (IntListList.cons(l1, IntListList.cons(l1, IntListList.nil))) print (RealList.cons("1/3", RealList.nil)) print (l1.sort()) ``` The example above demonstrates that Z3 supports operator overloading. There are several functions named cons, but they are different since they receive and/or return values of different sorts. Note that it is not necessary to use a different sort name for each instance of the sort list. That is, the expression 'List_of_%s' % sort.name() is not necessary, we use it just to provide more meaningful names. As described above enumeration types are a special case of algebraic datatypes. The following example declares an enumeration type consisting of three values: red, green and blue. ``` Color = Datatype('Color') Color.declare('red') Color.declare('green') Color.declare('blue') Color = Color.create() print (is_expr(Color.green)) print (Color.green == Color.blue) print (simplify(Color.green == Color.blue)) # Let c be a constant of sort Color c = Const('c', Color) # Then, c must be red, green or blue prove(Or(c == Color.green, c == Color.blue, c == Color.red)) ``` Z3Py also provides the following shorthand for declaring enumeration sorts. ``` Color, (red, green, blue) = EnumSort('Color', ('red', 'green', 'blue')) print (green == blue) print (simplify(green == blue)) c = Const('c', Color) solve(c != green, c != blue) ``` Mutually recursive datatypes can also be declared. The only difference is that we use the function CreateDatatypes instead of the method create() to create the mutually recursive datatypes. ``` TreeList = Datatype('TreeList') Tree = Datatype('Tree') Tree.declare('leaf', ('val', IntSort())) Tree.declare('node', ('left', TreeList), ('right', TreeList)) TreeList.declare('nil') TreeList.declare('cons', ('car', Tree), ('cdr', TreeList)) Tree, TreeList = CreateDatatypes(Tree, TreeList) t1 = Tree.leaf(10) tl1 = TreeList.cons(t1, TreeList.nil) t2 = Tree.node(tl1, TreeList.nil) print (t2) print (simplify(Tree.val(t1))) t1, t2, t3 = Consts('t1 t2 t3', TreeList) solve(Distinct(t1, t2, t3)) ``` ## Uninterpreted Sorts Function and constant symbols in pure first-order logic are uninterpreted or free, which means that no a priori interpretation is attached. This is in contrast to arithmetic operators such as + and - that have a fixed standard interpretation. Uninterpreted functions and constants are maximally flexible; they allow any interpretation that is consistent with the constraints over the function or constant. To illustrate uninterpreted functions and constants let us introduce an (uninterpreted) sort A, and the constants x, y ranging over A. Finally let f be an uninterpreted function that takes one argument of sort A and results in a value of sort A. The example illustrates how one can force an interpretation where f applied twice to x results in x again, but f applied once to x is different from x. ``` A = DeclareSort('A') x, y = Consts('x y', A) f = Function('f', A, A) s = Solver() s.add(f(f(x)) == x, f(x) == y, x != y) print (s.check()) m = s.model() print (m) print ("interpretation assigned to A:") print (m[A]) ``` The resulting model introduces abstract values for the elements in A, because the sort A is uninterpreted. The interpretation for f in the model toggles between the two values for x and y, which are different. The expression m[A] returns the interpretation (universe) for the uninterpreted sort A in the model m. ## Quantifiers Z3 is can solve quantifier-free problems containing arithmetic, bit-vector, Booleans, arrays, functions and datatypes. Z3 also accepts and can work with formulas that use quantifiers. It is no longer a decision procedure for such formulas in general (and for good reasons, as there can be no decision procedure for first-order logic). ``` f = Function('f', IntSort(), IntSort(), IntSort()) x, y = Ints('x y') print (ForAll([x, y], f(x, y) == 0)) print (Exists(x, f(x, x) >= 0)) a, b = Ints('a b') solve(ForAll(x, f(x, x) == 0), f(a, b) == 1) ``` Nevertheless, Z3 is often able to handle formulas involving quantifiers. It uses several approaches to handle quantifiers. The most prolific approach is using pattern-based quantifier instantiation. This approach allows instantiating quantified formulas with ground terms that appear in the current search context based on pattern annotations on quantifiers. Z3 also contains a model-based quantifier instantiation component that uses a model construction to find good terms to instantiate quantifiers with; and Z3 also handles many decidable fragments. Note that in the previous example the constants x and y were used to create quantified formulas. This is a "trick" for simplifying the construction of quantified formulas in Z3Py. Internally, these constants are replaced by bounded variables. The next example demonstrates that. The method body() retrieves the quantified expression. In the resultant formula the bounded variables are free. The function Var(index, sort) creates a bounded/free variable with the given index and sort. ``` f = Function('f', IntSort(), IntSort(), IntSort()) x, y = Ints('x y') f = ForAll([x, y], f(x, y) == 0) print (f.body()) v1 = f.body().arg(0).arg(0) print (v1) print (eq(v1, Var(1, IntSort()))) ``` ### Modeling with Quantifiers Suppose we want to model an object oriented type system with single inheritance. We would need a predicate for sub-typing. Sub-typing should be a partial order, and respect single inheritance. For some built-in type constructors, such as for array_of, sub-typing should be monotone. ``` Type = DeclareSort('Type') subtype = Function('subtype', Type, Type, BoolSort()) array_of = Function('array_of', Type, Type) root = Const('root', Type) x, y, z = Consts('x y z', Type) axioms = [ ForAll(x, subtype(x, x)), ForAll([x, y, z], Implies(And(subtype(x, y), subtype(y, z)), subtype(x, z))), ForAll([x, y], Implies(And(subtype(x, y), subtype(y, x)), x == y)), ForAll([x, y, z], Implies(And(subtype(x, y), subtype(x, z)), Or(subtype(y, z), subtype(z, y)))), ForAll([x, y], Implies(subtype(x, y), subtype(array_of(x), array_of(y)))), ForAll(x, subtype(root, x)) ] s = Solver() s.add(axioms) print (s) print (s.check()) print ("Interpretation for Type:") print (s.model()[Type]) print ("Model:") print (s.model()) ``` ### Patterns The Stanford Pascal verifier and the subsequent Simplify theorem prover pioneered the use of pattern-based quantifier instantiation. The basic idea behind pattern-based quantifier instantiation is in a sense straight-forward: Annotate a quantified formula using a pattern that contains all the bound variables. So a pattern is an expression (that does not contain binding operations, such as quantifiers) that contains variables bound by a quantifier. Then instantiate the quantifier whenever a term that matches the pattern is created during search. This is a conceptually easy starting point, but there are several subtleties that are important. In the following example, the first two options make sure that Model-based quantifier instantiation engine is disabled. We also annotate the quantified formula with the pattern f(g(x)). Since there is no ground instance of this pattern, the quantifier is not instantiated, and Z3 fails to show that the formula is unsatisfiable. ``` f = Function('f', IntSort(), IntSort()) g = Function('g', IntSort(), IntSort()) a, b, c = Ints('a b c') x = Int('x') s = Solver() s.set(auto_config=False, mbqi=False) s.add( ForAll(x, f(g(x)) == x, patterns = [f(g(x))]), g(a) == c, g(b) == c, a != b ) # Display solver state using internal format print (s.sexpr()) print (s.check()) ``` When the more permissive pattern g(x) is used. Z3 proves the formula to be unsatisfiable. More restrictive patterns minimize the number of instantiations (and potentially improve performance), but they may also make Z3 "less complete". ``` f = Function('f', IntSort(), IntSort()) g = Function('g', IntSort(), IntSort()) a, b, c = Ints('a b c') x = Int('x') s = Solver() s.set(auto_config=False, mbqi=False) s.add( ForAll(x, f(g(x)) == x, patterns = [g(x)]), g(a) == c, g(b) == c, a != b ) # Display solver state using internal format print (s.sexpr()) print (s.check()) ``` Some patterns may also create long instantiation chains. Consider the following assertion. <pre> ForAll([x, y], Implies(subtype(x, y), subtype(array_of(x), array_of(y))), patterns=[subtype(x, y)]) </pre> The axiom gets instantiated whenever there is some ground term of the form subtype(s, t). The instantiation causes a fresh ground term subtype(array_of(s), array_of(t)), which enables a new instantiation. This undesirable situation is called a matching loop. Z3 uses many heuristics to break matching loops. Before elaborating on the subtleties, we should address an important first question. What defines the terms that are created during search? In the context of most SMT solvers, and of the Simplify theorem prover, terms exist as part of the input formula, they are of course also created by instantiating quantifiers, but terms are also implicitly created when equalities are asserted. The last point means that terms are considered up to congruence and pattern matching takes place modulo ground equalities. We call the matching problem E-matching. For example, if we have the following equalities: ``` f = Function('f', IntSort(), IntSort()) g = Function('g', IntSort(), IntSort()) a, b, c = Ints('a b c') x = Int('x') s = Solver() s.set(auto_config=False, mbqi=False) s.add( ForAll(x, f(g(x)) == x, patterns = [f(g(x))]), a == g(b), b == c, f(a) != c ) print (s.check()) ``` The terms f(a) and f(g(b)) are equal modulo the equalities. The pattern f(g(x)) can be matched and x bound to b and the equality f(g(b)) == b is deduced. While E-matching is an NP-complete problem, the main sources of overhead in larger verification problems comes from matching thousands of patterns in the context of an evolving set of terms and equalities. Z3 integrates an efficient E-matching engine using term indexing techniques. ### Multi-patterns In some cases, there is no pattern that contains all bound variables and does not contain interpreted symbols. In these cases, we use multi-patterns. In the following example, the quantified formula states that f is injective. This quantified formula is annotated with the multi-pattern MultiPattern(f(x), f(y)). ``` A = DeclareSort('A') B = DeclareSort('B') f = Function('f', A, B) a1, a2 = Consts('a1 a2', A) b = Const('b', B) x, y = Consts('x y', A) s = Solver() s.add(a1 != a2, f(a1) == b, f(a2) == b, ForAll([x, y], Implies(f(x) == f(y), x == y), patterns=[MultiPattern(f(x), f(y))]) ) print (s.check()) ``` The quantified formula is instantiated for every pair of occurrences of f. A simple trick allows formulating injectivity of f in such a way that only a linear number of instantiations is required. The trick is to realize that f is injective if and only if it has a partial inverse. ``` A = DeclareSort('A') B = DeclareSort('B') f = Function('f', A, B) finv = Function('finv', B, A) a1, a2 = Consts('a1 a2', A) b = Const('b', B) x, y = Consts('x y', A) s = Solver() s.add(a1 != a2, f(a1) == b, f(a2) == b, ForAll(x, finv(f(x)) == x) ) print (s.check()) ``` ### Other attributes In Z3Py, the following additional attributes are supported: qid (quantifier identifier for debugging), weight (hint to the quantifier instantiation module: "more weight equals less instances"), no_patterns (expressions that should not be used as patterns, skid (identifier prefix used to create skolem constants/functions. ## Multiple Solvers In Z3Py and Z3 4.0 multiple solvers can be simultaneously used. It is also very easy to copy assertions/formulas from one solver to another. ``` x, y = Ints('x y') s1 = Solver() s1.add(x > 10, y > 10) s2 = Solver() # solver s2 is empty print (s2) # copy assertions from s1 to s2 s2.add(s1.assertions()) print (s2) ``` ## Unsat Cores and Soft Constraints Z3Py also supports unsat core extraction. The basic idea is to use assumptions, that is, auxiliary propositional variables that we want to track. Assumptions are also available in the Z3 SMT 2.0 frontend, and in other Z3 front-ends. They are used to extract unsatisfiable cores. They may be also used to "retract" constraints. Note that, assumptions are not really soft constraints, but they can be used to implement them. ``` p1, p2, p3 = Bools('p1 p2 p3') x, y = Ints('x y') # We assert Implies(p, C) to track constraint C using p s = Solver() s.add(Implies(p1, x > 10), Implies(p1, y > x), Implies(p2, y < 5), Implies(p3, y > 0)) print (s) # Check satisfiability assuming p1, p2, p3 are true print (s.check(p1, p2, p3)) print (s.unsat_core()) # Try again retracting p2 print (s.check(p1, p3)) print (s.model()) ``` The example above also shows that a Boolean variable (p1) can be used to track more than one constraint. Note that Z3 does not guarantee that the unsat cores are minimal. ## Formatter Z3Py uses a formatter (aka pretty printer) for displaying formulas, expressions, solvers, and other Z3 objects. The formatter supports many configuration options. The command set_option(html_mode=False) makes all formulas and expressions to be displayed in Z3Py notation. ``` x = Int('x') y = Int('y') set_option(html_mode=True) print (x**2 + y**2 >= 1) set_option(html_mode=False) print (x**2 + y**2 >= 1) ``` By default, Z3Py will truncate the output if the object being displayed is too big. Z3Py uses … to denote the output is truncated. The following configuration options can be set to control the behavior of Z3Py's formatter: * max_depth Maximal expression depth. Deep expressions are replaced with …. * max_args Maximal number of arguments to display per node. * rational_to_decimal Display rationals as decimals if True. * precision Maximal number of decimal places for numbers being displayed in decimal notation. * max_lines Maximal number of lines to be displayed. * max_width Maximal line width (this is a suggestion to Z3Py). * max_indent Maximal indentation. ``` x = IntVector('x', 20) y = IntVector('y', 20) f = And(Sum(x) >= 0, Sum(y) >= 0) set_option(max_args=5) print ("\ntest 1:", f) set_option(max_args=100, max_lines=10) print ("\ntest 2:", f) set_option(max_width=300) print ("\ntest 3:", f) ```
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/tutorial/jupyter/advanced.ipynb
advanced.ipynb
from z3 import * def main(): x, y = Reals('x y') constraints = [x > 2, x < 1, x < 0, Or(x + y > 0, y < 0), Or(y >= 0, x >= 0), Or(y < 0, x < 0), Or(y > 0, x < 0)] csolver = SubsetSolver(constraints) msolver = MapSolver(n=csolver.n) for orig, lits in enumerate_sets(csolver, msolver): output = "%s %s" % (orig, lits) print(output) def get_id(x): return Z3_get_ast_id(x.ctx.ref(),x.as_ast()) class SubsetSolver: constraints = [] n = 0 s = Solver() varcache = {} idcache = {} def __init__(self, constraints): self.constraints = constraints self.n = len(constraints) for i in range(self.n): self.s.add(Implies(self.c_var(i), constraints[i])) def c_var(self, i): if i not in self.varcache: v = Bool(str(self.constraints[abs(i)])) self.idcache[get_id(v)] = abs(i) if i >= 0: self.varcache[i] = v else: self.varcache[i] = Not(v) return self.varcache[i] def check_subset(self, seed): assumptions = self.to_c_lits(seed) return (self.s.check(assumptions) == sat) def to_c_lits(self, seed): return [self.c_var(i) for i in seed] def complement(self, aset): return set(range(self.n)).difference(aset) def seed_from_core(self): core = self.s.unsat_core() return [self.idcache[get_id(x)] for x in core] def shrink(self, seed): current = set(seed) for i in seed: if i not in current: continue current.remove(i) if not self.check_subset(current): current = set(self.seed_from_core()) else: current.add(i) return current def grow(self, seed): current = seed for i in self.complement(current): current.append(i) if not self.check_subset(current): current.pop() return current class MapSolver: def __init__(self, n): """Initialization. Args: n: The number of constraints to map. """ self.solver = Solver() self.n = n self.all_n = set(range(n)) # used in complement fairly frequently def next_seed(self): """Get the seed from the current model, if there is one. Returns: A seed as an array of 0-based constraint indexes. """ if self.solver.check() == unsat: return None seed = self.all_n.copy() # default to all True for "high bias" model = self.solver.model() for x in model: if is_false(model[x]): seed.remove(int(x.name())) return list(seed) def complement(self, aset): """Return the complement of a given set w.r.t. the set of mapped constraints.""" return self.all_n.difference(aset) def block_down(self, frompoint): """Block down from a given set.""" comp = self.complement(frompoint) self.solver.add( Or( [Bool(str(i)) for i in comp] ) ) def block_up(self, frompoint): """Block up from a given set.""" self.solver.add( Or( [Not(Bool(str(i))) for i in frompoint] ) ) def enumerate_sets(csolver, map): """Basic MUS/MCS enumeration, as a simple example.""" while True: seed = map.next_seed() if seed is None: return if csolver.check_subset(seed): MSS = csolver.grow(seed) yield ("MSS", csolver.to_c_lits(MSS)) map.block_down(MSS) else: MUS = csolver.shrink(seed) yield ("MUS", csolver.to_c_lits(MUS)) map.block_up(MUS) main()
z3-solver-crosshair
/z3-solver-crosshair-4.8.8.0.1.tar.gz/z3-solver-crosshair-4.8.8.0.1/core/examples/python/mus/marco.py
marco.py