repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
qfactor
qfactor-master/tests/gates/gate/test_repr.py
import numpy as np import unittest as ut from qfactor.gates import Gate class TestGateRepr ( ut.TestCase ): TOFFOLI = np.asarray( [[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j]] ) def test_gate_repr_1 ( self ): gate = Gate( self.TOFFOLI, (0, 1, 2) ) self.assertEqual( repr( gate ), str( (0, 1, 2) ) + ": [[(1+0j) ... 0j]]" ) def test_gate_repr_2 ( self ): gate = Gate( self.TOFFOLI, (4, 5, 7) ) self.assertEqual( repr( gate ), str( (4, 5, 7) ) + ": [[(1+0j) ... 0j]]" ) if __name__ == '__main__': ut.main()
1,196
35.272727
79
py
qfactor
qfactor-master/tests/gates/gate/__init__.py
0
0
0
py
qfactor
qfactor-master/tests/gates/ry/test_constructor.py
import scipy import numpy as np import unittest as ut from qfactor import get_distance from qfactor.gates import RyGate class TestRyGateConstructor ( ut.TestCase ): def test_rygate_constructor_invalid ( self ): self.assertRaises( TypeError, RyGate, 1, 0 ) self.assertRaises( TypeError, RyGate, "a", 0 ) self.assertRaises( TypeError, RyGate, [0, 1], 0 ) self.assertRaises( ValueError, RyGate, np.pi/2, -1 ) self.assertRaises( TypeError, RyGate, np.pi/2, [0, 1] ) self.assertRaises( TypeError, RyGate, np.pi/2, (0, 1) ) self.assertRaises( TypeError, RyGate, np.pi/2, ("a") ) self.assertRaises( TypeError, RyGate, np.pi/2, 0, 0 ) def test_rygate_constructor_valid ( self ): gate = RyGate( np.pi, 0, True ) Y = np.array( [ [ 0, -1j ], [ 1j, 0 ] ] ) Ry = scipy.linalg.expm( -1j * np.pi/2 * Y ) self.assertTrue( get_distance( [ gate ], Ry ) < 1e-15 ) self.assertTrue( np.array_equal( gate.location, (0,) ) ) self.assertEqual( gate.gate_size, 1 ) self.assertTrue( gate.fixed ) if __name__ == '__main__': ut.main()
1,151
31.914286
64
py
qfactor
qfactor-master/tests/gates/ry/test_repr.py
import numpy as np import unittest as ut from qfactor.gates import RyGate class TestRyGateRepr ( ut.TestCase ): def test_rygate_repr_1 ( self ): gate = RyGate( 0., 0 ) self.assertEqual( repr( gate ), "(0,): Ry(0.0)" ) def test_rygate_repr_2 ( self ): gate = RyGate( 2., 1 ) self.assertEqual( repr( gate ), "(1,): Ry(2.0)" ) if __name__ == '__main__': ut.main()
416
18.857143
57
py
qfactor
qfactor-master/tests/gates/ry/test_update.py
import numpy as np import unittest as ut from qfactor.gates import RyGate class TestRyGateUpdate ( ut.TestCase ): def test_rygate_update_1 ( self ): env = RyGate( np.pi/3, 0 ).utry gate = RyGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, -np.pi/3 ) ) def test_rygate_update_2 ( self ): env = RyGate( 2*np.pi/3, 0 ).utry gate = RyGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, -2*np.pi/3 ) ) def test_rygate_update_3 ( self ): env = RyGate( -2*np.pi/3, 0 ).utry gate = RyGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, 2*np.pi/3 ) ) def test_rygate_update_4 ( self ): env = RyGate( -np.pi/3, 0 ).utry gate = RyGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, np.pi/3 ) ) if __name__ == '__main__': ut.main()
988
25.72973
64
py
qfactor
qfactor-master/tests/gates/ry/__init__.py
0
0
0
py
qfactor
qfactor-master/tests/gates/rz/test_constructor.py
import scipy import numpy as np import unittest as ut from qfactor import get_distance from qfactor.gates import RzGate class TestRzGateConstructor ( ut.TestCase ): def test_rzgate_constructor_invalid ( self ): self.assertRaises( TypeError, RzGate, 1, 0 ) self.assertRaises( TypeError, RzGate, "a", 0 ) self.assertRaises( TypeError, RzGate, [0, 1], 0 ) self.assertRaises( ValueError, RzGate, np.pi/2, -1 ) self.assertRaises( TypeError, RzGate, np.pi/2, [0, 1] ) self.assertRaises( TypeError, RzGate, np.pi/2, (0, 1) ) self.assertRaises( TypeError, RzGate, np.pi/2, ("a") ) self.assertRaises( TypeError, RzGate, np.pi/2, 0, 0 ) def test_rzgate_constructor_valid ( self ): gate = RzGate( np.pi, 0, True ) Z = np.array( [ [ 1, 0 ], [ 0, -1 ] ] ) Rz = scipy.linalg.expm( -1j * np.pi/2 * Z ) self.assertTrue( get_distance( [ gate ], Rz ) < 1e-15 ) self.assertTrue( np.array_equal( gate.location, (0,) ) ) self.assertEqual( gate.gate_size, 1 ) self.assertTrue( gate.fixed ) if __name__ == '__main__': ut.main()
1,149
31.857143
64
py
qfactor
qfactor-master/tests/gates/rz/test_repr.py
import numpy as np import unittest as ut from qfactor.gates import RzGate class TestRzGateRepr ( ut.TestCase ): def test_rzgate_repr_1 ( self ): gate = RzGate( 0., 0 ) self.assertEqual( repr( gate ), "(0,): Rz(0.0)" ) def test_rzgate_repr_2 ( self ): gate = RzGate( 2., 1 ) self.assertEqual( repr( gate ), "(1,): Rz(2.0)" ) if __name__ == '__main__': ut.main()
416
18.857143
57
py
qfactor
qfactor-master/tests/gates/rz/test_update.py
import numpy as np import unittest as ut from qfactor.gates import RzGate class TestRzGateUpdate ( ut.TestCase ): def test_rzgate_update_1 ( self ): env = RzGate( np.pi/3, 0 ).utry gate = RzGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, -np.pi/3 ) ) def test_rzgate_update_2 ( self ): env = RzGate( 2*np.pi/3, 0 ).utry gate = RzGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, -2*np.pi/3 ) ) def test_rzgate_update_3 ( self ): env = RzGate( -2*np.pi/3, 0 ).utry gate = RzGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, 2*np.pi/3 ) ) def test_rzgate_update_4 ( self ): env = RzGate( -np.pi/3, 0 ).utry gate = RzGate( 0., 0 ) gate.update( env, 0 ) self.assertTrue( np.allclose( gate.theta, np.pi/3 ) ) if __name__ == '__main__': ut.main()
988
25.72973
64
py
qfactor
qfactor-master/tests/gates/rz/__init__.py
0
0
0
py
qfactor
qfactor-master/tests/utils/test_is_matrix.py
import numpy as np import unittest as ut from scipy.stats import unitary_group from qfactor.utils import is_matrix class TestIsMatrix ( ut.TestCase ): def test_is_matrix1 ( self ): for i in range( 1, 10 ): self.assertTrue( is_matrix( unitary_group.rvs( 2 * i ) ) ) def test_is_matrix2 ( self ): self.assertTrue( is_matrix( 1j * np.ones( ( 4, 4 ) ) ) ) self.assertTrue( is_matrix( np.ones( ( 4, 3 ) ) ) ) def test_is_matrix_invalid ( self ): self.assertFalse( is_matrix( np.ones( ( 4, ) ) ) ) self.assertFalse( is_matrix( 1 ) ) self.assertFalse( is_matrix( "a" ) ) if __name__ == '__main__': ut.main()
695
25.769231
70
py
qfactor
qfactor-master/tests/utils/test_is_unitary.py
import numpy as np import scipy as sp import unittest as ut from scipy.stats import unitary_group from qfactor.utils import is_unitary class TestIsUnitary ( ut.TestCase ): def test_is_unitary1 ( self ): for i in range( 1, 10 ): U = unitary_group.rvs( 2 * i ) self.assertTrue( is_unitary( U, tol = 1e-14 ) ) def test_is_unitary2 ( self ): for i in range( 1, 10 ): U = unitary_group.rvs( 2 * i ) U += 1e-13 * np.ones( ( 2 * i, 2 * i ) ) self.assertTrue( is_unitary( U, tol = 1e-12 ) ) def test_is_unitary_invalid ( self ): self.assertFalse( is_unitary( 1j * np.ones( ( 4, 4 ) ) ) ) self.assertFalse( is_unitary( np.ones( ( 4, 3 ) ) ) ) self.assertFalse( is_unitary( np.ones( ( 4, ) ) ) ) self.assertFalse( is_unitary( 1 ) ) self.assertFalse( is_unitary( "a" ) ) if __name__ == '__main__': ut.main()
950
28.71875
66
py
qfactor
qfactor-master/tests/utils/test_is_square_matrix.py
import numpy as np import unittest as ut from scipy.stats import unitary_group from qfactor.utils import is_square_matrix class TestIsSquareMatrix ( ut.TestCase ): def test_is_square_matrix1 ( self ): for i in range( 1, 10 ): self.assertTrue( is_square_matrix( unitary_group.rvs( 2 * i ) ) ) def test_is_square_matrix2 ( self ): self.assertTrue( is_square_matrix( 1j * np.ones( ( 4, 4 ) ) ) ) def test_is_square_matrix_invalid ( self ): self.assertFalse( is_square_matrix( np.ones( ( 4, 3 ) ) ) ) self.assertFalse( is_square_matrix( np.ones( ( 4, ) ) ) ) self.assertFalse( is_square_matrix( 1 ) ) self.assertFalse( is_square_matrix( "a" ) ) if __name__ == '__main__': ut.main()
772
28.730769
77
py
qfactor
qfactor-master/tests/utils/test_is_valid_location.py
import numpy as np import unittest as ut from qfactor.utils import is_valid_location class TestIsValidLocation ( ut.TestCase ): def test_is_valid_location_invalid1 ( self ): self.assertFalse( is_valid_location( "a" ) ) self.assertFalse( is_valid_location( 0 ) ) self.assertFalse( is_valid_location( "a", 256 ) ) self.assertFalse( is_valid_location( 0, 256 ) ) def test_is_valid_location_invalid2 ( self ): self.assertFalse( is_valid_location( (0, "a", 2) ) ) self.assertFalse( is_valid_location( (0, "a", 2), 256 ) ) def test_is_valid_location_invalid3 ( self ): self.assertFalse( is_valid_location( (0, 0) ) ) self.assertFalse( is_valid_location( (0, 0), 256 ) ) def test_is_valid_location_invalid4 ( self ): self.assertFalse( is_valid_location( (0, 1, 2), 1 ) ) self.assertFalse( is_valid_location( (0, 1, 2), 0 ) ) def test_is_valid_location_invalid5 ( self ): self.assertFalse( is_valid_location( (0, 2, 1) ) ) def test_is_valid_location_empty ( self ): self.assertTrue( is_valid_location( tuple() ) ) self.assertTrue( is_valid_location( tuple(), 0 ) ) self.assertTrue( is_valid_location( tuple(), 3 ) ) def test_is_valid_location_valid ( self ): self.assertTrue( is_valid_location( (0, 1, 2) ) ) self.assertTrue( is_valid_location( (0, 1, 2), 3 ) ) self.assertTrue( is_valid_location( (0, 1, 2, 17) ) ) self.assertTrue( is_valid_location( (0, 1, 2, 17), 18 ) ) if __name__ == '__main__': ut.main()
1,606
35.522727
65
py
qfactor
qfactor-master/tests/utils/__init__.py
0
0
0
py
qfactor
qfactor-master/tests/utils/test_get_num_qubits.py
import numpy as np import unittest as ut from qfactor.utils import get_num_qubits class TestGetNumQubits ( ut.TestCase ): def test_num_qubits ( self ): for i in range( 4 ): M = np.identity( 2 ** i ) self.assertTrue( get_num_qubits( M ) == i ) def test_num_qubits_invalid ( self ): M0 = np.ones( ( 3, 2 ) ) M1 = "a" M2 = 3 self.assertRaises( TypeError, get_num_qubits, M0 ) self.assertRaises( TypeError, get_num_qubits, M1 ) self.assertRaises( TypeError, get_num_qubits, M2 ) if __name__ == '__main__': ut.main()
623
23
58
py
pytorch_conv4D
pytorch_conv4D-master/conv4d.py
import numpy as np import math import torch import torch.nn as nn import torch.nn.functional as F class Conv4d_broadcast(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, padding, stride=1, padding_mode='circular', dilation=1, groups=1, bias=True, Nd=4, bias_initializer=None, kernel_initializer= None, channels_last=False): super(Conv4d_broadcast, self).__init__() assert padding_mode == 'circular' or padding == 0 and padding_mode == 'zeros', \ 'Implemented only for circular or no padding' assert stride == 1, "not implemented" assert dilation == 1, "not implemented" assert groups == 1, "not implemented" assert Nd <= 4 and Nd > 2, "not implemented" if not isinstance(kernel_size, (tuple, list)): kernel_size = tuple(kernel_size for _ in range(Nd)) if not isinstance(padding, (tuple, list)): padding = tuple(padding for _ in range(Nd)) # assert np.all(np.array(padding) == np.array(kernel_size) - 1), "works only in circular mode" self.conv_f = (nn.Conv2d, nn.Conv3d)[Nd - 3] self.out_channels = out_channels self.kernel_size = kernel_size self.padding = padding self.padding_mode = padding_mode self.use_bias = bias self.bias = nn.Parameter(torch.randn(out_channels)) if bias else self.register_parameter('bias', None) if bias_initializer is not None: bias_initializer(self.bias) self.conv_layers = torch.nn.ModuleList() for _ in range(self.kernel_size[0]): conv_layer = self.conv_f( in_channels=in_channels, out_channels=self.out_channels, bias=False, kernel_size=self.kernel_size[1:], ) if kernel_initializer is not None: kernel_initializer(conv_layer.weight) if channels_last: channels_last = [torch.channels_last, torch.channels_last_3d][Nd-3] conv_layer.to(memory_format=channels_last) self.conv_layers.append(conv_layer) def do_padding(self, input): (b, c_i) = tuple(input.shape[0:2]) size_i = tuple(input.shape[2:]) size_p = [size_i[i] + self.padding[i] for i in range(len(size_i))] padding = tuple(np.array( [((self.padding[i+1]+1)//2, self.padding[i+1]//2) for i in range(len(size_i[1:]))] ).reshape(-1)[::-1]) input = F.pad( # Ls padding input.reshape(b, -1, *size_i[1:]), padding, 'circular', 0 ).reshape(b, c_i, -1, *size_p[1:]) return input def forward(self, input): if self.padding_mode == 'circular': input = self.do_padding(input) (b, c_i) = tuple(input.shape[0:2]) size_i = tuple(input.shape[2:]) size_k = self.kernel_size padding = list(self.padding) size_o = (size_i[0], ) + tuple([size_i[x+1] - size_k[x+1] + 1 for x in range(len(size_i[1:]))]) result = torch.zeros((b, self.out_channels) + size_o, device=input.device) for i in range(size_k[0]): cinput = torch.transpose(input, 1, 2) # 1 -> channels, 2 -> Lt cinput = cinput.reshape(-1, c_i, *size_i[1:]) # merge bs and Lt output = self.conv_layers[i](cinput) output = output.reshape(b, size_i[0], *output.shape[1:]) output = torch.transpose(output, 1, 2) result = result + torch.roll(output, -1 * i, 2) if self.use_bias: resultShape = result.shape result = result.view(b, resultShape[1], -1) result += self.bias.reshape(1, self.out_channels, 1) result = result.view(resultShape) shift = math.ceil(padding[0] / 2) result = torch.roll(result, shift, 2) # after we rearranged 3D convolutions we can cut 4th dimention # depending on padding type circular or not dim_size = size_i[0] + self.padding[0] - size_k[0] + 1 result = result[:, :, :dim_size, ] return result class Conv4d_groups(nn.Module): def __init__(self, in_channels: int, out_channels: int, kernel_size, padding, stride=1, padding_mode='circular', dilation: int = 1, groups: int = 1, bias: bool = True, Nd: int = 4, bias_initializer=None, kernel_initializer=None, channels_last=False): super(Conv4d_groups, self).__init__() assert padding_mode == 'circular' or padding == 0, 'Implemented only for circular or no padding' assert stride == 1, "not implemented" assert dilation == 1, "not implemented" assert groups == 1, "not implemented" assert Nd <= 4, "not implemented" assert padding == kernel_size - 1, "works only in circular mode" if not isinstance(kernel_size, tuple): kernel_size = tuple(kernel_size for _ in range(Nd)) if not isinstance(padding, tuple): padding = tuple(padding for _ in range(Nd)) self.conv_f = (nn.Conv1d, nn.Conv2d, nn.Conv3d)[Nd - 2] self.out_channels = out_channels self.kernel_size = kernel_size self.padding = padding self.padding_mode = padding_mode self.use_bias = bias self.bias = nn.Parameter(torch.randn(out_channels)) if bias else self.register_parameter('bias', None) if bias_initializer is not None: bias_initializer(self.bias) self.conv = self.conv_f(in_channels=in_channels*self.kernel_size[0], out_channels=self.out_channels*self.kernel_size[0], bias=False, stride=stride, kernel_size=self.kernel_size[1:], padding_mode=self.padding_mode, groups=self.kernel_size[0]) if channels_last: channels_last = [torch.channels_last, torch.channels_last_3d][Nd-3] self.conv.to(memory_format=channels_last) if kernel_initializer is not None: kernel_initializer(self.conv.weight) def do_padding(self, input): (b, c_i) = tuple(input.shape[0:2]) size_i = tuple(input.shape[2:]) size_p = [size_i[i] + self.padding[i] for i in range(len(size_i))] input = F.pad( # Ls padding input.reshape(b, -1, *size_i[1:]), tuple(np.array( # [(0, self.padding[i+1]) for i in range(len(size_i[1:]))] [((self.padding[i+1]+1)//2, self.padding[i+1]//2) for i in range(len(size_i[1:]))] ).reshape(-1)), 'circular', 0 ).reshape(b, c_i, -1, *size_p[1:]) return input def forward(self, input): if self.padding_mode == 'circular': input = self.do_padding(input) (b, c_i) = tuple(input.shape[0:2]) size_i = tuple(input.shape[2:]) size_k = self.kernel_size padding = list(self.padding) size_o = (size_i[0], ) + tuple([size_i[x+1] - size_k[x+1] + 1 for x in range(len(size_i[1:]))]) # size_o = tuple([size_i[x] + padding[x] - size_k[x] + 1 for x in range(len(size_i))]) cinput = torch.transpose(input, 1, 2) # (bs, channels, Lt, ...) -> (bs, Lt, channels, ...) cinput = cinput.reshape(b * size_i[0], c_i, *size_i[1:]) # (bs, Lt, ...) -> (bs * Lt, ...) # # (bs * Lt, c_i, ...) -> (bs * Lt, 1, c_i, ...) -> (bs * Lt, k[0], c_i, ...) -> (bs * Lt, k[0] * c_i, ...) cinput = cinput[:,np.newaxis,:] \ .expand(cinput.shape[0], self.kernel_size[0], *cinput.shape[1:]) \ .reshape(cinput.shape[0], self.kernel_size[0] * cinput.shape[1], *cinput.shape[2:]) out = self.conv(cinput) # out.shape = (bs * Lt, k[0] * c_o, ...) # (bs * Lt, c_o * k[0], ...) -> (bs, Lt, k[0], c_o, ...) out = out.reshape(b, size_i[0], self.kernel_size[0], self.out_channels, *size_o[1:]) out = out.transpose(1, 3)# (bs, Lt, k[0], c_o, ...) -> (bs, c_o, k[0], Lt...) out = out.split(1, dim=2) # (bs, c_o, k[0], Lt...)-> list( (bs, c_o, 1, Lt...) ) out = torch.stack([torch.roll(out[i].squeeze(2), -1 * i, 2) for i in range(len(out))], dim=0) result = torch.sum(out, dim=0) if self.use_bias: resultShape = result.shape result = result.view(b,resultShape[1],-1) result += self.bias.reshape(1, self.out_channels, 1) result = result.view(resultShape) shift = math.ceil(padding[0] / 2) result = torch.roll(result, shift, 2) result = result[:, :, :size_o[0], ] return result
9,176
40.337838
116
py
pytorch_conv4D
pytorch_conv4D-master/__init__.py
0
0
0
py
pytorch_conv4D
pytorch_conv4D-master/test_conv4d.py
import pytest import timeit import numpy as np import scipy.stats as sns from functools import partial import torch import torch.nn as nn from .conv4d import Conv4d_broadcast, Conv4d_groups try: import intel_extension_for_pytorch as ipex device = torch.device("xpu" if torch.xpu.is_available() else "cpu") sync_cmd = 'torch.xpu.synchronize()' except: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") sync_cmd = 'torch.cuda.synchronize()' torch.set_default_dtype(torch.float64) def init(inChans, outChans, L, Nd, bs, ks, isBias, Conv4dClass, channels_last=True): def init_broadcast(weights): def wgen(weights): for i in range(weights.shape[2]): yield weights[:, :, i, ] g = wgen(weights) def init(x): tmp = next(g) x.data = tmp return x return init def init_groups(x, weights): Lt = weights.shape[2] tmp = [weights[:, :, i, ...] for i in range(Lt)] tmp = torch.cat(tmp, dim=0) x.data = tmp return x def init_bias(x, bias): x.data = bias return x assert ks % 2 == 1, 'Since PT 1.5 works only with odd kernel size' padding_mode = 'circular' mf = [torch.channels_last, torch.channels_last_3d][Nd-2] if channels_last else torch.contiguous_format x = torch.randn(bs, inChans, *((L,)*Nd)).to(device) x = x.to(memory_format=mf) convPT = nn.Conv3d( inChans, outChans, ks, stride=1, padding=(ks-1)//2, bias=isBias, padding_mode=padding_mode ).to(device).to(memory_format=mf) conv = Conv4dClass( inChans, outChans, Nd=Nd, kernel_size=ks, padding=ks-1, bias=isBias, padding_mode=padding_mode, kernel_initializer= partial( init_groups, weights=tuple(convPT.parameters())[0] ) if Conv4dClass.__name__ == 'Conv4d_groups' else init_broadcast(tuple(convPT.parameters())[0]), bias_initializer= lambda x: init_bias(x, tuple(convPT.parameters())[1]) if isBias else None, channels_last=channels_last ).to(device) return x, convPT, conv @pytest.mark.parametrize('inChans', [1, 2]) @pytest.mark.parametrize('outChans', [1, 2, 8]) @pytest.mark.parametrize('L', [8, 16]) @pytest.mark.parametrize('Nd', [3]) @pytest.mark.parametrize('bs', [256]) # ks = 2 is not working due to bug in pytorch.nn.conv2d with padding=1 @pytest.mark.parametrize('ks', [3, 5, 7]) @pytest.mark.parametrize('isBias', [True, False]) @pytest.mark.parametrize('Conv4dClass', [Conv4d_groups, Conv4d_broadcast]) @pytest.mark.parametrize('channels_last', [True, False]) def test_convNd(inChans, outChans, L, Nd, bs, ks, isBias, Conv4dClass, channels_last): torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False _data, _convPt, _convNd = init(inChans, outChans, L, Nd, bs, ks, isBias, Conv4dClass) outPT = _convPt(_data) out = _convNd(_data) diff = torch.abs((out-outPT)).max() print(f"convNd max error: {diff:.2g}") assert diff < 1e-5, f'err: {diff}' def compare_time(inChans, outChans, L, Nd, bs, ks, isBias, Conv4dClass, channels_last): import torch torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = True number = 1 _data, _convPT, _convNd = init(inChans, outChans, L, Nd, bs, ks, isBias, Conv4dClass,channels_last) times = np.array( timeit.repeat( f"{sync_cmd}; out = _convPT(_data);{sync_cmd};", globals=locals(), number=number) ) print("ConvPT Forward time: ", f'{times[1:].mean():3g} pm {sns.sem(times[1:]):3g}') times = np.array( timeit.repeat( f"{sync_cmd}; out = _convNd(_data);{sync_cmd};", globals=locals(), number=number) ) print("ConvNd Forward time: ", f'{times[1:].mean():3g} pm {sns.sem(times[1:]):3g}') times = np.array( timeit.repeat( f"{sync_cmd};out=_convPT(_data);out.sum().backward();{sync_cmd};", globals=locals(), number=number) ) print( "ConvPt Forward+Backward time: ", f'{times[1:].mean():3g} pm {sns.sem(times[1:]):3g}' ) times = np.array( timeit.repeat( f"{sync_cmd};_convNd(_data).sum().backward();{sync_cmd};", globals=locals(), number=number) ) print( "ConvNd Forward+Backward time: ", f'{times[1:].mean():3g} pm {sns.sem(times[1:]):3g}') def run_4d_benchmark(inChans, outChans, L, bs, ks, isBias, Conv4dClass, channels_last): import torch torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = True number = 1 Nd = 4 mf = torch.channels_last_3d if channels_last else torch.contiguous_format _data = torch.randn(bs, inChans, *((L,)*Nd)).to(device) #.to(memory_format=mf) _convNd = Conv4dClass( inChans, outChans, Nd=Nd, kernel_size=ks, padding=ks-1, bias=isBias, padding_mode='circular', channels_last=channels_last).to(device) times = np.array( timeit.repeat( f"{sync_cmd}; out = _convNd(_data);{sync_cmd};", globals=locals(), number=number) ) print("Forward time: ", f'{times[1:].mean():3g} pm {sns.sem(times[1:]):3g}') times = np.array( timeit.repeat( f"{sync_cmd}; out = _convNd(_data).sum().backward(); {sync_cmd}", globals=locals(), number=number) ) print("Forward+Backward time: ", f'{times[1:].mean():3g} pm {sns.sem(times[1:]):3g}') if __name__ == "__main__": for conv_type in [Conv4d_broadcast, Conv4d_groups]: for channels_last in [True, False]: print("========================================================") print(conv_type, '| channels_last =', channels_last) print("========================================================") print("--> Bechmark 3D") test_convNd(inChans=8, outChans=32, L=16, Nd=3, bs=64, ks=3, isBias=True, Conv4dClass=conv_type, channels_last=channels_last) compare_time(inChans=64, outChans=64, L=16, Nd=3, bs=64, ks=3, isBias=True, Conv4dClass=conv_type, channels_last=channels_last) print("--> Benchmark 4D") print("----> inChannels = 18, outChannels = 32") run_4d_benchmark(inChans=18, outChans=32, L=8, bs=64, ks=3, isBias=True, Conv4dClass=conv_type, channels_last=channels_last) print("----> inChannels = 32, outChannels = 32") run_4d_benchmark(inChans=32, outChans=32, L=8, bs=64, ks=3, isBias=True, Conv4dClass=conv_type, channels_last=channels_last) print("----> inChannels = 32, outChannels = 48") run_4d_benchmark(inChans=32, outChans=48, L=8, bs=64, ks=3, isBias=True, Conv4dClass=conv_type, channels_last=channels_last)
7,179
35.262626
106
py
phocnet
phocnet-master/install.py
import os import shutil import logging import argparse from subprocess import call import sys def main(cudnn_dir, no_caffe, opencv_dir, install_dir, install_caffe_dir): # init logger logging.basicConfig(level=logging.INFO) logger = logging.getLogger('install.py') # init submodules call(['git', 'submodule', 'init']) call(['git', 'submodule', 'update']) # compile caffe # cmake if not no_caffe: logger.info('Running CMake to configure Caffe submodule...') if install_caffe_dir is None: install_caffe_dir = os.path.join(install_dir, 'caffe') else: install_caffe_dir = os.path.join(install_caffe_dir, 'caffe') os.chdir('caffe') if os.path.exists('build'): shutil.rmtree('build') os.makedirs('build') os.chdir('build') call_list = ['cmake', '..', '-DCMAKE_INSTALL_PREFIX=%s' % install_caffe_dir] if cudnn_dir is not None: call_list.append('-DCUDNN_DIR=%s' % cudnn_dir) if opencv_dir is not None: call_list.append('-DOpenCV_DIR=%s' % opencv_dir) if call(call_list) != 0: raise ValueError('Error during CMake run') # make logger.info('Compiling Caffe submodule...') if call(['make', 'install']) != 0: raise ValueError('Error during make') os.chdir('../..') # copy to desired location install_path = os.path.join(install_dir, 'lib','python' + '.'.join(sys.version.split('.')[:2]), 'site-packages') if not os.path.exists(install_path): os.makedirs(install_path) shutil.copytree('src/phocnet', install_path + '/phocnet') logger.info('Finished installation.') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Script for easy install of the PHOCNet library (dependencies must be present).') parser.add_argument('--cudnn-dir', type=str, help='Path to the CUDNN root dir.') parser.add_argument('--opencv-dir', type=str, help='Path to the OpenCV share dir.') parser.add_argument('--install-dir', type=str, required=True, help='Path to install the PHOCNet library into.') parser.add_argument('--install-caffe-dir', type=str, help='Path to install the custom Caffe library into. If unspecified, the install_ir path is chosen.') parser.add_argument('--no-caffe', action='store_true', help='If this flag is provided, the PHOCNet library is installed without the custom Caffe (e.g. if you installed a different Caffe version and don''') args = vars(parser.parse_args()) main(**args)
2,659
41.222222
174
py
phocnet
phocnet-master/tools/predict_phocs.py
#!/usr/bin/env python ''' Script for predicting PHOCs for a number of images residing in a folder on disk. ''' import argparse import logging import os import caffe import numpy as np import cv2 from phocnet.evaluation.cnn import net_output_for_word_image_list def main(img_dir, output_dir, pretrained_phocnet, deploy_proto, min_image_width_height, gpu_id): logging_format = '[%(asctime)-19s, %(name)s, %(levelname)s] %(message)s' logging.basicConfig(level=logging.INFO, format=logging_format) logger = logging.getLogger('Predict PHOCs') if gpu_id is None: caffe.set_mode_cpu() else: caffe.set_mode_gpu() caffe.set_device(gpu_id) logger.info('Loading PHOCNet...') phocnet = caffe.Net(deploy_proto, caffe.TEST, weights=pretrained_phocnet) # find all images in the supplied dir logger.info('Found %d word images to process', len(os.listdir(img_dir))) word_img_list = [cv2.imread(os.path.join(img_dir, filename), cv2.CV_LOAD_IMAGE_GRAYSCALE) for filename in sorted(os.listdir(img_dir)) if filename not in ['.', '..']] # push images through the PHOCNet logger.info('Predicting PHOCs...') predicted_phocs = net_output_for_word_image_list(phocnet=phocnet, word_img_list=word_img_list, min_img_width_height=min_image_width_height) # save everything logger.info('Saving...') np.save(os.path.join(output_dir, 'predicted_phocs.npy'), predicted_phocs) logger.info('Finished') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Predict PHOCs from a pretrained PHOCNet. The PHOCs are saved as Numpy Array to disk.') parser.add_argument('--min_image_width_height', '-miwh', action='store', type=int, default=26, help='The minimum image width or height to be passed through the PHOCNet. Default: 26') parser.add_argument('--output_dir', '-od', action='store', type=str, default='.', help='The directory where to store the PHOC Numpy Array. Default: .') parser.add_argument('--img_dir', '-id', action='store', type=str, required=True, help='All images in this folder are processed in ASCII order of their '+ 'respective names. A PHOC is predicted for each.') parser.add_argument('--pretrained_phocnet', '-pp', action='store', type=str, required=True, help='Path to a pretrained PHOCNet binaryproto file.') parser.add_argument('--deploy_proto', '-dp', action='store', type=str, required=True, help='Path to PHOCNet deploy prototxt file.') parser.add_argument('--gpu_id', '-gpu', action='store', type=int, help='The ID of the GPU to use. If not specified, training is run in CPU mode.') args = vars(parser.parse_args()) main(**args)
2,673
42.836066
133
py
phocnet
phocnet-master/tools/train_phocnet.py
import argparse from phocnet.training.phocnet_trainer import PHOCNetTrainer if __name__ == '__main__': parser = argparse.ArgumentParser() # required training parameters parser.add_argument('--doc_img_dir', action='store', type=str, required=True, help='The location of the document images.') parser.add_argument('--train_annotation_file', action='store', type=str, required=True, help='The file path to the READ-style XML file for the training partition of the dataset to be used.') parser.add_argument('--test_annotation_file', action='store', type=str, required=True, help='The file path to the READ-style XML file for the testing partition of the dataset to be used.') parser.add_argument('--proto_dir', action='store', type=str, required=True, help='Directory where to save the protobuffer files generated during the training.') parser.add_argument('--lmdb_dir', action='store', type=str, required=True, help='Directory where to save the LMDB databases created during training.') # IO parameters parser.add_argument('--save_net_dir', '-snd', action='store', type=str, help='Directory where to save the final PHOCNet. If unspecified, the net is not saved after training') parser.add_argument('--recreate_lmdbs', '-rl', action='store_true', default=False, help='Flag indicating to delete existing LMDBs for this dataset and recompute them.') parser.add_argument('--debug_mode', '-dm', action='store_true', default=False, help='Flag indicating to run the PHOCNet training in debug mode.') # Caffe parameters parser.add_argument('--learning_rate', '-lr', action='store', type=float, default=0.0001, help='The learning rate for SGD training. Default: 0.0001') parser.add_argument('--momentum', '-mom', action='store', type=float, default=0.9, help='The momentum for SGD training. Default: 0.9') parser.add_argument('--step_size', '-ss', action='store', type=int, default=70000, help='The step size at which to reduce the learning rate. Default: 70000') parser.add_argument('--display', action='store', type=int, default=500, help='The number of iterations after which to display the loss values. Default: 500') parser.add_argument('--test_interval', action='store', type=int, default=500, help='The number of iterations after which to periodically evaluate the PHOCNet. Default: 500') parser.add_argument('--max_iter', action='store', type=int, default=80000, help='The maximum number of SGD iterations. Default: 80000') parser.add_argument('--batch_size', '-bs', action='store', type=int, default=10, help='The batch size after which the gradient is computed. Default: 10') parser.add_argument('--weight_decay', '-wd', action='store', type=float, default=0.00005, help='The weight decay for SGD training. Default: 0.00005') parser.add_argument('--gamma', '-gam', action='store', type=float, default=0.1, help='The value with which the learning rate is multiplied after step_size iteraionts. Default: 0.1') parser.add_argument('--gpu_id', '-gpu', action='store', type=int, help='The ID of the GPU to use. If not specified, training is run in CPU mode.') # PHOCNet parameters parser.add_argument('--phoc_unigram_levels', '-pul', action='store', type=lambda x: [int(elem) for elem in x.split(',')], default='2,3,4,5', help='Comma seperated list of PHOC unigram levels to be used. Default: 2,3,4,5') parser.add_argument('--use_bigrams', '-ub', action='store_true', help='Flag indicating to build the PHOC with bigrams') parser.add_argument('--n_train_images', '-nti', action='store', type=int, default=500000, help='The number of images to be generated for the training LMDB. Default: 500000') parser.add_argument('--metric', '-met', action='store', type=str, default='braycurtis', help='The metric with which to compare the PHOCNet predicitions (possible metrics are all scipy metrics). Default: braycurtis') parser.add_argument('--annotation_delimiter', '-ad', action='store', type=str, help='If the annotation in the XML is separated by special delimiters, it can be specified here.') parser.add_argument('--use_lower_case_only', '-ulco', action='store_true', default=False, help='Flag indicating to convert all annotations from the XML to lower case before proceeding') params = vars(parser.parse_args()) PHOCNetTrainer(**params).train_phocnet()
4,914
80.916667
149
py
phocnet
phocnet-master/tools/eval_phocnet.py
''' This script uses a pretrained PHOCNet to generate the output for a given test list ''' import argparse from phocnet.evaluation.phocnet_evaluator import PHOCNetEvaluation if __name__ == '__main__': pne = PHOCNetEvaluation() parser = argparse.ArgumentParser() subparser = parser.add_subparsers() standard_args = argparse.ArgumentParser(add_help=False) standard_args.add_argument('--phocnet_bin_path', action='store', type=str, required=True, help='Path to a pretrained PHOCNet binary protofile.') standard_args.add_argument('--doc_img_dir', action='store', type=str, required=True, help='The location of the document images.') standard_args.add_argument('--gpu_id', '-gpu', action='store', type=int, help='The ID of the GPU to use. If not specified, prediction is run in CPU mode.') standard_args.add_argument('--debug_mode', '-dm', action='store_true', default=False, help='Flag indicating to run the PHOCNet training in debug mode.') standard_args.add_argument('--train_xml_file', action='store', type=str, required=True, help='The READ-style XML file of words used in training') standard_args.add_argument('--test_xml_file', action='store', type=str, required=True, help='The READ-style XML file of words to be used for testing') standard_args.add_argument('--deploy_proto_path', '-dpp', action='store', type=str, default='/tmp/deploy_phocnet.prototxt', help='Location where to save the deploy file. Default: /tmp/deploy_phocnet.prototxt') standard_args.add_argument('--metric', action='store', type=str, default='braycurtis', help='The metric to be used when comparing the PHOCNet output. Possible: all scipy metrics. Default: braycurtis') standard_args.add_argument('--phoc_unigram_levels', '-pul', action='store', type=lambda str_list: [int(elem) for elem in str_list.split(',')], default='2,3,4,5', help='The comma seperated list of PHOC unigram levels. Default: 2,3,4,5') standard_args.add_argument('--no_bigrams', '-ub', action='store_true', default=False, help='Flag indicating to build the PHOC without bigrams') standard_args.add_argument('--annotation_delimiter', '-ad', action='store', type=str, help='If the annotation in the XML is separated by special delimiters, it can be specified here.') # --- calc-phocs extract_unigrams_parser = subparser.add_parser('extract-unigrams', help='Finds the unigrams for a given XML and saves them') calc_phocs_parser = subparser.add_parser('calc-phocs', help='Predicts PHOCs from a pretrained CNN and saves them', parents=[standard_args]) calc_phocs_parser.add_argument('--output_dir', '-od', action='store', type=str, default='.', help='Location where to save the estimated PHOCs. Default: working directory') calc_phocs_parser.set_defaults(func=pne.predict_and_save_phocs) # --- extract-unigrams extract_unigrams_parser.add_argument('--word_xml_file', action='store', type=str, required=True, help='The READ-style XML file of words for which to extract the unigrams') extract_unigrams_parser.add_argument('--annotation_delimiter', '-ad', action='store', type=str, help='If the annotation in the XML is separated by special delimiters, it can be specified here.') extract_unigrams_parser.add_argument('--doc_img_dir', action='store', type=str, required=True, help='The location of the document images.') extract_unigrams_parser.set_defaults(func=pne.extract_unigrams) # --- qbs qbs_parser = subparser.add_parser('qbs', help='Evaluates the supplied CNN in a Query-by-String scenario (for protocol see Sudholt 2016 - PHOCNet)', parents=[standard_args]) qbs_parser.set_defaults(func=pne.eval_qbs) # --- qbe qbe_parser = subparser.add_parser('qbe', help='Evaluates the supplied CNN in a Query-by-Example scenario (for protocol see Sudholt 2016 - PHOCNet)', parents=[standard_args]) qbe_parser.set_defaults(func=pne.eval_qbe) # run everything subfunc = parser.parse_args() args = vars(subfunc).copy() del args['func'] subfunc.func(**args)
4,794
67.5
152
py
phocnet
phocnet-master/tools/save_deploy_proto.py
#!/usr/bin/env python import argparse import os from phocnet.caffe.model_proto_generator import ModelProtoGenerator if __name__ == '__main__': parser = argparse.ArgumentParser(description='Save a PHOCNet deploy proto file to disk.') parser.add_argument('--output_dir', '-od', action='store', type=str, default='.', help='The directory where to save the deploy proto. Default: .') parser.add_argument('--phoc_size', '-ps', action='store', type=int, default=604, help='The dimensionality of the PHOC. Default: 604') args = vars(parser.parse_args()) proto = ModelProtoGenerator(use_cudnn_engine=False).get_phocnet(word_image_lmdb_path=None, phoc_lmdb_path=None, phoc_size=args['phoc_size'], generate_deploy=True) with open(os.path.join(args['output_dir'], 'deploy_phocnet.prototxt'), 'w') as deploy_file: deploy_file.write('#Deploy PHOCNet\n') deploy_file.write(str(proto))
1,028
59.529412
118
py
phocnet
phocnet-master/examples/prediction_example.py
import caffe import numpy as np def main(): # This example is going to show you how you can use the API to predict # PHOCs from a trained PHOCNet for your own word images. # First we need to load the trained PHOCNet. We are going to use the trained # PHOCNet supplied at # http://patrec.cs.tu-dortmund.de/files/cnns/phocnet_gw_cv1.binaryproto deploy_path = 'deploy_phocnet.prototxt' trainet_net_path = 'phocnet_gw_cv1.binaryproto' phocnet = caffe.Net(deploy_path, caffe.TEST, weights=trainet_net_path) # Now you can supply your own images. For the sake of example, we use # random arrays. We generate 4 images of shape 60 x 160, each having one # channel. The pixel range is 0 - 255 images = [np.around(np.random.rand(60, 160, 1)*255) for _ in xrange(4)] # Note that the image ndarray arrays are now in the typical shape and pixel # range of what you would get if you were to load your images with the # standard tools such as OpenCV or skimage. For Caffe, we need to translate # it into a 4D tensor of shape (num. images, channels, height, width) for idx in xrange(4): images[idx] = np.transpose(images[idx], (2, 0, 1)) images[idx] = np.reshape(images[idx], (1, 1, 60, 160)) # The PHOCNet accepts images in a pixel range of 0 (white) to 1 (black). # Typically, the pixel intensities are inverted i.e. white is 255 and # black is 0. We thus need to prepare our word images to be in the # correct range. If your images are already in 0 (white) to 1 (black) # you can skip this step. images[idx] -= 255.0 images[idx] /= -255.0 # Now we are all set to shove the images through the PHOCNet. # As we usually have different image sizes, we need to predict them # one by one from the net. # First, you need to reshape the input layer blob (word_images) to match # the current word image shape you want to process. phocs = [] for image in images: phocnet.blobs['word_images'].reshape(*image.shape) phocnet.reshape() # Put the current image into the input layer... phocnet.blobs['word_images'].data[...] = image # ... and predict the PHOC (flatten automatically returns a copy) phoc = phocnet.forward()['sigmoid'].flatten() phocs.append(phoc) # Congrats, you have a set of PHOCs for your word images. # If you run into errors with the code above, make sure that your word images are # shape (num. images, channels, height, width). # Only in cases where you have images of the exact same size should num. images # be different from 1 if __name__ == '__main__': main()
2,767
44.377049
85
py
phocnet
phocnet-master/src/phocnet/__init__.py
0
0
0
py
phocnet
phocnet-master/src/phocnet/evaluation/cnn.py
''' Created on Jul 10, 2016 @author: ssudholt ''' import logging import numpy as np from skimage.transform import resize from phocnet.evaluation.retrieval import map_from_feature_matrix def net_output_for_word_image_list(phocnet, word_img_list, min_img_width_height=-1,input_layer='word_images', output_layer='sigmoid', print_frequency=1000): ''' Predict PHOCs from the given PHOCNet @param phocnet: caffe.Net A pretrained PHOCNet. The first layer of the PHOCNet must be an InputLayer (no LMDB or MemoryDataLayers) @param word_img_list: list of ndarrays A list of word images for which to predict the PHOCs. Every image in the last has to be a single channel gray-scale or binary ndarray in the range from 0 (black) to 255 (white). @param min_img_width_height: int The minimum height or width of an image to be passed to the PHOCNet. If an image in the word_img_list is smaller than the supplied number it is automatically resized before processed by the CNN. Default: -1 @param input_layer: str The name of the input layer blob. Default: word_images @param output_layer: str The name of the output layer blob. Default: sigmoid @param print_frequency: int Output is generated after this amount of images has been prcessed by the PHOCNet. ''' output = [] logger = logging.getLogger('NetOutput') logger.info('Evaluating net...') for idx, word_img in enumerate(word_img_list): # scale to correct pixel values (0 = background, 1 = text) word_img = word_img.astype(np.float32) word_img -= 255.0 word_img /= -255.0 # check size if np.amin(word_img.shape[:2]) < min_img_width_height: scale = float(min_img_width_height+1)/float(np.amin(word_img.shape[:2])) new_shape = (int(scale*word_img.shape[0]), int(scale*word_img.shape[1])) word_img = resize(image=word_img, output_shape=new_shape) word_img = word_img.reshape((1,1,) + word_img.shape).astype(np.float32) # reshape the PHOCNet phocnet.blobs[input_layer].reshape(*word_img.shape) phocnet.reshape() # forward the word image through the PHOCNet phocnet.blobs[input_layer].data[...] = word_img output.append(phocnet.forward()[output_layer].flatten()) if ((idx+1)%print_frequency == 0 or (idx+1) == len(word_img_list)): logger.debug(' [ %*d / %d ]', len(str(len(word_img_list))), idx+1, len(word_img_list)) return np.vstack(output) def calc_map_from_cnn_features(solver, test_iterations, metric): net_output = np.zeros((test_iterations, solver.test_nets[0].blobs['sigmoid'].data.flatten().shape[0])) labels = np.zeros(test_iterations) for idx in xrange(solver.param.test_iter[0]): # calculate the net output solver.test_nets[0].forward() net_output[idx] = solver.test_nets[0].blobs['sigmoid'].data.flatten() labels[idx] = solver.test_nets[0].blobs['label'].data.flatten() # calculate mAP _, ave_precs = map_from_feature_matrix(features=net_output, labels=labels, metric=metric, drop_first=True) # some queries might not have a relevant sample in the test set # -> exclude them mean_ap = np.mean(ave_precs[ave_precs > 0]) return mean_ap, ave_precs
3,594
44.506329
113
py
phocnet
phocnet-master/src/phocnet/evaluation/retrieval.py
''' Created on Jul 10, 2016 @author: ssudholt ''' import numpy as np from scipy.spatial.distance import pdist, squareform, cdist def map_from_feature_matrix(features, labels, metric, drop_first): ''' Computes mAP and APs from a given matrix of feature vectors Each sample is used as a query once and all the other samples are used for testing. The user can specify whether he wants to include the query in the test results as well or not. Args: features (2d-ndarray): the feature representation from which to compute the mAP labels (1d-ndarray or list): the labels corresponding to the features (either numeric or characters) metric (string): the metric to be used in calculating the mAP drop_first (bool): whether to drop the first retrieval result or not ''' # argument error checks if features.shape[0] != len(labels): raise ValueError('The number of feature vectors and number of labels must match') # compute the pairwise distances from the # features dists = pdist(X=features, metric=metric) dists = squareform(dists) inds = np.argsort(dists, axis=1) retr_mat = np.tile(labels, (features.shape[0],1)) # compute two matrices for selecting rows and columns # from the label matrix # -> advanced indexing row_selector = np.transpose(np.tile(np.arange(features.shape[0]), (features.shape[0],1))) retr_mat = retr_mat[row_selector, inds] # create the relevance matrix rel_matrix = retr_mat == np.atleast_2d(labels).T if drop_first: rel_matrix = rel_matrix[:,1:] # calculate mAP and APs map_calc = MeanAveragePrecision() avg_precs = np.array([map_calc.average_precision(row) for row in rel_matrix]) mAP = np.mean(avg_precs) return mAP, avg_precs def map_from_query_test_feature_matrices(query_features, test_features, query_labels, test_labels, metric, drop_first=False): ''' Computes mAP and APs for a given matrix of query representations and another matrix of test representations Each query is used once to rank the test samples. Args: query_features (2d-ndarray): the feature representation for the queries query_labels (1d-ndarray or list): the labels corresponding to the queries (either numeric or characters) test_features (2d-ndarray): the feature representation for the test samples test_labels (1d-ndarray or list): the labels corresponding to the test samples (either numeric or characters) metric (string): the metric to be used in calculating the mAP drop_first (bool): whether to drop the first retrieval result or not ''' # some argument error checking if query_features.shape[1] != test_features.shape[1]: raise ValueError('Shape mismatch') if query_features.shape[0] != len(query_labels): raise ValueError('The number of query feature vectors and query labels does not match') if test_features.shape[0] != len(test_labels): raise ValueError('The number of test feature vectors and test labels does not match') # compute the nearest neighbors dist_mat = cdist(XA=query_features, XB=test_features, metric=metric) retrieval_indices = np.argsort(dist_mat, axis=1) # create the retrieval matrix retr_mat = np.tile(test_labels, (len(query_labels),1)) row_selector = np.transpose(np.tile(np.arange(len(query_labels)), (len(test_labels),1))) retr_mat = retr_mat[row_selector, retrieval_indices] # create the relevance matrix relevance_matrix = retr_mat == np.atleast_2d(query_labels).T if drop_first: relevance_matrix = relevance_matrix[:,1:] # calculate mAP and APs mapCalc = MeanAveragePrecision() avg_precs = np.array([mapCalc.average_precision(row) for row in relevance_matrix], ndmin=2).flatten() mAP = np.mean(avg_precs) return mAP, avg_precs class IterativeMean(object): ''' Class for iteratively computing a mean. With every new value (@see: _add_value) the mean will be updated ''' def __init__(self, mean_init=0.0): self.__mean = mean_init self.__N = 0.0 def add_value(self, value): ''' Updates the mean with respect to value Args: value (float): The value that will be incorporated in the mean ''' self.__mean = (self.__N / (self.__N + 1)) * self.__mean + (1.0 / (self.__N + 1)) * value self.__N += 1 def get_mean(self): return self.__mean def reset(self): self.__mean = 0.0 self.__N = 0.0 class MeanAveragePrecision(IterativeMean): ''' Computes average precision values and iteratively updates their mean ''' def __init__(self): super(MeanAveragePrecision, self).__init__() def average_precision(self, ret_vec_relevance, gt_relevance_num=None): ''' Computes the average precision and updates the mean average precision Args: ret_vec_relevance (1d-ndarray): array containing ground truth (gt) relevance values gt_relevance_num (int): The number of relevant samples in retrieval. If None the sum over the retrieval gt list is used. ''' ret_vec_cumsum = np.cumsum(ret_vec_relevance, dtype=float) ret_vec_range = np.arange(1, ret_vec_relevance.size + 1) ret_vec_precision = ret_vec_cumsum / ret_vec_range if gt_relevance_num is None: n_relevance = ret_vec_relevance.sum() else: n_relevance = gt_relevance_num if n_relevance > 0: ret_vec_ap = (ret_vec_precision * ret_vec_relevance).sum() / n_relevance else: ret_vec_ap = 0.0 super(MeanAveragePrecision, self).add_value(ret_vec_ap) return ret_vec_ap
6,032
38.690789
117
py
phocnet
phocnet-master/src/phocnet/evaluation/time.py
''' Created on Jul 10, 2016 @author: ssudholt ''' def convert_secs2HHMMSS(secs): ''' Takes as input a float/int representing a timing interval in seconds and converts it to a string in the format hh:mm:ss ''' secs = int(secs) m, s = divmod(secs, 60) h, m = divmod(m, 60) return'%dh%02dm%02ds' % (h, m, s)
337
23.142857
72
py
phocnet
phocnet-master/src/phocnet/evaluation/__init__.py
0
0
0
py
phocnet
phocnet-master/src/phocnet/evaluation/phocnet_evaluator.py
''' Created on Aug 29, 2016 @author: ssudholt ''' import logging import os import caffe import numpy as np from skimage.transform import resize from phocnet.caffe.model_proto_generator import ModelProtoGenerator from phocnet.io.xml_io import XMLReader from phocnet.io.context_manager import Suppressor from phocnet.attributes.phoc import unigrams_from_word_list, build_phoc,\ get_most_common_n_grams from phocnet.io.files import write_list from phocnet.evaluation.retrieval import map_from_feature_matrix,\ map_from_query_test_feature_matrices from phocnet.io import word_list class PHOCNetEvaluation(object): def __init__(self): logging_format = '[%(asctime)-19s, %(name)s] %(message)s' logging.basicConfig(level=logging.INFO, format=logging_format) self.logger = logging.getLogger(self.__class__.__name__) def predict_and_save_phocs(self,phocnet_bin_path, train_xml_file, test_xml_file, gpu_id, debug_mode, doc_img_dir, phoc_unigram_levels, deploy_proto_path, phoc_size, output_dir, no_bigrams, annotation_delimiter): self.logger.info('--- Predict and save PHOCS ---') train_list = self._load_word_list_from_xml(train_xml_file, doc_img_dir) test_list = self._load_word_list_from_xml(test_xml_file, doc_img_dir) phoc_unigrams = unigrams_from_word_list(word_list=train_list, split_character=annotation_delimiter) phoc_size = np.sum(phoc_unigram_levels)*len(phoc_unigrams) if not no_bigrams: phoc_size += 100 phocnet = self._load_pretrained_phocnet(phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size) self.logger.info('Predicting PHOCs for %d test words', len(test_list)) phocs = self._net_output_for_word_list(word_list=test_list, cnn=phocnet, suppress_caffe_output=not debug_mode) self._save_phocs(phocs, output_dir) def extract_unigrams(self, word_xml_file, doc_img_dir, annotation_delimiter): self.logger.info('--- Extract Unigrams ---') self.logger.info('Loading XML file from: %s...', word_xml_file) xml_reader = XMLReader(make_lower_case=True) dataset_name, word_list = xml_reader.load_word_list_from_READ_xml(xml_filename=word_xml_file, img_dir=doc_img_dir) self.logger.info('Found dataset: %s', dataset_name) self.logger.info('Saving unigrams to current working directory...') phoc_unigrams = unigrams_from_word_list(word_list=word_list, split_character=annotation_delimiter) idx_list = ['%d: %s' % elem for elem in enumerate(phoc_unigrams)] write_list(file_path='phoc_unigrams.txt', line_list=idx_list) def eval_qbs(self, phocnet_bin_path, train_xml_file, test_xml_file, phoc_unigram_levels, gpu_id, debug_mode, doc_img_dir, deploy_proto_path, metric, annotation_delimiter, no_bigrams): self.logger.info('--- Query-by-String Evaluation ---') train_list = self._load_word_list_from_xml(train_xml_file, doc_img_dir) test_list = self._load_word_list_from_xml(test_xml_file, doc_img_dir) phoc_unigrams = unigrams_from_word_list(word_list=train_list, split_character=annotation_delimiter) phoc_size = np.sum(phoc_unigram_levels)*len(phoc_unigrams) if no_bigrams: n_bigrams = 0 bigrams = None bigram_levels = None else: n_bigrams = 50 bigrams = get_most_common_n_grams(words=[word.get_transcription() for word in train_list], num_results=n_bigrams, n=2) bigram_levels = [2] phoc_size += 100 # Set CPU/GPU mode if gpu_id != None: self.logger.info('Setting Caffe to GPU mode using device %d', gpu_id) caffe.set_mode_gpu() caffe.set_device(gpu_id) else: self.logger.info('Setting Caffe to CPU mode') caffe.set_mode_cpu() phocnet = self._load_pretrained_phocnet(phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size) self.logger.info('Predicting PHOCs for %d test words', len(test_list)) test_phocs = self._net_output_for_word_list(word_list=test_list, cnn=phocnet, suppress_caffe_output=not debug_mode) test_strings = [word.get_transcription() for word in test_list] qry_strings = list(sorted(set(test_strings))) qry_phocs = build_phoc(words=qry_strings, phoc_unigrams=phoc_unigrams, unigram_levels=phoc_unigram_levels, split_character=annotation_delimiter, phoc_bigrams=bigrams, bigram_levels=bigram_levels) self.logger.info('Calculating mAP...') mean_ap, _ = map_from_query_test_feature_matrices(query_features=qry_phocs, test_features=test_phocs, query_labels=qry_strings, test_labels=test_strings, metric=metric, drop_first=False) self.logger.info('mAP: %f', mean_ap*100) def eval_qbe(self, phocnet_bin_path, train_xml_file, test_xml_file, gpu_id, debug_mode, doc_img_dir, annotation_delimiter, deploy_proto_path, metric, phoc_unigram_levels, no_bigrams): self.logger.info('--- Query-by-Example Evaluation ---') train_list = self._load_word_list_from_xml(train_xml_file, doc_img_dir) test_list = self._load_word_list_from_xml(test_xml_file, doc_img_dir) phoc_unigrams = unigrams_from_word_list(word_list=train_list, split_character=annotation_delimiter) phoc_size = np.sum(phoc_unigram_levels)*len(phoc_unigrams) if not no_bigrams: phoc_size += 100 # Set CPU/GPU mode if gpu_id != None: self.logger.info('Setting Caffe to GPU mode using device %d', gpu_id) caffe.set_mode_gpu() caffe.set_device(gpu_id) else: self.logger.info('Setting Caffe to CPU mode') caffe.set_mode_cpu() phocnet = self._load_pretrained_phocnet(phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size) self.logger.info('Predicting PHOCs for %d test words', len(test_list)) phocs = self._net_output_for_word_list(word_list=test_list, cnn=phocnet, suppress_caffe_output=not debug_mode) self.logger.info('Calculating mAP...') _, avg_precs = map_from_feature_matrix(features=phocs, labels=[word.get_transcription() for word in test_list], metric=metric, drop_first=True) self.logger.info('mAP: %f', np.mean(avg_precs[avg_precs > 0])*100) def _net_output_for_word_list(self, word_list, cnn, min_img_width_height=26,input_layer='word_images', output_layer='sigmoid', suppress_caffe_output=False): output = [] for idx, word in enumerate(word_list): # scale to correct pixel values (0 = background, 1 = text) word_img = word.get_word_image().astype(np.float32) word_img -= 255.0 word_img /= -255.0 # check size if np.amin(word_img.shape[:2]) < min_img_width_height: scale = float(min_img_width_height+1)/float(np.amin(word_img.shape[:2])) new_shape = (int(scale*word_img.shape[0]), int(scale*word_img.shape[1])) word_img = resize(image=word_img, output_shape=new_shape) word_img = word_img.reshape((1,1,) + word_img.shape).astype(np.float32) # reshape the PHOCNet cnn.blobs[input_layer].reshape(*word_img.shape) cnn.reshape() # forward the word image through the PHOCNet cnn.blobs[input_layer].data[...] = word_img if suppress_caffe_output: with Suppressor(): output.append(cnn.forward()[output_layer].flatten()) else: output.append(cnn.forward()[output_layer].flatten()) if ((idx+1)%100 == 0 or (idx+1) == len(word_list)): self.logger.info(' [ %*d / %d ]', len(str(len(word_list))), idx+1, len(word_list)) return np.vstack(output) def _load_pretrained_phocnet(self, phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size): # create a deploy proto file self.logger.info('Saving PHOCNet deploy proto file to %s...', deploy_proto_path) mpg = ModelProtoGenerator(initialization='msra', use_cudnn_engine=gpu_id is not None) proto = mpg.get_phocnet(word_image_lmdb_path=None, phoc_lmdb_path=None, phoc_size=phoc_size, generate_deploy=True) with open(deploy_proto_path, 'w') as proto_file: proto_file.write(str(proto)) # create the Caffe PHOCNet object self.logger.info('Creating PHOCNet...') if debug_mode: phocnet = caffe.Net(deploy_proto_path, phocnet_bin_path, caffe.TEST) else: with Suppressor(): phocnet = caffe.Net(deploy_proto_path, phocnet_bin_path, caffe.TEST) return phocnet def _load_word_list_from_xml(self, word_xml_file, doc_img_dir): self.logger.info('Loading XML file from: %s...', word_xml_file) dataset_name, word_list = XMLReader().load_word_list_from_READ_xml(xml_filename=word_xml_file, img_dir=doc_img_dir) self.logger.info('Found dataset: %s', dataset_name) return word_list def _setup_caffe(self, gpu_id): if gpu_id != None: self.logger.info('Setting Caffe to GPU mode using device %d', gpu_id) caffe.set_mode_gpu() caffe.set_device(gpu_id) else: self.logger.info('Setting Caffe to CPU mode') caffe.set_mode_cpu() def _predict_phocs(self, phocnet_bin_path, word_xml_file, gpu_id, debug_mode, doc_img_dir, deploy_proto_path, phoc_size): self._setup_caffe(gpu_id) # load everything word_list = self._load_word_list_from_xml(word_xml_file, doc_img_dir) phocnet = self._load_pretrained_phocnet(phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size) # compute the PHOCs self.logger.info('Predicting PHOCs...') phocs = self._net_output_for_word_list(word_list=word_list, cnn=phocnet, suppress_caffe_output=not debug_mode) return phocs def _predict_phocs_for_sliding_window(self, net, word, frame_width, step_size, phoc_size, padding=True, input_layer_name='word_images', output_layer_name='sigmoid'): # load and transform image for PHOCNet img = word.get_word_image().astype(np.float32) img -= 255 img /= -255 # pad if requested if padding: img = np.pad(array=img, pad_width=((0,0), (frame_width/2,frame_width/2)), mode='constant') # determine the output mat shape and init the mat phoc_mat = np.zeros((len(xrange(0, img.shape[1]-frame_width, step_size)), phoc_size), dtype=np.float32) # push every frame through the net for idx, offset in enumerate(xrange(0, img.shape[1]-frame_width, step_size)): frame = img[:, offset:offset+frame_width] # convert to 4D array for Caffe frame = frame.reshape((1,1,) + frame.shape) # push the frame through the net net.blobs[input_layer_name].reshape(*frame.shape) net.reshape() net.blobs[input_layer_name].data[...] = frame phoc = net.forward()[output_layer_name].flatten() phoc_mat[idx] = phoc return phoc_mat def _save_phocs(self, phocs, output_dir): self.logger.info('Saving PHOCs as .npy-file...') np.save(os.path.join(output_dir, 'phocs.npy'), phocs) self.logger.info('Finished')
12,724
51.80083
136
py
phocnet
phocnet-master/src/phocnet/io/word_container.py
''' Created on Aug 29, 2014 This module holds simple container classes for storing word images for the PHOCNet experiments @author: ssudholt ''' import cv2 import numpy as np class SimpleWordContainer(object): def __init__(self, transcription, bounding_box, image_path): self.__transcription = transcription self.__bounding_box = bounding_box self.__image_path = image_path def get_transcription(self): return self.__transcription def get_bounding_box(self): return self.__bounding_box def get_image_path(self): return self.__image_path def set_transcription(self, value): self.__transcription = value def set_bounding_box(self, value): self.__bounding_box = value def set_image_path(self, value): self.__image_path = value def del_transcription(self): del self.__transcription def del_bounding_box(self): del self.__bounding_box def del_image_path(self): del self.__image_path def get_word_image(self, gray_scale=True): col_type = None if gray_scale: col_type = cv2.CV_LOAD_IMAGE_GRAYSCALE else: col_type = cv2.CV_LOAD_IMAGE_COLOR # load the image ul = self.bounding_box['upperLeft'] wh = self.bounding_box['widthHeight'] img = cv2.imread(self.image_path, col_type) if not np.all(self.bounding_box['widthHeight'] == -1): img = img[ul[1]:ul[1]+wh[1], ul[0]:ul[0]+wh[0]] return img transcription = property(get_transcription, set_transcription, del_transcription, "transcription's docstring") bounding_box = property(get_bounding_box, set_bounding_box, del_bounding_box, "bounding_box's docstring") image_path = property(get_image_path, set_image_path, del_image_path, "image_path's docstring") class DocImageWordContainer(SimpleWordContainer): def __init__(self, transcription, page, bounding_box, id_on_page, image_path): super(DocImageWordContainer, self).__init__(transcription, bounding_box, image_path) self.__page = page self.__id_on_page = id_on_page def get_page(self): return self.__page def get_id_on_page(self): return self.__id_on_page def set_page(self, value): self.__page = value def set_id_on_page(self, value): self.__id_on_page = value def del_page(self): del self.__page def del_id_on_page(self): del self.__id_on_page page = property(get_page, set_page, del_page, "page's docstring") id_on_page = property(get_id_on_page, set_id_on_page, del_id_on_page, "id_on_page's docstring")
2,747
25.423077
114
py
phocnet
phocnet-master/src/phocnet/io/context_manager.py
''' Created on Aug 28, 2014 @author: ssudholt ''' import os class Suppressor(object): ''' A context manager for doing a "deep suppression" of stdout and stderr in Python, i.e. will suppress all print, even if the print originates in a compiled C/Fortran sub-function. This will not suppress raised exceptions, since exceptions are printed to stderr just before a script exits, and after the context manager has exited (at least, I think that is why it lets exceptions through). ''' def __init__(self): # Open a pair of null files self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)] # Save the actual stdout (1) and stderr (2) file descriptors. self.save_fds = (os.dup(1), os.dup(2)) def __enter__(self): # Assign the null pointers to stdout and stderr. os.dup2(self.null_fds[0],1) os.dup2(self.null_fds[1],2) def __exit__(self, *_): # Re-assign the real stdout/stderr back to (1) and (2) os.dup2(self.save_fds[0],1) os.dup2(self.save_fds[1],2) # Close the null files os.close(self.null_fds[0]) os.close(self.null_fds[1])
1,201
31.486486
77
py
phocnet
phocnet-master/src/phocnet/io/__init__.py
0
0
0
py
phocnet
phocnet-master/src/phocnet/io/word_list.py
''' Created on Jul 8, 2016 @author: ssudholt ''' import os from xml.etree import ElementTree import numpy as np from phocnet.io.word_container import DocImageWordContainer def load_word_list_from_READ_xml(xml_file_path, doc_img_dir, dataset_name): tree = ElementTree.parse(os.path.join(xml_file_path)) root = tree.getroot() # check if we have the correct XML if root.attrib['dataset'] != dataset_name: raise ValueError('The supplied XML file at \'%s\' is not for the %s dataset' % (xml_file_path, dataset_name)) # iterate through all word bounding boxes and put them in a word list word_list = [] for word_idx, word_elem in enumerate(root.findall('spot')): word_list.append(DocImageWordContainer(transcription=unicode(word_elem.attrib['word']).lower(), page=word_elem.attrib['image'].split('.')[0], bounding_box=dict(upperLeft=np.array([int(word_elem.attrib['x']), int(word_elem.attrib['y'])]), widthHeight=np.array([int(word_elem.attrib['w']), int(word_elem.attrib['h'])])), id_on_page=word_idx, image_path=os.path.join(doc_img_dir, word_elem.attrib['image']))) return word_list
1,569
49.645161
118
py
phocnet
phocnet-master/src/phocnet/io/files.py
''' Created on Jul 10, 2016 @author: ssudholt ''' import os def save_prototxt(file_path, proto_object, header_comment=None): with open(file_path, 'w') as output_file: if header_comment is not None: output_file.write('#' + header_comment + '\n') output_file.write(str(proto_object)) def read_list(file_path): if not os.path.exists(file_path): raise ValueError('File for reading list does NOT exist: ' + file_path) linelist = [] with open(file_path) as stream: for line in stream: line = line.strip() if line != '': linelist.append(line) return linelist def write_list(file_path, line_list): ''' Writes a list into the given file object file_path: the file path that will be written to line_list: the list of strings that will be written ''' with open(file_path, 'w') as f: for l in line_list: f.write(str(l) + '\n')
1,013
27.166667
82
py
phocnet
phocnet-master/src/phocnet/io/xml_io.py
''' Created on Jul 9, 2016 @author: ssudholt ''' import logging import os import xml.etree.ElementTree as ET import numpy as np from phocnet.io.word_container import DocImageWordContainer class XMLReader(object): ''' Class for reading a training and test set from two READ-style XML files. ''' def __init__(self, make_lower_case=True): ''' Constructor Args: make_lower_case (bool): whether to convert XML annotation values to lower case ''' self.logger = logging.getLogger('XMLReader') self.make_lower_case = make_lower_case def load_train_test_xml(self, train_xml_path, test_xml_path, img_dir): ''' Reads two XML files as training and test partitions into word lists and returns them as well as the corresponding dataset name. Args: train_xml_path (str): the path to the READ-style training XML file test_xml_path (str): the path to the READ-style test XML file ''' self.logger.info('Loading training XML at %s', train_xml_path) train_dataset_name, train_list = self.load_word_list_from_READ_xml(xml_filename=train_xml_path, img_dir=img_dir) self.logger.info('Loading test XML at %s', test_xml_path) test_dataset_name, test_list = self.load_word_list_from_READ_xml(xml_filename=test_xml_path, img_dir=img_dir) # check if the two datasets match if train_dataset_name != test_dataset_name: raise ValueError('Training and test XML do not belong to the same dataset!') return train_dataset_name, train_list, test_list def load_word_list_from_READ_xml(self, xml_filename, img_dir): self.logger.debug('Using XML-File at %s and image directory %s...', xml_filename, img_dir) tree = ET.parse(os.path.join(xml_filename)) root = tree.getroot() # load the dataset name dataset_name = root.attrib['dataset'] # iterate through all word bounding boxes and put them in a word list word_list = [] for word_idx, word_elem in enumerate(root.findall('spot')): transcription = unicode(word_elem.attrib['word']) if self.make_lower_case: transcription = transcription.lower() word_list.append(DocImageWordContainer(transcription=transcription, page=word_elem.attrib['image'].split('.')[0], bounding_box=dict(upperLeft=np.array([int(word_elem.attrib['x']), int(word_elem.attrib['y'])]), widthHeight=np.array([int(word_elem.attrib['w']), int(word_elem.attrib['h'])])), id_on_page=word_idx, image_path=os.path.join(img_dir, word_elem.attrib['image']))) return dataset_name, word_list
3,251
45.457143
122
py
phocnet
phocnet-master/src/phocnet/training/phocnet_trainer.py
''' Created on Aug 29, 2016 @author: ssudholt ''' import logging import os import time import caffe import numpy as np from skimage.transform import resize from phocnet.attributes.phoc import build_phoc, unigrams_from_word_list,\ get_most_common_n_grams from phocnet.caffe.model_proto_generator import ModelProtoGenerator from phocnet.caffe.solver_proto_generator import generate_solver_proto from phocnet.caffe.lmdb_creator import CaffeLMDBCreator from phocnet.caffe.augmentation import AugmentationCreator from phocnet.evaluation.time import convert_secs2HHMMSS from phocnet.evaluation.cnn import calc_map_from_cnn_features from phocnet.io.xml_io import XMLReader from phocnet.io.files import save_prototxt, write_list from phocnet.io.context_manager import Suppressor from phocnet.numpy.numpy_helper import NumpyHelper class PHOCNetTrainer(object): ''' Driver class for all PHOCNet experiments ''' def __init__(self, doc_img_dir, train_annotation_file, test_annotation_file, proto_dir, n_train_images, lmdb_dir, save_net_dir, phoc_unigram_levels, recreate_lmdbs, gpu_id, learning_rate, momentum, weight_decay, batch_size, test_interval, display, max_iter, step_size, gamma, debug_mode, metric, annotation_delimiter, use_lower_case_only, use_bigrams): ''' The constructor Args: doc_img_dir (str): the location of the document images for the given dataset train_annotation_file (str): the absolute path to the READ-style annotation file for the training samples test_annotation_file (str): the absolute path to the READ-style annotation file for the test samples proto_dir (str): absolute path where to save the Caffe protobuffer files n_train_images (int): the total number of training images to be used lmdb_dir (str): directory to save the LMDB files into save_net_dir (str): directory where to save the trained PHOCNet phoc_unigrams_levels (list of int): the list of unigram levels recreate_lmdbs (bool): whether to delete and recompute existing LMDBs debug_mode (bool): flag indicating to run this experiment in debug mode metric (str): metric for comparing the PHOCNet output during test annotation_delimiter (str): delimiter for the annotation in the XML files use_lower_case_only (bool): convert annotation to lower case before creating LMDBs use_bigrams (bool): if true, the PHOC predicted from the net contains bigrams gpu_id (int): the ID of the GPU to use learning_rate (float): the learning rate to be used in training momentum (float): the SGD momentum to be used in training weight_decay (float): the SGD weight decay to be used in training batch_size (int): the number of images to be used in a mini batch test_interval (int): the number of steps after which to evaluate the PHOCNet during training display (int): the number of iterations after which to show the training net loss max_iter (int): the maximum number of SGD iterations step_size (int): the number of iterations after which to reduce the learning rate gamma (float): the factor to multiply the step size with after step_size iterations ''' # store the experiment parameters self.doc_img_dir = doc_img_dir self.train_annotation_file = train_annotation_file self.test_annotation_file = test_annotation_file self.proto_dir = proto_dir self.n_train_images = n_train_images self.lmdb_dir = lmdb_dir self.save_net_dir = save_net_dir self.phoc_unigram_levels = phoc_unigram_levels self.recreate_lmdbs = recreate_lmdbs self.debug_mode = debug_mode self.metric = metric self.annotation_delimiter = annotation_delimiter self.use_lower_case_only = use_lower_case_only self.use_bigrams = use_bigrams # store the Caffe parameters self.gpu_id = gpu_id self.learning_rate = learning_rate self.momentum = momentum self.weight_decay = weight_decay self.batch_size = batch_size self.test_interval = test_interval self.display = display self.max_iter = max_iter self.step_size = step_size self.gamma = gamma # misc members for training/evaluation if self.gpu_id is not None: self.solver_mode = 'GPU' else: self.solver_mode = 'CPU' self.min_image_width_height = 26 self.epoch_map = None self.test_iter = None self.dataset_name = None # set up the logging logging_format = '[%(asctime)-19s, %(name)s] %(message)s' if self.debug_mode: logging_level = logging.DEBUG else: logging_level = logging.INFO logging.basicConfig(level=logging_level, format=logging_format) self.logger = logging.getLogger(self.__class__.__name__) def train_phocnet(self): self.logger.info('--- Running PHOCNet Training ---') # --- Step 1: check if we need to create the LMDBs # load the word lists xml_reader = XMLReader(make_lower_case=self.use_lower_case_only) self.dataset_name, train_list, test_list = xml_reader.load_train_test_xml(train_xml_path=self.train_annotation_file, test_xml_path=self.test_annotation_file, img_dir=self.doc_img_dir) phoc_unigrams = unigrams_from_word_list(word_list=train_list, split_character=self.annotation_delimiter) self.logger.info('PHOC unigrams: %s', ' '.join(phoc_unigrams)) self.test_iter = len(test_list) self.logger.info('Using dataset \'%s\'', self.dataset_name) # check if we need to create LMDBs lmdb_prefix = '%s_nti%d_pul%s' % (self.dataset_name, self.n_train_images, '-'.join([str(elem) for elem in self.phoc_unigram_levels])) train_word_images_lmdb_path = os.path.join(self.lmdb_dir, '%s_train_word_images_lmdb' % lmdb_prefix) train_phoc_lmdb_path = os.path.join(self.lmdb_dir, '%s_train_phocs_lmdb' % lmdb_prefix) test_word_images_lmdb_path = os.path.join(self.lmdb_dir, '%s_test_word_images_lmdb' % lmdb_prefix) test_phoc_lmdb_path = os.path.join(self.lmdb_dir, '%s_test_phocs_lmdb' % lmdb_prefix) lmdbs_exist = (os.path.exists(train_word_images_lmdb_path), os.path.exists(train_phoc_lmdb_path), os.path.exists(test_word_images_lmdb_path), os.path.exists(test_phoc_lmdb_path)) if self.use_bigrams: n_bigrams = 50 bigrams = get_most_common_n_grams(words=[word.get_transcription() for word in train_list], num_results=n_bigrams, n=2) bigram_levels = [2] else: n_bigrams = 0 bigrams = None bigram_levels = None if not np.all(lmdbs_exist) or self.recreate_lmdbs: self.logger.info('Creating LMDBs...') train_phocs = build_phoc(words=[word.get_transcription() for word in train_list], phoc_unigrams=phoc_unigrams, unigram_levels=self.phoc_unigram_levels, phoc_bigrams=bigrams, bigram_levels=bigram_levels, split_character=self.annotation_delimiter, on_unknown_unigram='warn') test_phocs = build_phoc(words=[word.get_transcription() for word in test_list], phoc_unigrams=phoc_unigrams, unigram_levels=self.phoc_unigram_levels, phoc_bigrams=bigrams, bigram_levels=bigram_levels, split_character=self.annotation_delimiter, on_unknown_unigram='warn') self._create_train_test_phocs_lmdbs(train_list=train_list, train_phocs=train_phocs, test_list=test_list, test_phocs=test_phocs, train_word_images_lmdb_path=train_word_images_lmdb_path, train_phoc_lmdb_path=train_phoc_lmdb_path, test_word_images_lmdb_path=test_word_images_lmdb_path, test_phoc_lmdb_path=test_phoc_lmdb_path) else: self.logger.info('Found LMDBs...') # --- Step 2: create the proto files self.logger.info('Saving proto files...') # prepare the output paths train_proto_path = os.path.join(self.proto_dir, 'train_phocnet_%s.prototxt' % self.dataset_name) test_proto_path = os.path.join(self.proto_dir, 'test_phocnet_%s.prototxt' % self.dataset_name) solver_proto_path = os.path.join(self.proto_dir, 'solver_phocnet_%s.prototxt' % self.dataset_name) # generate the proto files n_attributes = np.sum(self.phoc_unigram_levels)*len(phoc_unigrams) if self.use_bigrams: n_attributes += np.sum(bigram_levels)*n_bigrams mpg = ModelProtoGenerator(initialization='msra', use_cudnn_engine=self.gpu_id is not None) train_proto = mpg.get_phocnet(word_image_lmdb_path=train_word_images_lmdb_path, phoc_lmdb_path=train_phoc_lmdb_path, phoc_size=n_attributes, generate_deploy=False) test_proto = mpg.get_phocnet(word_image_lmdb_path=test_word_images_lmdb_path, phoc_lmdb_path=test_phoc_lmdb_path, phoc_size=n_attributes, generate_deploy=False) solver_proto = generate_solver_proto(train_net=train_proto_path, test_net=test_proto_path, base_lr=self.learning_rate, momentum=self.momentum, display=self.display, lr_policy='step', gamma=self.gamma, stepsize=self.step_size, solver_mode=self.solver_mode, iter_size=self.batch_size, max_iter=self.max_iter, average_loss=self.display, test_iter=self.test_iter, test_interval=self.test_interval, weight_decay=self.weight_decay) # save the proto files save_prototxt(file_path=train_proto_path, proto_object=train_proto, header_comment='Train PHOCNet %s' % self.dataset_name) save_prototxt(file_path=test_proto_path, proto_object=test_proto, header_comment='Test PHOCNet %s' % self.dataset_name) save_prototxt(file_path=solver_proto_path, proto_object=solver_proto, header_comment='Solver PHOCNet %s' % self.dataset_name) # --- Step 3: train the PHOCNet self.logger.info('Starting SGD...') self._run_sgd(solver_proto_path=solver_proto_path) def pretrain_callback(self, solver): ''' Method called before starting the training ''' # init numpy arrays for mAP results epochs = self.max_iter/self.test_interval self.epoch_map = np.zeros(epochs+1) self.epoch_map[0], _ = calc_map_from_cnn_features(solver=solver, test_iterations=self.test_iter, metric=self.metric) self.logger.info('mAP: %f', self.epoch_map[0]) def test_callback(self, solver, epoch): ''' Method called every self.test_interval iterations during training ''' self.logger.info('Evaluating CNN after %d steps:', epoch*solver.param.test_interval) self.epoch_map[epoch+1], _ = calc_map_from_cnn_features(solver=solver, test_iterations=self.test_iter, metric=self.metric) self.logger.info('mAP: %f', self.epoch_map[epoch+1]) def posttrain_callback(self, solver): ''' Method called after finishing the training ''' # if self.save_net is not None, save the PHOCNet to the desired location if self.save_net_dir is not None: filename = 'phocnet_%s_nti%d_pul%s.binaryproto' % (self.dataset_name, self.n_train_images, '-'.join([str(elem) for elem in self.phoc_unigram_levels])) solver.net.save(os.path.join(self.save_net_dir, filename)) def _create_train_test_phocs_lmdbs(self, train_list, train_phocs, test_list, test_phocs, train_word_images_lmdb_path, train_phoc_lmdb_path, test_word_images_lmdb_path, test_phoc_lmdb_path): start_time = time.time() # --- TRAIN IMAGES # find all unique transcriptions and the label map... _, transcription_map = self.__get_unique_transcriptions_and_labelmap(train_list, test_list) # get the numeric training labels plus a random order to insert them into # create the numeric labels and counts train_labels = np.array([transcription_map[word.get_transcription()] for word in train_list]) unique_train_labels, counts = np.unique(train_labels, return_counts=True) # find the number of images that should be present for training per class n_images_per_class = self.n_train_images/unique_train_labels.shape[0] + 1 # create randomly shuffled numbers for later use as keys random_indices = list(xrange(n_images_per_class*unique_train_labels.shape[0])) np.random.shuffle(random_indices) #set random limits for affine transform random_limits = (0.8, 1.1) n_rescales = 0 # loading should be done in gray scale load_grayscale = True # create train LMDB self.logger.info('Creating Training LMDB (%d total word images)', len(random_indices)) lmdb_creator = CaffeLMDBCreator() lmdb_creator.open_dual_lmdb_for_write(image_lmdb_path=train_word_images_lmdb_path, additional_lmdb_path=train_phoc_lmdb_path, create=True) for cur_label, count in zip(unique_train_labels, counts): # find the words for the current class label and the # corresponding PHOC cur_word_indices = np.where(train_labels == cur_label)[0] cur_transcription = train_list[cur_word_indices[0]].get_transcription() cur_phoc = NumpyHelper.get_unique_rows(train_phocs[cur_word_indices]) # unique rows should only return one specific PHOC if cur_phoc.shape[0] != 1: raise ValueError('Extracted more than one PHOC for label %d' % cur_label) cur_phoc = np.atleast_3d(cur_phoc).transpose((2,0,1)).astype(np.uint8) # if there are to many images for the current word image class, # draw from them and cut the rest off if count > n_images_per_class: np.random.shuffle(cur_word_indices) cur_word_indices = cur_word_indices[:n_images_per_class] # load the word images cur_word_images = [] for idx in cur_word_indices: img = train_list[idx].get_word_image(gray_scale=load_grayscale) # check image size img, resized = self.__check_size(img) n_rescales += int(resized) # append to the current word images and # put into LMDB cur_word_images.append(img) key = '%s_%s' % (str(random_indices.pop()).zfill(8), cur_transcription.encode('ascii', 'ignore')) lmdb_creator.put_dual(img_mat=np.atleast_3d(img).transpose((2,0,1)).astype(np.uint8), additional_mat=cur_phoc, label=cur_label, key=key) # extract the extra augmented images # the random limits are the maximum percentage # that the destination point may deviate from the reference point # in the affine transform if len(cur_word_images) < n_images_per_class: # create the warped images inds = np.random.randint(len(cur_word_images), size=n_images_per_class - len(cur_word_images)) for ind in inds: aug_img = AugmentationCreator.create_affine_transform_augmentation(img=cur_word_images[ind], random_limits=random_limits) aug_img = np.atleast_3d(aug_img).transpose((2,0,1)).astype(np.uint8) key = '%s_%s' % (str(random_indices.pop()).zfill(8), cur_transcription.encode('ascii', 'ignore')) lmdb_creator.put_dual(img_mat=aug_img, additional_mat=cur_phoc, label=cur_label, key=key) # wrap up training LMDB creation if len(random_indices) != 0: raise ValueError('Random Indices are not empty, something went wrong during training LMDB creation') lmdb_creator.finish_creation() # write the label map to the LMDBs as well write_list(file_path=train_word_images_lmdb_path + '/label_map.txt', line_list=['%s %s' % elem for elem in transcription_map.items()]) write_list(file_path=train_phoc_lmdb_path + '/label_map.txt', line_list=['%s %s' % elem for elem in transcription_map.items()]) self.logger.info('Finished processing train words (took %s, %d rescales)', convert_secs2HHMMSS(time.time() - start_time), n_rescales) # --- TEST IMAGES self.logger.info('Creating Test LMDB (%d total word images)', len(test_list)) n_rescales = 0 start_time = time.time() lmdb_creator.open_dual_lmdb_for_write(image_lmdb_path=test_word_images_lmdb_path, additional_lmdb_path=test_phoc_lmdb_path, create=True, label_map=transcription_map) for word, phoc in zip(test_list, test_phocs): if word.get_transcription() not in transcription_map: transcription_map[word.get_transcription()] = len(transcription_map) img = word.get_word_image(gray_scale=load_grayscale) img, resized = self.__check_size(img) if img is None: self.logger.warning('!WARNING! Found image with 0 width or height!') else: n_rescales += int(resized) img = np.atleast_3d(img).transpose((2,0,1)).astype(np.uint8) phoc_3d = np.atleast_3d(phoc).transpose((2,0,1)).astype(np.uint8) lmdb_creator.put_dual(img_mat=img, additional_mat=phoc_3d, label=transcription_map[word.get_transcription()]) lmdb_creator.finish_creation() write_list(file_path=test_word_images_lmdb_path + '/label_map.txt', line_list=['%s %s' % elem for elem in transcription_map.items()]) write_list(file_path=test_phoc_lmdb_path + '/label_map.txt', line_list=['%s %s' % elem for elem in transcription_map.items()]) self.logger.info('Finished processing test words (took %s, %d rescales)', convert_secs2HHMMSS(time.time() - start_time), n_rescales) def __check_size(self, img): ''' checks if the image accords to the minimum size requirements Returns: tuple (img, bool): img: the original image if the image size was ok, a resized image otherwise bool: flag indicating whether the image was resized ''' if np.amin(img.shape[:2]) < self.min_image_width_height: if np.amin(img.shape[:2]) == 0: return None, False scale = float(self.min_image_width_height+1)/float(np.amin(img.shape[:2])) new_shape = (int(scale*img.shape[0]), int(scale*img.shape[1])) new_img = resize(image=img, output_shape=new_shape) return new_img, True else: return img, False def __get_unique_transcriptions_and_labelmap(self, train_list, test_list): ''' Returns a list of unique transcriptions for the given train and test lists and creates a dictionary mapping transcriptions to numeric class labels. ''' unique_transcriptions = [word.get_transcription() for word in train_list] unique_transcriptions.extend([word.get_transcription() for word in test_list]) unique_transcriptions = list(set(unique_transcriptions)) transcription_map = dict((k,v) for v,k in enumerate(unique_transcriptions)) return unique_transcriptions, transcription_map def _run_sgd(self, solver_proto_path): ''' Starts the SGD training of the PHOCNet Args: solver_proto_path (str): the absolute path to the solver protobuffer file to use ''' # Set CPU/GPU mode for solver training if self.gpu_id != None: self.logger.info('Setting Caffe to GPU mode using device %d', self.gpu_id) caffe.set_mode_gpu() caffe.set_device(self.gpu_id) else: self.logger.info('Setting Caffe to CPU mode') caffe.set_mode_cpu() # Create SGD solver self.logger.info('Using solver protofile at %s', solver_proto_path) solver = self.__get_solver(solver_proto_path) epochs = self.max_iter/self.test_interval # run test on the net before training self.logger.info('Running pre-train evaluation') self.pretrain_callback(solver=solver) # run the training self.logger.info('Finished Setup, running SGD') for epoch in xrange(epochs): # run training until we want to test self.__solver_step(solver, self.test_interval) # run test callback after test_interval iterations self.logger.debug('Running test evaluation') self.test_callback(solver=solver, epoch=epoch) # if we have iterations left to compute, do so iters_left = self.max_iter % self.test_interval if iters_left > 0: self.__solver_step(solver, iters_left) # run post train callback self.logger.info('Running post-train evaluation') self.posttrain_callback(solver=solver) # return the solver return solver def __solver_step(self, solver, steps): ''' Runs Caffe solver suppressing Caffe output if necessary ''' if not self.debug_mode: with Suppressor(): solver.step(steps) else: solver.step(steps) def __get_solver(self, solver_proto_path): ''' Returns a caffe.SGDSolver for the given protofile path, ignoring Caffe command line chatter if debug mode is not set to True. ''' if not self.debug_mode: # disable Caffe init chatter when not in debug with Suppressor(): return caffe.SGDSolver(solver_proto_path) else: return caffe.SGDSolver(solver_proto_path)
24,351
53.970655
141
py
phocnet
phocnet-master/src/phocnet/training/__init__.py
0
0
0
py
phocnet
phocnet-master/src/phocnet/numpy/numpy_helper.py
''' Created on Feb 25, 2015 @author: ssudholt ''' import numpy as np class NumpyHelper(object): @staticmethod def get_unique_rows(arr, return_indices=False): ''' Returns the unique rows of the supplied array this code was originally proposed at stackoverflow http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array Args: arr (2d-ndarray): the array from which to extract the unique rows return_indices (bool): if true, the indices corresponding to the unique rows in arr are returned as well ''' b = np.ascontiguousarray(arr).view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[1]))) _, idx = np.unique(b, return_index=True) # return the result if return_indices: return arr[idx], idx else: return arr[idx]
970
31.366667
99
py
phocnet
phocnet-master/src/phocnet/numpy/__init__.py
0
0
0
py
phocnet
phocnet-master/src/phocnet/attributes/__init__.py
0
0
0
py
phocnet
phocnet-master/src/phocnet/attributes/phoc.py
''' Created on Dec 17, 2015 @author: ssudholt ''' import logging import numpy as np def get_most_common_n_grams(words, num_results=50, n=2): ''' Calculates the 50 (default) most common bigrams (default) from a list of pages, where each page is a list of WordData objects. Args: words (list of str): List containing the word strings from which to extract the bigrams num_results (int): Number of n-grams returned. n (int): length of n-grams. Returns: most common <n>-grams ''' ngrams = {} for w in words: w_ngrams = get_n_grams(w, n) for ng in w_ngrams: ngrams[ng] = ngrams.get(ng, 0) + 1 sorted_list = sorted(ngrams.items(), key=lambda x: x[1], reverse=True) top_ngrams = sorted_list[:num_results] return {k: i for i, (k, _) in enumerate(top_ngrams)} def get_n_grams(word, n): ''' Calculates list of ngrams for a given word. Args: word (str): Word to calculate ngrams for. n (int): Maximal ngram size: n=3 extracts 1-, 2- and 3-grams. Returns: List of ngrams as strings. ''' return [word[i:i+n]for i in range(len(word)-n+1)] def build_phoc(words, phoc_unigrams, unigram_levels, bigram_levels=None, phoc_bigrams=None, split_character=None, on_unknown_unigram='error'): ''' Calculate Pyramidal Histogram of Characters (PHOC) descriptor (see Almazan 2014). Args: word (str): word to calculate descriptor for phoc_unigrams (str): string of all unigrams to use in the PHOC unigram_levels (list of int): the levels for the unigrams in PHOC phoc_bigrams (list of str): list of bigrams to be used in the PHOC phoc_bigram_levls (list of int): the levels of the bigrams in the PHOC split_character (str): special character to split the word strings into characters on_unknown_unigram (str): What to do if a unigram appearing in a word is not among the supplied phoc_unigrams. Possible: 'warn', 'error' Returns: the PHOC for the given word ''' # prepare output matrix logger = logging.getLogger('PHOCGenerator') if on_unknown_unigram not in ['error', 'warn']: raise ValueError('I don\'t know the on_unknown_unigram parameter \'%s\'' % on_unknown_unigram) phoc_size = len(phoc_unigrams) * np.sum(unigram_levels) if phoc_bigrams is not None: phoc_size += len(phoc_bigrams)*np.sum(bigram_levels) phocs = np.zeros((len(words), phoc_size)) # prepare some lambda functions occupancy = lambda k, n: [float(k) / n, float(k+1) / n] overlap = lambda a, b: [max(a[0], b[0]), min(a[1], b[1])] size = lambda region: region[1] - region[0] # map from character to alphabet position char_indices = {d: i for i, d in enumerate(phoc_unigrams)} # iterate through all the words for word_index, word in enumerate(words): if split_character is not None: word = word.split(split_character) n = len(word) for index, char in enumerate(word): char_occ = occupancy(index, n) if char not in char_indices: if on_unknown_unigram == 'warn': logger.warn('The unigram \'%s\' is unknown, skipping this character', char) continue else: logger.fatal('The unigram \'%s\' is unknown', char) raise ValueError() char_index = char_indices[char] for level in unigram_levels: for region in range(level): region_occ = occupancy(region, level) if size(overlap(char_occ, region_occ)) / size(char_occ) >= 0.5: feat_vec_index = sum([l for l in unigram_levels if l < level]) * len(phoc_unigrams) + region * len(phoc_unigrams) + char_index phocs[word_index, feat_vec_index] = 1 # add bigrams if phoc_bigrams is not None: ngram_features = np.zeros(len(phoc_bigrams)*np.sum(bigram_levels)) ngram_occupancy = lambda k, n: [float(k) / n, float(k+2) / n] for i in range(n-1): ngram = word[i:i+2] if phoc_bigrams.get(ngram, 0) == 0: continue occ = ngram_occupancy(i, n) for level in bigram_levels: for region in range(level): region_occ = occupancy(region, level) overlap_size = size(overlap(occ, region_occ)) / size(occ) if overlap_size >= 0.5: ngram_features[region * len(phoc_bigrams) + phoc_bigrams[ngram]] = 1 phocs[word_index, -ngram_features.shape[0]:] = ngram_features return phocs def unigrams_from_word_list(word_list, split_character=None): if split_character is not None: unigrams = [elem for word in word_list for elem in word.get_transcription().split(split_character)] else: unigrams = [elem for word in word_list for elem in word.get_transcription()] unigrams = list(sorted(set(unigrams))) return unigrams
5,251
41.354839
150
py
phocnet
phocnet-master/src/phocnet/caffe/augmentation.py
''' Created on Feb 18, 2016 @author: ssudholt ''' import numpy as np import cv2 class AugmentationCreator(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' pass @staticmethod def create_affine_transform_augmentation(img, random_limits=(0.8, 1.1)): ''' Creates an augmentation by computing a homography from three points in the image to three randomly generated points ''' y, x = img.shape[:2] fx = float(x) fy = float(y) src_point = np.float32([[fx/2, fy/3,], [2*fx/3, 2*fy/3], [fx/3, 2*fy/3]]) random_shift = (np.random.rand(3,2) - 0.5) * 2 * (random_limits[1]-random_limits[0])/2 + np.mean(random_limits) dst_point = src_point * random_shift.astype(np.float32) transform = cv2.getAffineTransform(src_point, dst_point) borderValue = 0 if img.ndim == 3: borderValue = np.median(np.reshape(img, (img.shape[0]*img.shape[1],-1)), axis=0) else: borderValue=np.median(img) warped_img = cv2.warpAffine(img, transform, dsize=(x,y), borderValue=borderValue) return warped_img @staticmethod def create_random_noise_flip_shift_rotate_augmentation(img, noise_variance=0.02, max_shift=0.05, max_abs_rotation=10, obj_list=None, obj_type = "rectangle"): ''' Creates an augmentation by randomly flipping the image, applying random noise from a Gaussian distribution, shifting the image and rotating it. ''' # copy the image aug_img = img.copy() # gaussian noise aug_img = aug_img.astype(np.float32) aug_img += (np.random.normal(loc=0.0, scale=noise_variance, size=img.shape)*255) # bring back to correct range aug_img -= aug_img.min() aug_img *= 255.0/aug_img.max() aug_img = aug_img.astype(np.uint8) # flip if np.random.rand() > 0.5: aug_img = AugmentationCreator.flip_image_lr(aug_img) if obj_list != None: if obj_type == "rectangle": obj_list = AugmentationCreator.flip_bboxes_lr(obj_list) elif obj_type == "point": obj_list = AugmentationCreator.flip_points_lr(obj_list) # random rotation angle = int((np.random.rand() - 0.5) * max_abs_rotation) aug_img = AugmentationCreator.rotate_image(aug_img, angle) if obj_list != None: if obj_type == "rectangle": obj_list = AugmentationCreator.rotate_bboxes(img, obj_list, angle) elif obj_type == "point": obj_list = AugmentationCreator.rotate_points(img, obj_list, angle) # random translation translation = (np.random.rand(2)-0.5) * max_shift aug_img = AugmentationCreator.translate_image(aug_img, translation) if obj_list != None: if obj_type == "rectangle": obj_list = AugmentationCreator.translate_bboxes(obj_list, translation) elif obj_type == "point": obj_list = AugmentationCreator.translate_points(obj_list, translation) return aug_img, obj_list, angle @staticmethod def flip_image_lr(image): ''' Flips the given image vertically. ''' return np.fliplr(image) @staticmethod def flip_points_lr(obj_list): ''' Flips the points of the given objects vertically. The coordinates of the points have to be normalized. ''' flipped_obj_list = [] for obj in obj_list: obj_name = obj[0] x = obj[1][0] y = obj[1][1] flipped_obj_list.append((obj_name, (1 - x, y))) return flipped_obj_list @staticmethod def flip_bboxes_lr(obj_list): ''' Flips the bounding boxes of the given objects vertically. The coordinates of the bounding boxes have to be normalized. ''' flipped_obj_list = [] for obj in obj_list: obj_name = obj[0] upper_left = obj[1]['upper_left'] lower_right = obj[1]['lower_right'] upper_left = np.array([1 - upper_left[0], upper_left[1]]) lower_right = np.array([1 - lower_right[0], lower_right[1]]) flipped_obj_list.append((obj_name, {'upper_left' : upper_left, 'lower_right' : lower_right})) return flipped_obj_list @staticmethod def rotate_image(image, angle): ''' Rotates the given image by the given angle. ''' rows, cols, _ = np.atleast_3d(image).shape rot_mat = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1) return cv2.warpAffine(image, rot_mat, (cols, rows)) @staticmethod def rotate_points(image, obj_list, angle): ''' Rotates the points of the given objects by the given angle. The points will be translated into absolute coordinates. Therefore the image (resp. its shape) is needed. ''' rotated_obj_list = [] cosOfAngle = np.cos(2 * np.pi / 360 * -angle) sinOfAngle = np.sin(2 * np.pi / 360 * -angle) image_shape = np.array(np.atleast_3d(image).shape[0:2][::-1]) rot_mat = np.array([[cosOfAngle, -sinOfAngle], [sinOfAngle, cosOfAngle]]) for obj in obj_list: obj_name = obj[0] point = obj[1] * image_shape rotated_point = AugmentationCreator._rotate_vector_around_point(image_shape/2, point, rot_mat) / image_shape rotated_obj_list.append((obj_name, (rotated_point[0], rotated_point[1]))) return rotated_obj_list @staticmethod def rotate_bboxes(image, obj_list, angle): ''' Rotates the bounding boxes of the given objects by the given angle. The bounding box will be translated into absolute coordinates. Therefore the image (resp. its shape) is needed. ''' rotated_obj_list = [] cosOfAngle = np.cos(2 * np.pi / 360 * -angle) sinOfAngle = np.sin(2 * np.pi / 360 * -angle) image_shape = np.array(np.atleast_3d(image).shape[0:2][::-1]) rot_mat = np.array([[cosOfAngle, -sinOfAngle], [sinOfAngle, cosOfAngle]]) for obj in obj_list: obj_name = obj[0] upper_left = obj[1]['upper_left'] * image_shape lower_right = obj[1]['lower_right'] * image_shape upper_left = AugmentationCreator._rotate_vector_around_point(image_shape/2, upper_left, rot_mat) / image_shape lower_right = AugmentationCreator._rotate_vector_around_point(image_shape/2, lower_right, rot_mat) / image_shape rotated_obj_list.append((obj_name, {'upper_left' : upper_left, 'lower_right' : lower_right})) return rotated_obj_list @staticmethod def _rotate_vector_around_point(point, vector, rot_mat): ''' Rotates a given vector around the given point using the given rotation matrix. ''' centering_translation = np.array([point[0], point[1]]) rotated_vector = vector - centering_translation rotated_vector = np.dot(rot_mat, rotated_vector.reshape(2, 1)).reshape(2) rotated_vector += centering_translation return rotated_vector @staticmethod def translate_image(image, translation): ''' Translates the given image with the given translation vector. ''' rows, cols, _ = np.atleast_3d(image).shape trans_mat = np.array([[1, 0, translation[0]*cols], [0, 1, translation[1]*rows]]) return cv2.warpAffine(image, trans_mat, (cols, rows)) @staticmethod def translate_points(obj_list, translation): ''' Translates the points of the given objects with the given translation vector. ''' translated_obj_list = [] for obj in obj_list: obj_name = obj[0] point = obj[1] translated_point = point + translation translated_obj_list.append((obj_name, (translated_point[0], translated_point[1]))) return translated_obj_list @staticmethod def translate_bboxes(obj_list, translation): ''' Translates the bounding boxes of the given objects with the given translation vector. ''' translated_obj_list = [] for obj in obj_list: obj_name = obj[0] upper_left = obj[1]['upper_left'] lower_right = obj[1]['lower_right'] upper_left = upper_left + translation lower_right = lower_right + translation translated_obj_list.append((obj_name, {'upper_left' : upper_left, 'lower_right' : lower_right})) return translated_obj_list
9,205
36.729508
124
py
phocnet
phocnet-master/src/phocnet/caffe/solver_proto_generator.py
''' Created on Jul 9, 2016 @author: ssudholt ''' from caffe.proto import caffe_pb2 from google.protobuf.internal.containers import RepeatedScalarFieldContainer def generate_solver_proto(**kwargs): sp = caffe_pb2.SolverParameter() for k,v in kwargs.iteritems(): if not hasattr(sp, k): raise ValueError('The argument \'%s\' is not part of the Caffe solver parameters!') elif v is not None: elem = getattr(sp, k) if type(elem) == RepeatedScalarFieldContainer: elem.append(v) elif k == 'solver_mode': setattr(sp, k, sp.SolverMode.DESCRIPTOR.values_by_name[v].number) else: setattr(sp, k, v) return sp
734
32.409091
95
py
phocnet
phocnet-master/src/phocnet/caffe/model_proto_generator.py
# pylint: disable=too-many-arguments ''' Created on Jul 8, 2016 @author: ssudholt ''' import logging from caffe import NetSpec from caffe import layers as L from caffe import params as P from caffe.io import caffe_pb2 import argparse class ModelProtoGenerator(object): ''' Class for generating Caffe CNN models through protobuffer files. ''' def __init__(self, initialization='msra', use_cudnn_engine=False): # set up the engines self.conv_engine = None self.spp_engine = None if use_cudnn_engine: self.conv_engine = P.Convolution.CUDNN self.spp_engine = P.SPP.CUDNN else: self.conv_engine = P.Convolution.CAFFE self.spp_engine = P.SPP.CAFFE self.phase_train = caffe_pb2.Phase.DESCRIPTOR.values_by_name['TRAIN'].number self.phase_test = caffe_pb2.Phase.DESCRIPTOR.values_by_name['TEST'].number self.initialization = initialization self.logger = logging.getLogger(self.__class__.__name__) def set_phocnet_data(self, n, generate_deploy, word_image_lmdb_path, phoc_lmdb_path): if generate_deploy: n.word_images = L.Input(shape=dict(dim=[1, 1, 100, 250])) else: n.word_images, n.label = L.Data(batch_size=1, backend=P.Data.LMDB, source=word_image_lmdb_path, prefetch=20, transform_param=dict(mean_value=255, scale=-1. / 255,), ntop=2) n.phocs, n.label_phocs = L.Data(batch_size=1, backend=P.Data.LMDB, source=phoc_lmdb_path, prefetch=20, ntop=2) def set_phocnet_conv_body(self, n, relu_in_place): n.conv1_1, n.relu1_1 = self.conv_relu(n.word_images, nout=64, relu_in_place=relu_in_place) n.conv1_2, n.relu1_2 = self.conv_relu(n.relu1_1, nout=64, relu_in_place=relu_in_place) n.pool1 = L.Pooling(n.relu1_2, pooling_param=dict(pool=P.Pooling.MAX, kernel_size=2, stride=2)) n.conv2_1, n.relu2_1 = self.conv_relu(n.pool1, nout=128, relu_in_place=relu_in_place) n.conv2_2, n.relu2_2 = self.conv_relu(n.relu2_1, nout=128, relu_in_place=relu_in_place) n.pool2 = L.Pooling(n.relu2_2, pooling_param=dict(pool=P.Pooling.MAX, kernel_size=2, stride=2)) n.conv3_1, n.relu3_1 = self.conv_relu(n.pool2, nout=256, relu_in_place=relu_in_place) n.conv3_2, n.relu3_2 = self.conv_relu(n.relu3_1, nout=256, relu_in_place=relu_in_place) n.conv3_3, n.relu3_3 = self.conv_relu(n.relu3_2, nout=256, relu_in_place=relu_in_place) n.conv3_4, n.relu3_4 = self.conv_relu(n.relu3_3, nout=256, relu_in_place=relu_in_place) n.conv3_5, n.relu3_5 = self.conv_relu(n.relu3_4, nout=256, relu_in_place=relu_in_place) n.conv3_6, n.relu3_6 = self.conv_relu(n.relu3_5, nout=256, relu_in_place=relu_in_place) n.conv4_1, n.relu4_1 = self.conv_relu(n.relu3_6, nout=512, relu_in_place=relu_in_place) n.conv4_2, n.relu4_2 = self.conv_relu(n.relu4_1, nout=512, relu_in_place=relu_in_place) n.conv4_3, n.relu4_3 = self.conv_relu(n.relu4_2, nout=512, relu_in_place=relu_in_place) def conv_relu(self, bottom, nout, kernel_size=3, stride=1, pad=1, relu_in_place=True): ''' Helper method for returning a ReLU activated Conv layer ''' conv = L.Convolution(bottom, kernel_size=kernel_size, stride=stride, num_output=nout, pad=pad, engine=self.conv_engine, weight_filler=dict(type=self.initialization), bias_filler=dict(type='constant')) return conv, L.ReLU(conv, in_place=relu_in_place) def fc_relu(self, bottom, layer_size, dropout_ratio=0.0, relu_in_place=True): ''' Helper method for returning a ReLU activated Fully Connected layer. It can be specified also if the layer should make use of Dropout as well. ''' fc = L.InnerProduct(bottom, num_output=layer_size, weight_filler=dict(type=self.initialization), bias_filler=dict(type='constant')) relu = L.ReLU(fc, in_place=relu_in_place) if dropout_ratio == 0.0: return fc, relu else: return fc, relu, L.Dropout(relu, dropout_ratio=0.5, in_place=True, include=dict(phase=self.phase_train)) def get_phocnet(self, word_image_lmdb_path, phoc_lmdb_path, phoc_size=604, generate_deploy=False): ''' Returns a NetSpec definition of the PHOCNet. The definition can then be transformed into a protobuffer message by casting it into a str. ''' n = NetSpec() # Data self.set_phocnet_data(n=n, generate_deploy=generate_deploy, word_image_lmdb_path=word_image_lmdb_path, phoc_lmdb_path=phoc_lmdb_path) # Conv Part self.set_phocnet_conv_body(n=n, relu_in_place=True) # FC Part n.spp5 = L.SPP(n.relu4_3, spp_param=dict(pool=P.SPP.MAX, pyramid_height=3, engine=self.spp_engine)) n.fc6, n.relu6, n.drop6 = self.fc_relu(bottom=n.spp5, layer_size=4096, dropout_ratio=0.5, relu_in_place=True) n.fc7, n.relu7, n.drop7 = self.fc_relu(bottom=n.drop6, layer_size=4096, dropout_ratio=0.5, relu_in_place=True) n.fc8 = L.InnerProduct(n.drop7, num_output=phoc_size, weight_filler=dict(type=self.initialization), bias_filler=dict(type='constant')) n.sigmoid = L.Sigmoid(n.fc8, include=dict(phase=self.phase_test)) # output part if not generate_deploy: n.silence = L.Silence(n.sigmoid, ntop=0, include=dict(phase=self.phase_test)) n.loss = L.SigmoidCrossEntropyLoss(n.fc8, n.phocs) return n.to_proto() def get_tpp_phocnet(self, word_image_lmdb_path, phoc_lmdb_path, phoc_size, tpp_levels=5, generate_deploy=False): ''' Returns a NetSpec definition of the TPP-PHOCNet. The definition can then be transformed into a protobuffer message by casting it into a str. ''' n = NetSpec() # Data self.set_phocnet_data(n=n, generate_deploy=generate_deploy, word_image_lmdb_path=word_image_lmdb_path, phoc_lmdb_path=phoc_lmdb_path) # Conv Part self.set_phocnet_conv_body(n=n, relu_in_place=True) # FC Part n.tpp5 = L.TPP(n.relu4_3, tpp_param=dict(pool=P.TPP.MAX, pyramid_layer=range(1, tpp_levels + 1), engine=self.spp_engine)) n.fc6, n.relu6, n.drop6 = self.fc_relu(bottom=n.tpp5, layer_size=4096, dropout_ratio=0.5, relu_in_place=True) n.fc7, n.relu7, n.drop7 = self.fc_relu(bottom=n.drop6, layer_size=4096, dropout_ratio=0.5, relu_in_place=True) n.fc8 = L.InnerProduct(n.drop7, num_output=phoc_size, weight_filler=dict(type=self.initialization), bias_filler=dict(type='constant')) n.sigmoid = L.Sigmoid(n.fc8, include=dict(phase=self.phase_test)) # output part if not generate_deploy: n.silence = L.Silence(n.sigmoid, ntop=0, include=dict(phase=self.phase_test)) n.loss = L.SigmoidCrossEntropyLoss(n.fc8, n.phocs) return n.to_proto() def main(): ''' this module can be called as main function in which case it prints the prototxt definition for the given net ''' parser = argparse.ArgumentParser() parser.add_argument('--cnn_architecture', '-ca', choices=['phocnet', 'tpp-phocnet'], default='phocnet', help='The CNN architecture to print to standard out') parser.add_argument('--word_image_lmdb_path', '-wilp', default='./word_images_lmdb') parser.add_argument('--phoc_lmdb_path', '-plp', default='./phoc_lmdb') parser.add_argument('--phoc_size', type=int, default=604) args = parser.parse_args() if args.cnn_architecture == 'phocnet': print str(ModelProtoGenerator().get_phocnet(word_image_lmdb_path=args.word_image_lmdb_path, phoc_lmdb_path=args.phoc_lmdb_path, phoc_size=args.phoc_size, generate_deploy=args.generate_deploy)) elif args.cnn_architecture == 'tpp-phocnet': print str(ModelProtoGenerator().get_tpp_phocnet(word_image_lmdb_path=args.word_image_lmdb_path, phoc_lmdb_path=args.phoc_lmdb_path, phoc_size=args.phoc_size, generate_deploy=args.generate_deploy)) if __name__ == '__main__': main()
9,101
49.566667
129
py
phocnet
phocnet-master/src/phocnet/caffe/lmdb_creator.py
''' Created on Feb 18, 2016 @author: ssudholt ''' import os import shutil import logging import numpy as np import lmdb import caffe.io # from patrec.serialization.list_io import LineListIO class CaffeLMDBCreator(object): def __init__(self): ''' LMDB creator can create a single LMDB for single label classification or two LMDBs where each element in the database_images has a corresponding counterpart in database_additional with the same key. This is useful for creating for example LMDBs for PHOCs, attributes or segmentation. ''' self.logger = logging.getLogger('CaffeLMDBCreator') self.database_images = None self.database_additional = None self.txn_images = None self.txn_additional = None self.label_map = None self.internal_counter = 0 self.logger.debug('Using LMDB version %d.%d.%d' % lmdb.version()) def open_single_lmdb_for_write(self, lmdb_path, max_lmdb_size=1024**4, create=True, label_map=None): ''' Opens a single LMDB for inserting ndarrays (i.e. images) Args: lmdb_path (str): Where to save the LMDB max_lmdb_size (int): The maximum size in bytes of the LMDB (default: 1TB) create (bool): If this flag is set, a potentially previously created LMDB at lmdb_path is deleted and overwritten by this new LMDB label_map (dictionary): If you supply a dictionary mapping string labels to integer indices, you can later call put_single with string labels instead of int labels ''' # delete existing LMDB if necessary if os.path.exists(lmdb_path) and create: self.logger.debug('Erasing previously created LMDB at %s', lmdb_path) shutil.rmtree(lmdb_path) self.logger.info('Opening single LMDB at %s for writing', lmdb_path) self.database_images = lmdb.open(path=lmdb_path, map_size=max_lmdb_size) self.txn_images = self.database_images.begin(write=True) self.label_map = label_map def open_dual_lmdb_for_write(self, image_lmdb_path, additional_lmdb_path, max_lmdb_size=1024**4, create=True, label_map=None): ''' Opens two LMDBs where each element in the first has a counterpart in the second Args: image_lmdb_path (str): Where to save the image LMDB additional_lmdb_path (str): Where to save the additional LMDB max_lmdb_size (int): The maximum size in bytes of each LMDB (default: 1TB) create (bool): If this flag is set, potentially previously created LMDBs at lmdb_path and additional_lmdb_path are deleted and overwritten by new LMDBs label_map (dictionary): If you supply a dictionary mapping string labels to integer indices, you can later call put_dual with string labels instead of int labels ''' # delete existing LMDBs if necessary if os.path.exists(image_lmdb_path) and create: self.logger.debug('Erasing previously created LMDB at %s', image_lmdb_path) shutil.rmtree(image_lmdb_path) if os.path.exists(additional_lmdb_path) and create: self.logger.debug('Erasing previously created LMDB at %s', additional_lmdb_path) shutil.rmtree(additional_lmdb_path) self.logger.info('Opening LMDBs at %s and %s for writing', image_lmdb_path, additional_lmdb_path) self.database_images = lmdb.open(path=image_lmdb_path, map_size=max_lmdb_size) self.txn_images = self.database_images.begin(write=True) self.database_additional = lmdb.open(path=additional_lmdb_path, map_size=max_lmdb_size) self.txn_additional = self.database_additional.begin(write=True) self.label_map = label_map def put_single(self, img_mat, label, key=None): ''' Puts an ndarray into the previously opened single LMDB Args: img_mat (3d-ndarray): The image data to be inserted in the LMDB label (str or int): The label for the image key (str): The key under which to save the data in the LMDB If key is None, a generic key is generated ''' # some checks if self.database_images is None: raise ValueError('No LMDB to write to. Have you called open_single_lmdb_for_write?') if self.database_additional is not None: raise ValueError('Cannot execute put_single as open_dual_lmdb_for_write has been chosen for LMDB creation') if img_mat.dtype != np.uint8 or img_mat.ndim != 3: raise ValueError('img_mat must be a 3d-ndarray of type np.uint8') # label may be a string if a label map was supplied datum_label = None if type(label) == str: if self.label_map is None: raise ValueError('You may only supply a label of type str if you called open_single_lmdb_for_write with a valid label_map') else: datum_label = self.label_map[label] elif type(label) == int: datum_label = label else: raise ValueError('label must be of type str or int') # convert img_mat to Caffe Datum datum = caffe.io.array_to_datum(arr=img_mat, label=datum_label) if key is None: key = '%s_%s' % (str(self.internal_counter).zfill(8), str(label)) # push Datum into the LMDB self.txn_images.put(key=key, value=datum.SerializeToString()) self.internal_counter += 1 if self.internal_counter % 1000 == 0: self.txn_images.commit() self.logger.info(' Finished %*d ndarrays', 8, self.internal_counter) # after a commit the txn object becomes invalid, so we need to get a new one self.txn_images = self.database_images.begin(write=True) def put_dual(self, img_mat, additional_mat, label, key=None): ''' Puts an image and its corresponding additional information ndarray into the previously opened LMDBs Args: img_mat (3d-ndarray): The image data to be inserted in the LMDB additional_mat (3d-ndarray): The label matrix (attributes, PHOC, ...) to be inserted label (str or int): The label for the image key (str): The key under which to save the data in the LMDB If key is None, a generic key is generated ''' # some checks if self.database_images is None: raise ValueError('No LMDB to write to. Have you called open_dual_lmdb_for_write?') if self.database_additional is None: raise ValueError('Cannot execute put_dual as open_single_lmdb_for_write has been chosen for LMDB creation') if img_mat.dtype != np.uint8 or img_mat.ndim != 3: raise TypeError('img_mat must be a 3d-ndarray of type np.uint8') if additional_mat.dtype != np.uint8 or additional_mat.ndim != 3: raise TypeError('additional_mat must be a 3d-ndarray of type np.uint8') # label may be a string if a label map was supplied datum_label = None if type(label) == str: if self.label_map is None: raise ValueError('You may only supply a label of type str if you called open_single_lmdb_for_write with a valid label_map') elif not label in self.label_map.keys(): self.logger.warn('Warning, unknown key - skipping this entry') return else: datum_label = self.label_map[label] elif type(label) in [int, np.int32, np.int64]: datum_label = int(label) else: raise TypeError('label must be of type str or int') # convert img_mat and additional_mat to Caffe Data datum_img = caffe.io.array_to_datum(arr=img_mat, label=datum_label) datum_additional = caffe.io.array_to_datum(arr=additional_mat, label=datum_label) if key is None: key = '%s_%s' % (str(self.internal_counter).zfill(8), str(label)) # push Data in the current LMDBs self.txn_images.put(key=key, value=datum_img.SerializeToString()) self.txn_additional.put(key=key, value=datum_additional.SerializeToString()) self.internal_counter += 1 if self.internal_counter % 10000 == 0: self.txn_images.commit() self.txn_additional.commit() self.logger.info(' Finished %*d ndarrays', 8, self.internal_counter) # after a commit the txn objects becomes invalid, so we need to get new ones self.txn_images = self.database_images.begin(write=True) self.txn_additional = self.database_additional.begin(write=True) return def finish_creation(self): ''' Wraps up LMDB creation and resets all internal variables ''' self.txn_images.commit() self.database_images.sync() self.database_images.close() if self.database_additional is not None: self.txn_additional.commit() self.database_additional.sync() self.database_additional.close() self.logger.info('Finished after writing %d ndarrays', self.internal_counter) self.database_images = None self.database_additional = None self.txn_images = None self.txn_additional = None self.label_map = None self.internal_counter = 0
9,744
48.217172
139
py
phocnet
phocnet-master/src/phocnet/caffe/__init__.py
0
0
0
py
pLogicNet
pLogicNet-master/utils.py
import sys import os # This function computes the probability of a triplet being true based on the MLN outputs. def mln_triplet_prob(h, r, t, hrt2p): # KGE algorithms tend to predict triplets like (e, r, e), which are less likely in practice. # Therefore, we give a penalty to such triplets, which yields some improvement. if h == t: if hrt2p.get((h, r, t), 0) < 0.5: return -100 return hrt2p[(h, r, t)] else: if (h, r, t) in hrt2p: return hrt2p[(h, r, t)] return 0.5 # This function reads the outputs from MLN and KGE to do evaluation. # Here, the parameter weight controls the relative weights of both models. def evaluate(mln_pred_file, kge_pred_file, output_file, weight): hit1 = 0 hit3 = 0 hit10 = 0 mr = 0 mrr = 0 cn = 0 hrt2p = dict() with open(mln_pred_file, 'r') as fi: for line in fi: h, r, t, p = line.strip().split('\t')[0:4] hrt2p[(h, r, t)] = float(p) with open(kge_pred_file, 'r') as fi: while True: truth = fi.readline() preds = fi.readline() if (not truth) or (not preds): break truth = truth.strip().split() preds = preds.strip().split() h, r, t, mode, original_ranking = truth[0:5] original_ranking = int(original_ranking) if mode == 'h': preds = [[pred.split(':')[0], float(pred.split(':')[1])] for pred in preds] for k in range(len(preds)): e = preds[k][0] preds[k][1] += mln_triplet_prob(e, r, t, hrt2p) * weight preds = sorted(preds, key=lambda x:x[1], reverse=True) ranking = -1 for k in range(len(preds)): e = preds[k][0] if e == h: ranking = k + 1 break if ranking == -1: ranking = original_ranking if mode == 't': preds = [[pred.split(':')[0], float(pred.split(':')[1])] for pred in preds] for k in range(len(preds)): e = preds[k][0] preds[k][1] += mln_triplet_prob(h, r, e, hrt2p) * weight preds = sorted(preds, key=lambda x:x[1], reverse=True) ranking = -1 for k in range(len(preds)): e = preds[k][0] if e == t: ranking = k + 1 break if ranking == -1: ranking = original_ranking if ranking <= 1: hit1 += 1 if ranking <=3: hit3 += 1 if ranking <= 10: hit10 += 1 mr += ranking mrr += 1.0 / ranking cn += 1 mr /= cn mrr /= cn hit1 /= cn hit3 /= cn hit10 /= cn print('MR: ', mr) print('MRR: ', mrr) print('Hit@1: ', hit1) print('Hit@3: ', hit3) print('Hit@10: ', hit10) with open(output_file, 'w') as fo: fo.write('MR: {}\n'.format(mr)) fo.write('MRR: {}\n'.format(mrr)) fo.write('Hit@1: {}\n'.format(hit1)) fo.write('Hit@3: {}\n'.format(hit3)) fo.write('Hit@10: {}\n'.format(hit10)) def augment_triplet(pred_file, trip_file, out_file, threshold): with open(pred_file, 'r') as fi: data = [] for line in fi: l = line.strip().split() data += [(l[0], l[1], l[2], float(l[3]))] with open(trip_file, 'r') as fi: trip = set() for line in fi: l = line.strip().split() trip.add((l[0], l[1], l[2])) for tp in data: if tp[3] < threshold: continue trip.add((tp[0], tp[1], tp[2])) with open(out_file, 'w') as fo: for h, r, t in trip: fo.write('{}\t{}\t{}\n'.format(h, r, t))
4,033
29.793893
96
py
pLogicNet
pLogicNet-master/run.py
import sys import os import datetime from utils import augment_triplet, evaluate dataset = 'data/FB15k' path = './record' iterations = 2 kge_model = 'TransE' kge_batch = 1024 kge_neg = 256 kge_dim = 100 kge_gamma = 24 kge_alpha = 1 kge_lr = 0.001 kge_iters = 10000 kge_tbatch = 16 kge_reg = 0.0 kge_topk = 100 if kge_model == 'RotatE': if dataset.split('/')[-1] == 'FB15k': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 1024, 256, 1000, 24.0, 1.0, 0.0001, 150000, 16 if dataset.split('/')[-1] == 'FB15k-237': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 1024, 256, 1000, 9.0, 1.0, 0.00005, 100000, 16 if dataset.split('/')[-1] == 'wn18': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 512, 1024, 500, 12.0, 0.5, 0.0001, 80000, 8 if dataset.split('/')[-1] == 'wn18rr': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 512, 1024, 500, 6.0, 0.5, 0.00005, 80000, 8 if kge_model == 'TransE': if dataset.split('/')[-1] == 'FB15k': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 1024, 256, 1000, 24.0, 1.0, 0.0001, 150000, 16 if dataset.split('/')[-1] == 'FB15k-237': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 1024, 256, 1000, 9.0, 1.0, 0.00005, 100000, 16 if dataset.split('/')[-1] == 'wn18': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 512, 1024, 500, 12.0, 0.5, 0.0001, 80000, 8 if dataset.split('/')[-1] == 'wn18rr': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch = 512, 1024, 500, 6.0, 0.5, 0.00005, 80000, 8 if kge_model == 'DistMult': if dataset.split('/')[-1] == 'FB15k': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 1024, 256, 2000, 500.0, 1.0, 0.001, 150000, 16, 0.000002 if dataset.split('/')[-1] == 'FB15k-237': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 1024, 256, 2000, 200.0, 1.0, 0.001, 100000, 16, 0.00001 if dataset.split('/')[-1] == 'wn18': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 512, 1024, 1000, 200.0, 1.0, 0.001, 80000, 8, 0.00001 if dataset.split('/')[-1] == 'wn18rr': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 512, 1024, 1000, 200.0, 1.0, 0.002, 80000, 8, 0.000005 if kge_model == 'ComplEx': if dataset.split('/')[-1] == 'FB15k': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 1024, 256, 1000, 500.0, 1.0, 0.001, 150000, 16, 0.000002 if dataset.split('/')[-1] == 'FB15k-237': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 1024, 256, 1000, 200.0, 1.0, 0.001, 100000, 16, 0.00001 if dataset.split('/')[-1] == 'wn18': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 512, 1024, 500, 200.0, 1.0, 0.001, 80000, 8, 0.00001 if dataset.split('/')[-1] == 'wn18rr': kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, kge_reg = 512, 1024, 500, 200.0, 1.0, 0.002, 80000, 8, 0.000005 if dataset.split('/')[-1] == 'FB15k': mln_threshold_of_rule = 0.1 mln_threshold_of_triplet = 0.7 weight = 0.5 if dataset.split('/')[-1] == 'FB15k-237': mln_threshold_of_rule = 0.6 mln_threshold_of_triplet = 0.7 weight = 0.5 if dataset.split('/')[-1] == 'wn18': mln_threshold_of_rule = 0.1 mln_threshold_of_triplet = 0.5 weight = 100 if dataset.split('/')[-1] == 'wn18rr': mln_threshold_of_rule = 0.1 mln_threshold_of_triplet = 0.5 weight = 100 mln_iters = 1000 mln_lr = 0.0001 mln_threads = 8 # ------------------------------------------ def ensure_dir(d): if not os.path.exists(d): os.makedirs(d) def cmd_kge(workspace_path, model): if model == 'RotatE': return 'bash ./kge/kge.sh train {} {} 0 {} {} {} {} {} {} {} {} {} {} -de'.format(model, dataset, kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, workspace_path, kge_topk) if model == 'TransE': return 'bash ./kge/kge.sh train {} {} 0 {} {} {} {} {} {} {} {} {} {}'.format(model, dataset, kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, workspace_path, kge_topk) if model == 'DistMult': return 'bash ./kge/kge.sh train {} {} 0 {} {} {} {} {} {} {} {} {} {} -r {}'.format(model, dataset, kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, workspace_path, kge_topk, kge_reg) if model == 'ComplEx': return 'bash ./kge/kge.sh train {} {} 0 {} {} {} {} {} {} {} {} {} {} -de -dr -r {}'.format(model, dataset, kge_batch, kge_neg, kge_dim, kge_gamma, kge_alpha, kge_lr, kge_iters, kge_tbatch, workspace_path, kge_topk, kge_reg) def cmd_mln(main_path, workspace_path=None, preprocessing=False): if preprocessing == True: return './mln/mln -observed {}/train.txt -out-hidden {}/hidden.txt -save {}/mln_saved.txt -thresh-rule {} -iterations 0 -threads {}'.format(main_path, main_path, main_path, mln_threshold_of_rule, mln_threads) else: return './mln/mln -load {}/mln_saved.txt -probability {}/annotation.txt -out-prediction {}/pred_mln.txt -out-rule {}/rule.txt -thresh-triplet 1 -iterations {} -lr {} -threads {}'.format(main_path, workspace_path, workspace_path, workspace_path, mln_iters, mln_lr, mln_threads) def save_cmd(save_path): with open(save_path, 'w') as fo: fo.write('dataset: {}\n'.format(dataset)) fo.write('iterations: {}\n'.format(iterations)) fo.write('kge_model: {}\n'.format(kge_model)) fo.write('kge_batch: {}\n'.format(kge_batch)) fo.write('kge_neg: {}\n'.format(kge_neg)) fo.write('kge_dim: {}\n'.format(kge_dim)) fo.write('kge_gamma: {}\n'.format(kge_gamma)) fo.write('kge_alpha: {}\n'.format(kge_alpha)) fo.write('kge_lr: {}\n'.format(kge_lr)) fo.write('kge_iters: {}\n'.format(kge_iters)) fo.write('kge_tbatch: {}\n'.format(kge_tbatch)) fo.write('kge_reg: {}\n'.format(kge_reg)) fo.write('mln_threshold_of_rule: {}\n'.format(mln_threshold_of_rule)) fo.write('mln_threshold_of_triplet: {}\n'.format(mln_threshold_of_triplet)) fo.write('mln_iters: {}\n'.format(mln_iters)) fo.write('mln_lr: {}\n'.format(mln_lr)) fo.write('mln_threads: {}\n'.format(mln_threads)) fo.write('weight: {}\n'.format(weight)) time = str(datetime.datetime.now()).replace(' ', '_') path = path + '/' + time ensure_dir(path) save_cmd('{}/cmd.txt'.format(path)) # ------------------------------------------ os.system('cp {}/train.txt {}/train.txt'.format(dataset, path)) os.system('cp {}/train.txt {}/train_augmented.txt'.format(dataset, path)) os.system(cmd_mln(path, preprocessing=True)) for k in range(iterations): workspace_path = path + '/' + str(k) ensure_dir(workspace_path) os.system('cp {}/train_augmented.txt {}/train_kge.txt'.format(path, workspace_path)) os.system('cp {}/hidden.txt {}/hidden.txt'.format(path, workspace_path)) os.system(cmd_kge(workspace_path, kge_model)) os.system(cmd_mln(path, workspace_path, preprocessing=False)) augment_triplet('{}/pred_mln.txt'.format(workspace_path), '{}/train.txt'.format(path), '{}/train_augmented.txt'.format(workspace_path), mln_threshold_of_triplet) os.system('cp {}/train_augmented.txt {}/train_augmented.txt'.format(workspace_path, path)) evaluate('{}/pred_mln.txt'.format(workspace_path), '{}/pred_kge.txt'.format(workspace_path), '{}/result_kge_mln.txt'.format(workspace_path), weight)
7,970
51.440789
284
py
pLogicNet
pLogicNet-master/kge/dataloader.py
#!/usr/bin/python3 from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import torch from torch.utils.data import Dataset class TrainDataset(Dataset): def __init__(self, triples, nentity, nrelation, negative_sample_size, mode): self.len = len(triples) self.triples = triples self.triple_set = set(triples) self.nentity = nentity self.nrelation = nrelation self.negative_sample_size = negative_sample_size self.mode = mode self.count = self.count_frequency(triples) self.true_head, self.true_tail = self.get_true_head_and_tail(self.triples) def __len__(self): return self.len def __getitem__(self, idx): positive_sample = self.triples[idx] head, relation, tail = positive_sample subsampling_weight = self.count[(head, relation)] + self.count[(tail, -relation-1)] subsampling_weight = torch.sqrt(1 / torch.Tensor([subsampling_weight])) negative_sample_list = [] negative_sample_size = 0 while negative_sample_size < self.negative_sample_size: negative_sample = np.random.randint(self.nentity, size=self.negative_sample_size*2) if self.mode == 'head-batch': mask = np.in1d( negative_sample, self.true_head[(relation, tail)], assume_unique=True, invert=True ) elif self.mode == 'tail-batch': mask = np.in1d( negative_sample, self.true_tail[(head, relation)], assume_unique=True, invert=True ) else: raise ValueError('Training batch mode %s not supported' % self.mode) negative_sample = negative_sample[mask] negative_sample_list.append(negative_sample) negative_sample_size += negative_sample.size negative_sample = np.concatenate(negative_sample_list)[:self.negative_sample_size] negative_sample = torch.from_numpy(negative_sample) positive_sample = torch.LongTensor(positive_sample) return positive_sample, negative_sample, subsampling_weight, self.mode @staticmethod def collate_fn(data): positive_sample = torch.stack([_[0] for _ in data], dim=0) negative_sample = torch.stack([_[1] for _ in data], dim=0) subsample_weight = torch.cat([_[2] for _ in data], dim=0) mode = data[0][3] return positive_sample, negative_sample, subsample_weight, mode @staticmethod def count_frequency(triples, start=4): ''' Get frequency of a partial triple like (head, relation) or (relation, tail) The frequency will be used for subsampling like word2vec ''' count = {} for head, relation, tail in triples: if (head, relation) not in count: count[(head, relation)] = start else: count[(head, relation)] += 1 if (tail, -relation-1) not in count: count[(tail, -relation-1)] = start else: count[(tail, -relation-1)] += 1 return count @staticmethod def get_true_head_and_tail(triples): ''' Build a dictionary of true triples that will be used to filter these true triples for negative sampling ''' true_head = {} true_tail = {} for head, relation, tail in triples: if (head, relation) not in true_tail: true_tail[(head, relation)] = [] true_tail[(head, relation)].append(tail) if (relation, tail) not in true_head: true_head[(relation, tail)] = [] true_head[(relation, tail)].append(head) for relation, tail in true_head: true_head[(relation, tail)] = np.array(list(set(true_head[(relation, tail)]))) for head, relation in true_tail: true_tail[(head, relation)] = np.array(list(set(true_tail[(head, relation)]))) return true_head, true_tail class TestDataset(Dataset): def __init__(self, triples, all_true_triples, nentity, nrelation, mode): self.len = len(triples) self.triple_set = set(all_true_triples) self.triples = triples self.nentity = nentity self.nrelation = nrelation self.mode = mode def __len__(self): return self.len def __getitem__(self, idx): head, relation, tail = self.triples[idx] if self.mode == 'head-batch': tmp = [(0, rand_head) if (rand_head, relation, tail) not in self.triple_set else (-1, head) for rand_head in range(self.nentity)] tmp[head] = (0, head) elif self.mode == 'tail-batch': tmp = [(0, rand_tail) if (head, relation, rand_tail) not in self.triple_set else (-1, tail) for rand_tail in range(self.nentity)] tmp[tail] = (0, tail) else: raise ValueError('negative batch mode %s not supported' % self.mode) tmp = torch.LongTensor(tmp) filter_bias = tmp[:, 0].float() negative_sample = tmp[:, 1] positive_sample = torch.LongTensor((head, relation, tail)) return positive_sample, negative_sample, filter_bias, self.mode @staticmethod def collate_fn(data): positive_sample = torch.stack([_[0] for _ in data], dim=0) negative_sample = torch.stack([_[1] for _ in data], dim=0) filter_bias = torch.stack([_[2] for _ in data], dim=0) mode = data[0][3] return positive_sample, negative_sample, filter_bias, mode class BidirectionalOneShotIterator(object): def __init__(self, dataloader_head, dataloader_tail): self.iterator_head = self.one_shot_iterator(dataloader_head) self.iterator_tail = self.one_shot_iterator(dataloader_tail) self.step = 0 def __next__(self): self.step += 1 if self.step % 2 == 0: data = next(self.iterator_head) else: data = next(self.iterator_tail) return data @staticmethod def one_shot_iterator(dataloader): ''' Transform a PyTorch Dataloader into python iterator ''' while True: for data in dataloader: yield data
6,670
35.255435
107
py
pLogicNet
pLogicNet-master/kge/model.py
#!/usr/bin/python3 from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import average_precision_score from torch.utils.data import DataLoader from dataloader import TestDataset class KGEModel(nn.Module): def __init__(self, model_name, nentity, nrelation, hidden_dim, gamma, double_entity_embedding=False, double_relation_embedding=False): super(KGEModel, self).__init__() self.model_name = model_name self.nentity = nentity self.nrelation = nrelation self.hidden_dim = hidden_dim self.epsilon = 2.0 self.gamma = nn.Parameter( torch.Tensor([gamma]), requires_grad=False ) self.embedding_range = nn.Parameter( torch.Tensor([(self.gamma.item() + self.epsilon) / hidden_dim]), requires_grad=False ) self.entity_dim = hidden_dim*2 if double_entity_embedding else hidden_dim self.relation_dim = hidden_dim*2 if double_relation_embedding else hidden_dim self.entity_embedding = nn.Parameter(torch.zeros(nentity, self.entity_dim)) nn.init.uniform_( tensor=self.entity_embedding, a=-self.embedding_range.item(), b=self.embedding_range.item() ) self.relation_embedding = nn.Parameter(torch.zeros(nrelation, self.relation_dim)) nn.init.uniform_( tensor=self.relation_embedding, a=-self.embedding_range.item(), b=self.embedding_range.item() ) if model_name == 'pRotatE': self.modulus = nn.Parameter(torch.Tensor([[0.5 * self.embedding_range.item()]])) #Do not forget to modify this line when you add a new model in the "forward" function if model_name not in ['TransE', 'DistMult', 'ComplEx', 'RotatE', 'pRotatE']: raise ValueError('model %s not supported' % model_name) if model_name == 'RotatE' and (not double_entity_embedding or double_relation_embedding): raise ValueError('RotatE should use --double_entity_embedding') if model_name == 'ComplEx' and (not double_entity_embedding or not double_relation_embedding): raise ValueError('ComplEx should use --double_entity_embedding and --double_relation_embedding') def forward(self, sample, mode='single'): ''' Forward function that calculate the score of a batch of triples. In the 'single' mode, sample is a batch of triple. In the 'head-batch' or 'tail-batch' mode, sample consists two part. The first part is usually the positive sample. And the second part is the entities in the negative samples. Because negative samples and positive samples usually share two elements in their triple ((head, relation) or (relation, tail)). ''' if mode == 'single': batch_size, negative_sample_size = sample.size(0), 1 head = torch.index_select( self.entity_embedding, dim=0, index=sample[:,0] ).unsqueeze(1) relation = torch.index_select( self.relation_embedding, dim=0, index=sample[:,1] ).unsqueeze(1) tail = torch.index_select( self.entity_embedding, dim=0, index=sample[:,2] ).unsqueeze(1) elif mode == 'head-batch': tail_part, head_part = sample batch_size, negative_sample_size = head_part.size(0), head_part.size(1) head = torch.index_select( self.entity_embedding, dim=0, index=head_part.view(-1) ).view(batch_size, negative_sample_size, -1) relation = torch.index_select( self.relation_embedding, dim=0, index=tail_part[:, 1] ).unsqueeze(1) tail = torch.index_select( self.entity_embedding, dim=0, index=tail_part[:, 2] ).unsqueeze(1) elif mode == 'tail-batch': head_part, tail_part = sample batch_size, negative_sample_size = tail_part.size(0), tail_part.size(1) head = torch.index_select( self.entity_embedding, dim=0, index=head_part[:, 0] ).unsqueeze(1) relation = torch.index_select( self.relation_embedding, dim=0, index=head_part[:, 1] ).unsqueeze(1) tail = torch.index_select( self.entity_embedding, dim=0, index=tail_part.view(-1) ).view(batch_size, negative_sample_size, -1) else: raise ValueError('mode %s not supported' % mode) model_func = { 'TransE': self.TransE, 'DistMult': self.DistMult, 'ComplEx': self.ComplEx, 'RotatE': self.RotatE, 'pRotatE': self.pRotatE } if self.model_name in model_func: score = model_func[self.model_name](head, relation, tail, mode) else: raise ValueError('model %s not supported' % self.model_name) return score def TransE(self, head, relation, tail, mode): if mode == 'head-batch': score = head + (relation - tail) else: score = (head + relation) - tail score = self.gamma.item() - torch.norm(score, p=1, dim=2) return score def DistMult(self, head, relation, tail, mode): if mode == 'head-batch': score = head * (relation * tail) else: score = (head * relation) * tail score = score.sum(dim = 2) return score def ComplEx(self, head, relation, tail, mode): re_head, im_head = torch.chunk(head, 2, dim=2) re_relation, im_relation = torch.chunk(relation, 2, dim=2) re_tail, im_tail = torch.chunk(tail, 2, dim=2) if mode == 'head-batch': re_score = re_relation * re_tail + im_relation * im_tail im_score = re_relation * im_tail - im_relation * re_tail score = re_head * re_score + im_head * im_score else: re_score = re_head * re_relation - im_head * im_relation im_score = re_head * im_relation + im_head * re_relation score = re_score * re_tail + im_score * im_tail score = score.sum(dim = 2) return score def RotatE(self, head, relation, tail, mode): pi = 3.14159265358979323846 re_head, im_head = torch.chunk(head, 2, dim=2) re_tail, im_tail = torch.chunk(tail, 2, dim=2) #Make phases of relations uniformly distributed in [-pi, pi] phase_relation = relation/(self.embedding_range.item()/pi) re_relation = torch.cos(phase_relation) im_relation = torch.sin(phase_relation) if mode == 'head-batch': re_score = re_relation * re_tail + im_relation * im_tail im_score = re_relation * im_tail - im_relation * re_tail re_score = re_score - re_head im_score = im_score - im_head else: re_score = re_head * re_relation - im_head * im_relation im_score = re_head * im_relation + im_head * re_relation re_score = re_score - re_tail im_score = im_score - im_tail score = torch.stack([re_score, im_score], dim = 0) score = score.norm(dim = 0) score = self.gamma.item() - score.sum(dim = 2) return score def pRotatE(self, head, relation, tail, mode): pi = 3.14159262358979323846 #Make phases of entities and relations uniformly distributed in [-pi, pi] phase_head = head/(self.embedding_range.item()/pi) phase_relation = relation/(self.embedding_range.item()/pi) phase_tail = tail/(self.embedding_range.item()/pi) if mode == 'head-batch': score = phase_head + (phase_relation - phase_tail) else: score = (phase_head + phase_relation) - phase_tail score = torch.sin(score) score = torch.abs(score) score = self.gamma.item() - score.sum(dim = 2) * self.modulus return score @staticmethod def train_step(model, optimizer, train_iterator, args): ''' A single train step. Apply back-propation and return the loss ''' model.train() optimizer.zero_grad() positive_sample, negative_sample, subsampling_weight, mode = next(train_iterator) if args.cuda: positive_sample = positive_sample.cuda() negative_sample = negative_sample.cuda() subsampling_weight = subsampling_weight.cuda() negative_score = model((positive_sample, negative_sample), mode=mode) if args.negative_adversarial_sampling: #In self-adversarial sampling, we do not apply back-propagation on the sampling weight negative_score = (F.softmax(negative_score * args.adversarial_temperature, dim = 1).detach() * F.logsigmoid(-negative_score)).sum(dim = 1) else: negative_score = F.logsigmoid(-negative_score).mean(dim = 1) positive_score = model(positive_sample) positive_score = F.logsigmoid(positive_score).squeeze(dim = 1) if args.uni_weight: positive_sample_loss = - positive_score.mean() negative_sample_loss = - negative_score.mean() else: positive_sample_loss = - (subsampling_weight * positive_score).sum()/subsampling_weight.sum() negative_sample_loss = - (subsampling_weight * negative_score).sum()/subsampling_weight.sum() loss = (positive_sample_loss + negative_sample_loss)/2 if args.regularization != 0.0: #Use L3 regularization for ComplEx and DistMult regularization = args.regularization * ( model.entity_embedding.norm(p = 3)**3 + model.relation_embedding.norm(p = 3).norm(p = 3)**3 ) loss = loss + regularization regularization_log = {'regularization': regularization.item()} else: regularization_log = {} loss.backward() optimizer.step() log = { **regularization_log, 'positive_sample_loss': positive_sample_loss.item(), 'negative_sample_loss': negative_sample_loss.item(), 'loss': loss.item() } return log @staticmethod def test_step(model, test_triples, all_true_triples, args): ''' Evaluate the model on test or valid datasets ''' model.eval() if args.countries: #Countries S* datasets are evaluated on AUC-PR #Process test data for AUC-PR evaluation sample = list() y_true = list() for head, relation, tail in test_triples: for candidate_region in args.regions: y_true.append(1 if candidate_region == tail else 0) sample.append((head, relation, candidate_region)) sample = torch.LongTensor(sample) if args.cuda: sample = sample.cuda() with torch.no_grad(): y_score = model(sample).squeeze(1).cpu().numpy() y_true = np.array(y_true) #average_precision_score is the same as auc_pr auc_pr = average_precision_score(y_true, y_score) metrics = {'auc_pr': auc_pr} else: #Otherwise use standard (filtered) MRR, MR, HITS@1, HITS@3, and HITS@10 metrics #Prepare dataloader for evaluation test_dataloader_head = DataLoader( TestDataset( test_triples, all_true_triples, args.nentity, args.nrelation, 'head-batch' ), batch_size=args.test_batch_size, num_workers=max(1, args.cpu_num//2), collate_fn=TestDataset.collate_fn ) test_dataloader_tail = DataLoader( TestDataset( test_triples, all_true_triples, args.nentity, args.nrelation, 'tail-batch' ), batch_size=args.test_batch_size, num_workers=max(1, args.cpu_num//2), collate_fn=TestDataset.collate_fn ) test_dataset_list = [test_dataloader_head, test_dataloader_tail] logs = [] step = 0 total_steps = sum([len(dataset) for dataset in test_dataset_list]) # -------------------------------------------------- # Comments by Meng: # Here we slightly modify the codes to save the intermediate prediction results of KGE models, so that we can combine the predictions from KGE and MLN to improve the results. # -------------------------------------------------- predictions = [] with torch.no_grad(): for test_dataset in test_dataset_list: for positive_sample, negative_sample, filter_bias, mode in test_dataset: if args.cuda: positive_sample = positive_sample.cuda() negative_sample = negative_sample.cuda() filter_bias = filter_bias.cuda() # Save prediction results prediction = positive_sample.data.cpu().numpy().tolist() batch_size = positive_sample.size(0) score = torch.sigmoid(model((positive_sample, negative_sample), mode)) score += filter_bias #Explicitly sort all the entities to ensure that there is no test exposure bias valsort, argsort = torch.sort(score, dim = 1, descending=True) if mode == 'head-batch': positive_arg = positive_sample[:, 0] elif mode == 'tail-batch': positive_arg = positive_sample[:, 2] else: raise ValueError('mode %s not supported' % mode) for i in range(batch_size): #Notice that argsort is not ranking ranking = (argsort[i, :] == positive_arg[i]).nonzero() assert ranking.size(0) == 1 # For each test triplet, save the ranked list (h, r, [ts]) and ([hs], r, t) if mode == 'head-batch': prediction[i].append('h') prediction[i].append(ranking.item() + 1) ls = zip(argsort[i, 0:args.topk].data.cpu().numpy().tolist(), valsort[i, 0:args.topk].data.cpu().numpy().tolist()) prediction[i].append(ls) elif mode == 'tail-batch': prediction[i].append('t') prediction[i].append(ranking.item() + 1) ls = zip(argsort[i, 0:args.topk].data.cpu().numpy().tolist(), valsort[i, 0:args.topk].data.cpu().numpy().tolist()) prediction[i].append(ls) #ranking + 1 is the true ranking used in evaluation metrics ranking = 1 + ranking.item() logs.append({ 'MR': float(ranking), 'MRR': 1.0/ranking, 'HITS@1': 1.0 if ranking <= 1 else 0.0, 'HITS@3': 1.0 if ranking <= 3 else 0.0, 'HITS@10': 1.0 if ranking <= 10 else 0.0, }) predictions += prediction if step % args.test_log_steps == 0: logging.info('Evaluating the model... (%d/%d)' % (step, total_steps)) step += 1 metrics = {} for metric in logs[0].keys(): metrics[metric] = sum([log[metric] for log in logs])/len(logs) return metrics, predictions # -------------------------------------------------- # Comments by Meng: # Here we add a new function, which will predict the probability of each hidden triplet being true. # The results will be used by MLN. # -------------------------------------------------- @staticmethod def infer_step(model, infer_triples, args): batch_size = args.batch_size scores = [] model.eval() for k in range(0, len(infer_triples), batch_size): bg = k ed = min(k + batch_size, len(infer_triples)) batch = infer_triples[bg:ed] batch = torch.LongTensor(batch) if args.cuda: batch = batch.cuda() score = torch.sigmoid(model(batch)).squeeze(1) scores += score.data.cpu().numpy().tolist() return scores
18,193
37.222689
186
py
pLogicNet
pLogicNet-master/kge/run.py
#!/usr/bin/python3 from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import json import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader from model import KGEModel from dataloader import TrainDataset from dataloader import BidirectionalOneShotIterator def parse_args(args=None): parser = argparse.ArgumentParser( description='Training and Testing Knowledge Graph Embedding Models', usage='train.py [<args>] [-h | --help]' ) parser.add_argument('--cuda', action='store_true', help='use GPU') parser.add_argument('--do_train', action='store_true') parser.add_argument('--do_valid', action='store_true') parser.add_argument('--do_test', action='store_true') parser.add_argument('--evaluate_train', action='store_true', help='Evaluate on training data') parser.add_argument('--countries', action='store_true', help='Use Countries S1/S2/S3 datasets') parser.add_argument('--regions', type=int, nargs='+', default=None, help='Region Id for Countries S1/S2/S3 datasets, DO NOT MANUALLY SET') parser.add_argument('--data_path', type=str, default=None) parser.add_argument('--workspace_path', type=str, default=None) parser.add_argument('--model', default='TransE', type=str) parser.add_argument('-de', '--double_entity_embedding', action='store_true') parser.add_argument('-dr', '--double_relation_embedding', action='store_true') parser.add_argument('-n', '--negative_sample_size', default=128, type=int) parser.add_argument('-d', '--hidden_dim', default=500, type=int) parser.add_argument('-g', '--gamma', default=12.0, type=float) parser.add_argument('-adv', '--negative_adversarial_sampling', action='store_true') parser.add_argument('-a', '--adversarial_temperature', default=1.0, type=float) parser.add_argument('-b', '--batch_size', default=1024, type=int) parser.add_argument('-r', '--regularization', default=0.0, type=float) parser.add_argument('--test_batch_size', default=4, type=int, help='valid/test batch size') parser.add_argument('--uni_weight', action='store_true', help='Otherwise use subsampling weighting like in word2vec') parser.add_argument('-lr', '--learning_rate', default=0.0001, type=float) parser.add_argument('-cpu', '--cpu_num', default=10, type=int) parser.add_argument('-init', '--init_checkpoint', default=None, type=str) parser.add_argument('-save', '--save_path', default=None, type=str) parser.add_argument('--max_steps', default=100000, type=int) parser.add_argument('--warm_up_steps', default=None, type=int) parser.add_argument('--save_checkpoint_steps', default=10000, type=int) parser.add_argument('--valid_steps', default=10000, type=int) parser.add_argument('--log_steps', default=100, type=int, help='train log every xx steps') parser.add_argument('--test_log_steps', default=1000, type=int, help='valid/test log every xx steps') parser.add_argument('--nentity', type=int, default=0, help='DO NOT MANUALLY SET') parser.add_argument('--nrelation', type=int, default=0, help='DO NOT MANUALLY SET') parser.add_argument('--record', action='store_true') parser.add_argument('--topk', default=100, type=int) return parser.parse_args(args) def override_config(args): ''' Override model and data configuration ''' with open(os.path.join(args.init_checkpoint, 'config.json'), 'r') as fjson: argparse_dict = json.load(fjson) args.countries = argparse_dict['countries'] if args.data_path is None: args.data_path = argparse_dict['data_path'] args.model = argparse_dict['model'] args.double_entity_embedding = argparse_dict['double_entity_embedding'] args.double_relation_embedding = argparse_dict['double_relation_embedding'] args.hidden_dim = argparse_dict['hidden_dim'] args.test_batch_size = argparse_dict['test_batch_size'] def save_model(model, optimizer, save_variable_list, args): ''' Save the parameters of the model and the optimizer, as well as some other variables such as step and learning_rate ''' argparse_dict = vars(args) with open(os.path.join(args.save_path, 'config.json'), 'w') as fjson: json.dump(argparse_dict, fjson) torch.save({ **save_variable_list, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()}, os.path.join(args.save_path, 'checkpoint') ) entity_embedding = model.entity_embedding.detach().cpu().numpy() np.save( os.path.join(args.save_path, 'entity_embedding'), entity_embedding ) relation_embedding = model.relation_embedding.detach().cpu().numpy() np.save( os.path.join(args.save_path, 'relation_embedding'), relation_embedding ) def read_triple(file_path, entity2id, relation2id): ''' Read triples and map them into ids. ''' triples = [] with open(file_path) as fin: for line in fin: h, r, t = line.strip().split('\t') triples.append((entity2id[h], relation2id[r], entity2id[t])) return triples def set_logger(args): ''' Write logs to checkpoint and console ''' if args.do_train: log_file = os.path.join(args.save_path or args.init_checkpoint, 'train.log') else: log_file = os.path.join(args.save_path or args.init_checkpoint, 'test.log') logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', filename=log_file, filemode='w' ) console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) def log_metrics(mode, step, metrics): ''' Print the evaluation logs ''' for metric in metrics: logging.info('%s %s at step %d: %f' % (mode, metric, step, metrics[metric])) def ensure_dir(d): if not os.path.exists(d): os.makedirs(d) def main(args): if (not args.do_train) and (not args.do_valid) and (not args.do_test): raise ValueError('one of train/val/test mode must be choosed.') if args.init_checkpoint: override_config(args) elif args.data_path is None: raise ValueError('one of init_checkpoint/data_path must be choosed.') if args.do_train and args.save_path is None: raise ValueError('Where do you want to save your trained model?') if args.save_path and not os.path.exists(args.save_path): os.makedirs(args.save_path) # Write logs to checkpoint and console set_logger(args) with open(os.path.join(args.data_path, 'entities.dict')) as fin: entity2id = dict() id2entity = dict() for line in fin: eid, entity = line.strip().split('\t') entity2id[entity] = int(eid) id2entity[int(eid)] = entity with open(os.path.join(args.data_path, 'relations.dict')) as fin: relation2id = dict() id2relation = dict() for line in fin: rid, relation = line.strip().split('\t') relation2id[relation] = int(rid) id2relation[int(rid)] = relation # Read regions for Countries S* datasets if args.countries: regions = list() with open(os.path.join(args.data_path, 'regions.list')) as fin: for line in fin: region = line.strip() regions.append(entity2id[region]) args.regions = regions nentity = len(entity2id) nrelation = len(relation2id) args.nentity = nentity args.nrelation = nrelation logging.info('Model: %s' % args.model) logging.info('Data Path: %s' % args.data_path) logging.info('#entity: %d' % nentity) logging.info('#relation: %d' % nrelation) # -------------------------------------------------- # Comments by Meng: # During training, pLogicNet will augment the training triplets, # so here we load both the augmented triplets (train.txt) for training and # the original triplets (train_kge.txt) for evaluation. # Also, the hidden triplets (hidden.txt) are also loaded for annotation. # -------------------------------------------------- train_triples = read_triple(os.path.join(args.workspace_path, 'train_kge.txt'), entity2id, relation2id) logging.info('#train: %d' % len(train_triples)) train_original_triples = read_triple(os.path.join(args.data_path, 'train.txt'), entity2id, relation2id) logging.info('#train original: %d' % len(train_original_triples)) valid_triples = read_triple(os.path.join(args.data_path, 'valid.txt'), entity2id, relation2id) logging.info('#valid: %d' % len(valid_triples)) test_triples = read_triple(os.path.join(args.data_path, 'test.txt'), entity2id, relation2id) logging.info('#test: %d' % len(test_triples)) hidden_triples = read_triple(os.path.join(args.workspace_path, 'hidden.txt'), entity2id, relation2id) logging.info('#hidden: %d' % len(hidden_triples)) #All true triples all_true_triples = train_original_triples + valid_triples + test_triples kge_model = KGEModel( model_name=args.model, nentity=nentity, nrelation=nrelation, hidden_dim=args.hidden_dim, gamma=args.gamma, double_entity_embedding=args.double_entity_embedding, double_relation_embedding=args.double_relation_embedding ) logging.info('Model Parameter Configuration:') for name, param in kge_model.named_parameters(): logging.info('Parameter %s: %s, require_grad = %s' % (name, str(param.size()), str(param.requires_grad))) if args.cuda: kge_model = kge_model.cuda() if args.do_train: # Set training dataloader iterator train_dataloader_head = DataLoader( TrainDataset(train_triples, nentity, nrelation, args.negative_sample_size, 'head-batch'), batch_size=args.batch_size, shuffle=True, num_workers=max(1, args.cpu_num//2), collate_fn=TrainDataset.collate_fn ) train_dataloader_tail = DataLoader( TrainDataset(train_triples, nentity, nrelation, args.negative_sample_size, 'tail-batch'), batch_size=args.batch_size, shuffle=True, num_workers=max(1, args.cpu_num//2), collate_fn=TrainDataset.collate_fn ) train_iterator = BidirectionalOneShotIterator(train_dataloader_head, train_dataloader_tail) # Set training configuration current_learning_rate = args.learning_rate optimizer = torch.optim.Adam( filter(lambda p: p.requires_grad, kge_model.parameters()), lr=current_learning_rate ) if args.warm_up_steps: warm_up_steps = args.warm_up_steps else: warm_up_steps = args.max_steps // 2 if args.init_checkpoint: # Restore model from checkpoint directory logging.info('Loading checkpoint %s...' % args.init_checkpoint) checkpoint = torch.load(os.path.join(args.init_checkpoint, 'checkpoint')) init_step = checkpoint['step'] kge_model.load_state_dict(checkpoint['model_state_dict']) if args.do_train: current_learning_rate = checkpoint['current_learning_rate'] warm_up_steps = checkpoint['warm_up_steps'] optimizer.load_state_dict(checkpoint['optimizer_state_dict']) else: logging.info('Ramdomly Initializing %s Model...' % args.model) init_step = 0 step = init_step logging.info('Start Training...') logging.info('init_step = %d' % init_step) logging.info('learning_rate = %d' % current_learning_rate) logging.info('batch_size = %d' % args.batch_size) logging.info('negative_adversarial_sampling = %d' % args.negative_adversarial_sampling) logging.info('hidden_dim = %d' % args.hidden_dim) logging.info('gamma = %f' % args.gamma) logging.info('negative_adversarial_sampling = %s' % str(args.negative_adversarial_sampling)) if args.negative_adversarial_sampling: logging.info('adversarial_temperature = %f' % args.adversarial_temperature) if args.record: local_path = args.workspace_path ensure_dir(local_path) opt = vars(args) with open(local_path + '/opt.txt', 'w') as fo: for key, val in opt.items(): fo.write('{} {}\n'.format(key, val)) # Set valid dataloader as it would be evaluated during training if args.do_train: training_logs = [] #Training Loop for step in range(init_step, args.max_steps): log = kge_model.train_step(kge_model, optimizer, train_iterator, args) training_logs.append(log) if step >= warm_up_steps: current_learning_rate = current_learning_rate / 10 logging.info('Change learning_rate to %f at step %d' % (current_learning_rate, step)) optimizer = torch.optim.Adam( filter(lambda p: p.requires_grad, kge_model.parameters()), lr=current_learning_rate ) warm_up_steps = warm_up_steps * 3 if step % args.save_checkpoint_steps == 0: save_variable_list = { 'step': step, 'current_learning_rate': current_learning_rate, 'warm_up_steps': warm_up_steps } save_model(kge_model, optimizer, save_variable_list, args) if step % args.log_steps == 0: metrics = {} for metric in training_logs[0].keys(): metrics[metric] = sum([log[metric] for log in training_logs])/len(training_logs) log_metrics('Training average', step, metrics) training_logs = [] if args.do_valid and (step + 1) % args.valid_steps == 0: logging.info('Evaluating on Valid Dataset...') metrics, preds = kge_model.test_step(kge_model, valid_triples, all_true_triples, args) log_metrics('Valid', step, metrics) save_variable_list = { 'step': step, 'current_learning_rate': current_learning_rate, 'warm_up_steps': warm_up_steps } save_model(kge_model, optimizer, save_variable_list, args) if args.do_valid: logging.info('Evaluating on Valid Dataset...') metrics, preds = kge_model.test_step(kge_model, valid_triples, all_true_triples, args) log_metrics('Valid', step, metrics) # -------------------------------------------------- # Comments by Meng: # Save the prediction results of KGE on validation set. # -------------------------------------------------- if args.record: # Save the final results with open(local_path + '/result_kge_valid.txt', 'w') as fo: for metric in metrics: fo.write('{} : {}\n'.format(metric, metrics[metric])) # Save the predictions on test data with open(local_path + '/pred_kge_valid.txt', 'w') as fo: for h, r, t, f, rk, l in preds: fo.write('{}\t{}\t{}\t{}\t{}\n'.format(id2entity[h], id2relation[r], id2entity[t], f, rk)) for e, val in l: fo.write('{}:{:.4f} '.format(id2entity[e], val)) fo.write('\n') if args.do_test: logging.info('Evaluating on Test Dataset...') metrics, preds = kge_model.test_step(kge_model, test_triples, all_true_triples, args) log_metrics('Test', step, metrics) # -------------------------------------------------- # Comments by Meng: # Save the prediction results of KGE on test set. # -------------------------------------------------- if args.record: # Save the final results with open(local_path + '/result_kge.txt', 'w') as fo: for metric in metrics: fo.write('{} : {}\n'.format(metric, metrics[metric])) # Save the predictions on test data with open(local_path + '/pred_kge.txt', 'w') as fo: for h, r, t, f, rk, l in preds: fo.write('{}\t{}\t{}\t{}\t{}\n'.format(id2entity[h], id2relation[r], id2entity[t], f, rk)) for e, val in l: fo.write('{}:{:.4f} '.format(id2entity[e], val)) fo.write('\n') # -------------------------------------------------- # Comments by Meng: # Save the annotations on hidden triplets. # -------------------------------------------------- if args.record: # Annotate hidden triplets scores = kge_model.infer_step(kge_model, hidden_triples, args) with open(local_path + '/annotation.txt', 'w') as fo: for (h, r, t), s in zip(hidden_triples, scores): fo.write('{}\t{}\t{}\t{}\n'.format(id2entity[h], id2relation[r], id2entity[t], s)) if args.evaluate_train: logging.info('Evaluating on Training Dataset...') metrics, preds = kge_model.test_step(kge_model, train_triples, all_true_triples, args) log_metrics('Test', step, metrics) if __name__ == '__main__': main(parse_args())
18,047
39.832579
113
py
Tokenizer
Tokenizer-master/setup.py
#!/usr/bin/env python """ Tokenizer for Icelandic text Copyright (C) 2022 Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. """ from typing import Any import io import re from glob import glob from os.path import basename, dirname, join, splitext from setuptools import find_packages, setup # type: ignore def read(*names: str, **kwargs: Any) -> str: try: return io.open( join(dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8") ).read() except (IOError, OSError): return "" # Load version string from file __version__ = "[missing]" exec(open(join("src", "tokenizer", "version.py")).read()) setup( name="tokenizer", version=__version__, license="MIT", description="A tokenizer for Icelandic text", long_description="{0}\n{1}".format( re.compile("^.. start-badges.*^.. end-badges", re.M | re.S).sub( "", read("README.rst") ), re.sub(":[a-z]+:`~?(.*?)`", r"``\1``", read("CHANGELOG.rst")), ), author="Miðeind ehf.", author_email="[email protected]", url="https://github.com/mideind/Tokenizer", packages=find_packages("src"), package_dir={"": "src"}, py_modules=[splitext(basename(path))[0] for path in glob("src/*.py")], package_data={"tokenizer": ["py.typed", "tokenizer.pyi"]}, include_package_data=True, zip_safe=False, classifiers=[ # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: Unix", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Natural Language :: Icelandic", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Utilities", "Topic :: Text Processing :: Linguistic", ], keywords=["nlp", "tokenizer", "icelandic"], # Set up a tokenize command (tokenize.exe on Windows), # which calls main() in src/tokenizer/main.py entry_points={ "console_scripts": [ "tokenize=tokenizer.main:main", ], }, )
3,938
36.160377
90
py
Tokenizer
Tokenizer-master/src/tokenizer/main.py
#!/usr/bin/env python """ Tokenizer for Icelandic text Copyright (C) 2022 Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. This is an executable program wrapper (main module) for the Tokenizer package. It can be used to invoke the Tokenizer from the command line, or via fork() or exec(), with the command 'tokenize'. The main() function of this module is registered as a console_script entry point in setup.py. """ from typing import TextIO, Dict, Iterator, List, Callable, Any, Tuple, Union, cast import sys import argparse import json from functools import partial from .definitions import AmountTuple, BIN_Tuple, NumberTuple, PunctuationTuple from .tokenizer import TOK, Tok, tokenize ReadFile = argparse.FileType("r", encoding="utf-8") WriteFile = argparse.FileType("w", encoding="utf-8") # Define the command line arguments parser = argparse.ArgumentParser(description="Tokenizes Icelandic text") parser.add_argument( "infile", nargs="?", type=ReadFile, default=sys.stdin, help="UTF-8 text file to tokenize", ) parser.add_argument( "outfile", nargs="?", type=WriteFile, default=sys.stdout, help="UTF-8 output text file", ) group = parser.add_mutually_exclusive_group() group.add_argument( "--csv", help="Output one token per line in CSV format", action="store_true" ) group.add_argument( "--json", help="Output one token per line in JSON format", action="store_true" ) parser.add_argument( "-s", "--one_sent_per_line", action="store_true", help="Input contains one sentence per line", ) parser.add_argument( "-m", "--convert_measurements", action="store_true", help="Degree signal in temperature tokens normalized (200° C -> 200 °C)", ) parser.add_argument( "-p", "--coalesce_percent", action="store_true", help=( "Numbers combined into one token with percentage word forms " "(prósent/prósentustig/hundraðshlutar)" ), ) parser.add_argument( "-n", "--normalize", action="store_true", help="Outputs normalized value of punctuation tokens instead of original text", ) parser.add_argument( "-o", "--original", action="store_true", help="Outputs original text of tokens", ) parser.add_argument( "-g", "--keep_composite_glyphs", action="store_true", help="Composite glyphs not replaced with a single code point", ) parser.add_argument( "-e", "--replace_html_escapes", action="store_true", help="Escape codes from HTML replaced", ) parser.add_argument( "-c", "--convert_numbers", action="store_true", help=( "English-style decimal points and thousands separators " "in numbers changed to Icelandic style" ), ) parser.add_argument( "-k", "--handle_kludgy_ordinals", type=int, default=0, help=( "Kludgy ordinal handling defined.\n" "\t0: Returns the original word form.\n" "\t1: Ordinals returned as pure words.\n" "\t2: Ordinals returned as numbers." ), ) def main() -> None: """Main function, called when the tokenize command is invoked""" args = parser.parse_args() options: Dict[str, bool] = dict() def quote(s: str) -> str: """Return the string s within double quotes, and with any contained backslashes and double quotes escaped with a backslash""" return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"' def spanquote(l: List[int]) -> str: """Return the list l as a string within double quotes""" return '"' + "-".join(str(x) for x in l) + '"' def gen(f: TextIO) -> Iterator[str]: """Generate the lines of text in the input file""" for line in f: yield line def val(t: Tok, quote_word: bool = False) -> Any: """Return the value part of the token t""" if t.val is None: return None if t.kind == TOK.WORD: # Get the full expansion of an abbreviation mm = cast(List[BIN_Tuple], t.val) if quote_word: # Return a |-delimited list of possible meanings, # joined into a single string return quote("|".join(m[0] for m in mm)) # Return a list of all possible meanings return [m[0] for m in mm] if t.kind in {TOK.PERCENT, TOK.NUMBER, TOK.CURRENCY}: return cast(NumberTuple, t.val)[0] if t.kind == TOK.AMOUNT: am = cast(AmountTuple, t.val) if quote_word: # Format as "1234.56|USD" return '"{0}|{1}"'.format(am[0], am[1]) return am[0], am[1] if t.kind == TOK.S_BEGIN: return None if t.kind == TOK.PUNCTUATION: pt = cast(PunctuationTuple, t.val) return quote(pt[1]) if quote_word else pt[1] if quote_word and t.kind in { TOK.DATE, TOK.TIME, TOK.DATEABS, TOK.DATEREL, TOK.TIMESTAMP, TOK.TIMESTAMPABS, TOK.TIMESTAMPREL, TOK.TELNO, TOK.NUMWLETTER, TOK.MEASUREMENT, }: # Return a |-delimited list of numbers vv = cast(Tuple[Any, ...], t.val) return quote("|".join(str(v) for v in vv)) if quote_word and isinstance(t.val, str): return quote(t.val) return t.val to_text: Callable[[Tok], str] if args.normalize: to_text = lambda t: t.punctuation if t.kind == TOK.PUNCTUATION else t.txt elif args.original: to_text = lambda t: t.original or "" else: to_text = lambda t: t.txt if args.convert_measurements: options["convert_measurements"] = True if args.coalesce_percent: options["coalesce_percent"] = True if args.keep_composite_glyphs: # True is the default in tokenizer.py options["replace_composite_glyphs"] = False if args.replace_html_escapes: options["replace_html_escapes"] = True if args.convert_numbers: options["convert_numbers"] = True if args.one_sent_per_line: options["one_sent_per_line"] = True if args.handle_kludgy_ordinals: options["handle_kludgy_ordinals"] = args.handle_kludgy_ordinals if args.original: options["original"] = args.original # Configure our JSON dump function json_dumps = partial(json.dumps, ensure_ascii=False, separators=(",", ":")) curr_sent: List[str] = [] tsep = "" if args.original else " " # token separator for t in tokenize(gen(args.infile), **options): if args.csv: # Output the tokens in CSV format, one line per token if t.txt: print( "{0},{1},{2},{3},{4}".format( t.kind, quote(t.txt), val(t, quote_word=True) or '""', '""' if t.original is None else quote(t.original), "[]" if t.origin_spans is None else spanquote(t.origin_spans), ), file=args.outfile, ) elif t.kind == TOK.S_END: # Indicate end of sentence print('0,"","","",""', file=args.outfile) elif args.json: # Output the tokens in JSON format, one line per token d: Dict[str, Union[str, List[int]]] = dict(k=TOK.descr[t.kind]) if t.txt is not None: d["t"] = t.txt v = val(t) if v is not None: d["v"] = v if t.original is not None: d["o"] = t.original if t.origin_spans is not None: d["s"] = t.origin_spans print(json_dumps(d), file=args.outfile) else: # Normal shallow parse, sentences separated by newline by default, # tokens separated by spaces if t.kind in TOK.END: # End of sentence/paragraph if curr_sent: print(tsep.join(curr_sent), file=args.outfile) curr_sent = [] txt = to_text(t) if txt: curr_sent.append(txt) if curr_sent: print(tsep.join(curr_sent), file=args.outfile) if __name__ == "__main__": main()
9,652
30.545752
86
py
Tokenizer
Tokenizer-master/src/tokenizer/abbrev.py
""" Abbreviations module for tokenization of Icelandic text Copyright (C) 2022 Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. This module reads the definition of abbreviations from the file Abbrev.conf, assumed to be located in the same directory (or installation resource library) as this Python source file. """ from typing import Generic, Iterator, Optional, Set, List, Dict, TypeVar from threading import Lock from collections import defaultdict, OrderedDict from importlib.resources import open_text from .definitions import BIN_Tuple class ConfigError(Exception): pass _T = TypeVar("_T") class OrderedSet(Generic[_T]): """ Shim class to provide an ordered set API on top of an OrderedDict. This is necessary to make abbreviation lookups predictable and repeatable, which they would not be if a standard Python set() was used. """ def __init__(self) -> None: self._dict: Dict[_T, None] = OrderedDict() def add(self, item: _T) -> None: """ Add an item at the end of the ordered set """ if item not in self._dict: self._dict[item] = None def __contains__(self, item: _T) -> bool: return item in self._dict def __iter__(self) -> Iterator[_T]: return self._dict.__iter__() class Abbreviations: """ Wrapper around dictionary of abbreviations, initialized from the config file """ # Dictionary of abbreviations and their meanings DICT: Dict[str, OrderedSet[BIN_Tuple]] = defaultdict(OrderedSet) # Wrong versions of abbreviations WRONGDICT: Dict[str, OrderedSet[BIN_Tuple]] = defaultdict(OrderedSet) # All abbreviation meanings MEANINGS: Set[str] = set() # Single-word abbreviations, i.e. those with only one dot at the end SINGLES: Set[str] = set() # Set of abbreviations without periods, e.g. "td", "osfrv" WRONGSINGLES: Set[str] = set() # Potential sentence finishers, i.e. those with a dot at the end, # marked with an asterisk in the config file FINISHERS: Set[str] = set() # Abbreviations that should not be seen as such at the end of sentences, # marked with an exclamation mark in the config file NOT_FINISHERS: Set[str] = set() # Abbreviations that should not be seen as such at the end of sentences, but # are allowed in front of person names; marked with a hat ^ in the config file NAME_FINISHERS: Set[str] = set() # Wrong versions of abbreviations with possible corrections # wrong version : [correction1, correction2, ...] WRONGDOTS: Dict[str, List[str]] = defaultdict(list) # Word forms that should never be interpreted as abbreviations NOT_ABBREVIATIONS: Set[str] = set() # Ensure that only one thread initializes the abbreviations _lock = Lock() @staticmethod def add(abbrev: str, meaning: str, gender: str, fl: Optional[str] = None) -> None: """ Add an abbreviation to the dictionary. Called from the config file handler. """ # Check for sentence finishers finisher = False not_finisher = False name_finisher = False if abbrev.endswith("*"): # This abbreviation is explicitly allowed to finish a sentence finisher = True abbrev = abbrev[0:-1] if not abbrev.endswith("."): raise ConfigError( "Only abbreviations ending with periods can be sentence finishers" ) elif abbrev.endswith("!"): # A not-finisher cannot finish a sentence, because it is also a valid word # (Example: 'dags.', 'mín.', 'sek.') not_finisher = True abbrev = abbrev[0:-1] if not abbrev.endswith("."): raise ConfigError( "Only abbreviations ending with periods " "can be marked as not-finishers" ) elif abbrev.endswith("^"): # This abbreviation is only to be interpreted as an abbreviation # if it is followed by a name (example: 'próf.' for 'prófessor'). # This logic is not fully present in Tokenizer as information # about person names is needed to make it work. The full implementation, # using the NAME_FINISHERS set, is found in bintokenizer.py in # GreynirPackage. name_finisher = True abbrev = abbrev[0:-1] if not abbrev.endswith("."): raise ConfigError( "Only abbreviations ending with periods " "can be marked as name finishers" ) if abbrev.endswith("!") or abbrev.endswith("*") or abbrev.endswith("^"): raise ConfigError( "!, * and ^ modifiers are mutually exclusive on abbreviations" ) # Append the abbreviation and its meaning in tuple form # Multiple meanings are supported for each abbreviation Abbreviations.DICT[abbrev].add( BIN_Tuple(meaning, 0, gender, "skst" if fl is None else fl, abbrev, "-",) ) Abbreviations.MEANINGS.add(meaning) # Adding wrong versions of abbreviations if abbrev[-1] == "." and "." not in abbrev[0:-1]: # Only one dot, at the end # Lookup is without the dot wabbrev = abbrev[0:-1] Abbreviations.SINGLES.add(wabbrev) if finisher: Abbreviations.FINISHERS.add(wabbrev) Abbreviations.WRONGDOTS[wabbrev].append(abbrev) if len(wabbrev) > 1: # We don't add single letters (such as Í and Á) # as abbreviations, even though they are listed as such # in the form 'Í.' and 'Á.' for use within person names Abbreviations.WRONGDICT[wabbrev].add( BIN_Tuple(meaning, 0, gender, "skst" if fl is None else fl, wabbrev, "-",) ) elif "." in abbrev: # Only multiple dots, checked single dots above # Want to see versions with each one deleted, # and one where all are deleted indices = [pos for pos, char in enumerate(abbrev) if char == "."] for i in indices: # Removing one dot at a time wabbrev = abbrev[:i] + abbrev[i + 1 :] Abbreviations.WRONGDOTS[wabbrev].append(abbrev) Abbreviations.WRONGDICT[wabbrev].add( BIN_Tuple(meaning, 0, gender, "skst" if fl is None else fl, wabbrev, "-",) ) if len(indices) > 2: # 3 or 4 dots currently in vocabulary # Not all cases with 4 dots are handled. i1 = indices[0] i2 = indices[1] i3 = indices[2] wabbrevs: List[str] = [] # 1 and 2 removed wabbrevs.append(abbrev[:i1] + abbrev[i1 + 1 : i2] + abbrev[i2 + 1 :]) # 1 and 3 removed wabbrevs.append(abbrev[:i1] + abbrev[i1 + 1 : i3] + abbrev[i3 + 1 :]) # 2 and 3 removed wabbrevs.append(abbrev[:i2] + abbrev[i2 + 1 : i3] + abbrev[i3 + 1 :]) for wabbrev in wabbrevs: Abbreviations.WRONGDOTS[wabbrev].append(abbrev) Abbreviations.WRONGDICT[wabbrev].add( BIN_Tuple( meaning, 0, gender, "skst" if fl is None else fl, wabbrev, "-", ) ) # Removing all dots wabbrev = abbrev.replace(".", "") Abbreviations.WRONGSINGLES.add(wabbrev) Abbreviations.WRONGDOTS[wabbrev].append(abbrev) Abbreviations.WRONGDICT[wabbrev].add( BIN_Tuple(meaning, 0, gender, "skst" if fl is None else fl, wabbrev, "-",) ) if finisher: Abbreviations.FINISHERS.add(abbrev) if not_finisher: Abbreviations.NOT_FINISHERS.add(abbrev) if name_finisher: Abbreviations.NAME_FINISHERS.add(abbrev) @staticmethod def has_meaning(abbrev: str) -> bool: return abbrev in Abbreviations.DICT or abbrev in Abbreviations.WRONGDICT @staticmethod def has_abbreviation(meaning: str) -> bool: return meaning in Abbreviations.MEANINGS @staticmethod def get_meaning(abbrev: str) -> Optional[List[BIN_Tuple]]: """ Lookup meaning(s) of abbreviation, if available. """ m = Abbreviations.DICT.get(abbrev) if not m: m = Abbreviations.WRONGDICT.get(abbrev) return list(m) if m else None @staticmethod def _handle_abbreviations(s: str) -> None: """ Handle abbreviations in the settings section """ # Format: abbrev[*] = "meaning" gender (kk|kvk|hk) # An asterisk after an abbreviation ending with a period # indicates that the abbreviation may finish a sentence a = s.split("=", 1) # maxsplit=1 if len(a) != 2: raise ConfigError( "Wrong format for abbreviation: should be abbreviation = meaning" ) abbrev = a[0].strip() if not abbrev: raise ConfigError( "Missing abbreviation. Format should be abbreviation = meaning." ) m = a[1].strip().split('"') par = "" if len(m) >= 3: # Something follows the last quote par = m[-1].strip() gender = "hk" # Default gender is neutral fl = None # Default word category is None if par: p = par.split() if len(p) >= 1: gender = p[0].strip() if len(p) >= 2: fl = p[1].strip() Abbreviations.add(abbrev, m[1], gender, fl) @staticmethod def _handle_not_abbreviations(s: str) -> None: """ Handle not_abbreviations in the settings section """ if len(s) < 3 or s[0] != '"' or s[-1] != '"': raise ConfigError("not_abbreviations should be enclosed in double quotes") Abbreviations.NOT_ABBREVIATIONS.add(s[1:-1]) @staticmethod def initialize(): """ Read the abbreviations config file """ with Abbreviations._lock: if len(Abbreviations.DICT): # Already initialized return section = None config = open_text(package="tokenizer", resource="Abbrev.conf", encoding="utf-8") for s in config: # Ignore comments ix = s.find("#") if ix >= 0: s = s[0:ix] s = s.strip() if not s: # Blank line: ignore continue if s[0] == "[": # Section header (we are expecting [abbreviations]/[not_abbreviations]) if s not in {"[abbreviations]", "[not_abbreviations]"}: raise ConfigError("Wrong section header") section = s continue if section == "[abbreviations]": Abbreviations._handle_abbreviations(s) elif section == "[not_abbreviations]": Abbreviations._handle_not_abbreviations(s) else: raise ConfigError("Content outside section") # Remove not_abbreviations from WRONGDICT for abbr in Abbreviations.NOT_ABBREVIATIONS: if abbr in Abbreviations.WRONGDICT: del Abbreviations.WRONGDICT[abbr] Abbreviations.NOT_ABBREVIATIONS = set()
13,144
40.466877
94
py
Tokenizer
Tokenizer-master/src/tokenizer/definitions.py
""" Definitions used for tokenization of Icelandic text Copyright (C) 2022 Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. """ from typing import ( Dict, FrozenSet, Mapping, Tuple, Union, Callable, List, Sequence, Optional, NamedTuple, cast, ) import re BeginTuple = Tuple[int, Optional[int]] PunctuationTuple = Tuple[int, str] NumberTuple = Tuple[float, Optional[List[str]], Optional[List[str]]] DateTimeTuple = Tuple[int, int, int] MeasurementTuple = Tuple[str, float] TimeStampTuple = Tuple[int, int, int, int, int, int] AmountTuple = Tuple[float, str, Optional[List[str]], Optional[List[str]]] TelnoTuple = Tuple[str, str] CurrencyTuple = Tuple[str, Optional[List[str]], Optional[List[str]]] class BIN_Tuple(NamedTuple): stofn: str utg: int ordfl: str fl: str ordmynd: str beyging: str BIN_TupleList = Sequence[BIN_Tuple] class PersonNameTuple(NamedTuple): name: str gender: Optional[str] case: Optional[str] PersonNameList = Sequence[PersonNameTuple] # All possible contents of the Tok.val attribute ValType = Union[ None, int, # YEAR, ORDINAL str, # USERNAME BeginTuple, # S_BEGIN PunctuationTuple, # PUNCTUATION, NUMWLETTER MeasurementTuple, # MEASUREMENT TelnoTuple, # TELNO DateTimeTuple, # DATE, TIME TimeStampTuple, # TIMESTAMP NumberTuple, # PERCENT, NUMBER AmountTuple, # AMOUNT CurrencyTuple, # CURRENCY BIN_TupleList, # WORD PersonNameList, # PERSON ] # This seems to be needed as a workaround for Pylance/Pyright _escape = cast(Callable[[str], str], re.escape) ACCENT = chr(769) UMLAUT = chr(776) SOFT_HYPHEN = chr(173) ZEROWIDTH_SPACE = chr(8203) ZEROWIDTH_NBSP = chr(65279) # Preprocessing of unicode characters before tokenization UNICODE_REPLACEMENTS = { # Translations of separate umlauts and accents to single glyphs. # The strings to the left in each tuple are two Unicode code # points: vowel + COMBINING ACUTE ACCENT (chr(769)) or # vowel + COMBINING DIAERESIS (chr(776)). "a" + ACCENT: "á", "a" + UMLAUT: "ä", "e" + ACCENT: "é", "e" + UMLAUT: "ë", "i" + ACCENT: "í", "o" + ACCENT: "ó", "u" + ACCENT: "ú", "u" + UMLAUT: "ü", "y" + ACCENT: "ý", "o" + UMLAUT: "ö", "A" + UMLAUT: "Ä", "A" + ACCENT: "Á", "E" + ACCENT: "É", "E" + UMLAUT: "Ë", "I" + ACCENT: "Í", "O" + ACCENT: "Ó", "U" + ACCENT: "Ú", "U" + UMLAUT: "Ü", "Y" + ACCENT: "Ý", "O" + UMLAUT: "Ö", # Also remove these unwanted characters SOFT_HYPHEN: "", ZEROWIDTH_SPACE: "", ZEROWIDTH_NBSP: "", } UNICODE_REGEX = re.compile( r"|".join(map(_escape, UNICODE_REPLACEMENTS.keys())), re.UNICODE ) # Used for the first step of token splitting ROUGH_TOKEN_REGEX = re.compile(r"(\s*)([^\s]*)", re.UNICODE) # Constants for readability when using the ROUGH_TOKEN_REGEX ROUGH_TOKEN_REGEX_ENTIRE_MATCH = 0 ROUGH_TOKEN_REGEX_WHITE_SPACE_GROUP = 1 ROUGH_TOKEN_REGEX_TOKEN_GROUP = 2 # Hyphens are normalized to '-' HYPHEN = "-" # Normal hyphen EN_DASH = "\u2013" # "–" EM_DASH = "\u2014" # "—" HYPHENS = HYPHEN + EN_DASH + EM_DASH # Hyphens that may indicate composite words ('fjármála- og efnahagsráðuneyti') COMPOSITE_HYPHENS = HYPHEN + EN_DASH COMPOSITE_HYPHEN = EN_DASH # Recognized punctuation LEFT_PUNCTUATION = "([„‚«#$€£¥₽<" RIGHT_PUNCTUATION = ".,:;)]!%‰?“»”’‛‘…>°" CENTER_PUNCTUATION = '"*•&+=@©|' NONE_PUNCTUATION = "^/±'´~\\" + HYPHEN + EN_DASH + EM_DASH PUNCTUATION = ( LEFT_PUNCTUATION + CENTER_PUNCTUATION + RIGHT_PUNCTUATION + NONE_PUNCTUATION ) PUNCTUATION_REGEX = "[{0}]".format("|".join(re.escape(p) for p in PUNCTUATION)) # Punctuation types: left, center or right of word TP_LEFT = 1 # Whitespace to the left TP_CENTER = 2 # Whitespace to the left and right TP_RIGHT = 3 # Whitespace to the right TP_NONE = 4 # No whitespace TP_WORD = 5 # Flexible whitespace depending on surroundings # Matrix indicating correct spacing between tokens TP_SPACE = ( # Next token is: # LEFT CENTER RIGHT NONE WORD # Last token was TP_LEFT: (False, True, False, False, False), # Last token was TP_CENTER: (True, True, True, True, True), # Last token was TP_RIGHT: (True, True, False, False, True), # Last token was TP_NONE: (False, True, False, False, False), # Last token was TP_WORD: (True, True, False, False, True), ) # Punctuation that ends a sentence END_OF_SENTENCE = frozenset([".", "?", "!", "…"]) # Removed […] # Punctuation symbols that may additionally occur at the end of a sentence SENTENCE_FINISHERS = frozenset([")", "]", "“", "»", "”", "’", '"', "[…]"]) # Punctuation symbols that may occur inside words # Note that an EM_DASH is not allowed inside a word and will split words if present PUNCT_INSIDE_WORD = frozenset([".", "'", "‘", "´", "’", HYPHEN, EN_DASH]) # Punctuation symbols that can end words PUNCT_ENDING_WORD = frozenset(["'", "²", "³"]) # Punctuation symbols that may occur together PUNCT_COMBINATIONS = frozenset(["?", "!", "…"]) # Punctuation in end of indirect speech that doesn't necessarily end sentences PUNCT_INDIRECT_SPEECH = frozenset(["?", "!"]) # Single and double quotes SQUOTES = "'‚‛‘´" DQUOTES = '"“„”«»' CLOCK_ABBREVS = frozenset(("kl", "kl.", "klukkan")) # Allowed first digits in Icelandic telephone numbers TELNO_PREFIXES = "45678" # Known telephone country codes COUNTRY_CODES = frozenset( ( "354", "+354", "00354", ) ) # Words that can precede a year number; will be assimilated into the year token YEAR_WORD = frozenset(("árið", "ársins", "árinu")) # Characters that can start a numeric token DIGITS_PREFIX = frozenset([d for d in "0123456789"]) SIGN_PREFIX = frozenset(("+", "-")) # Month names and numbers MONTHS = { "janúar": 1, "janúars": 1, "febrúar": 2, "febrúars": 2, "mars": 3, "apríl": 4, "apríls": 4, "maí": 5, "maís": 5, "júní": 6, "júnís": 6, "júlí": 7, "júlís": 7, "ágúst": 8, "ágústs": 8, "september": 9, "septembers": 9, "október": 10, "októbers": 10, "nóvember": 11, "nóvembers": 11, "desember": 12, "desembers": 12, "jan.": 1, "feb.": 2, "mar.": 3, "apr.": 4, "jún.": 6, "júl.": 7, "ág.": 8, "ágú.": 8, "sep.": 9, "sept.": 9, "okt.": 10, "nóv.": 11, "des.": 12, "jan": 1, "feb": 2, "mar": 3, "apr": 4, "jún": 6, "júl": 7, "ág": 8, "ágú": 8, "sep": 9, "sept": 9, "okt": 10, "nóv": 11, "des": 12, } # The masculine Icelandic name should not be identified as a month MONTH_BLACKLIST = frozenset(("Ágúst",)) # Word forms that are not unambiguous as month names AMBIGUOUS_MONTH_NAMES = frozenset( ("jan", "Jan", "mar", "Mar", "júl", "Júl", "des", "Des", "Ágúst") ) # Max number of days in each month, indexed so that 1=January DAYS_IN_MONTH = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # Days of the month spelled out # DAYS_OF_MONTH = { # "fyrsti": 1, # "fyrsta": 1, # "annar": 2, # "annan": 2, # "þriðji": 3, # "þriðja": 3, # "fjórði": 4, # "fjórða": 4, # "fimmti": 5, # "fimmta": 5, # "sjötti": 6, # "sjötta": 6, # "sjöundi": 7, # "sjöunda": 7, # "áttundi": 8, # "áttunda": 8, # "níundi": 9, # "níunda": 9, # "tíundi": 10, # "tíunda": 10, # "ellefti": 11, # "ellefta": 11, # "tólfti": 12, # "tólfta": 12, # "þrettándi": 13, # "þrettánda": 13, # "fjórtándi": 14, # "fjórtánda": 14, # "fimmtándi": 15, # "fimmtánda": 15, # "sextándi": 16, # "sextánda": 16, # "sautjándi": 17, # "sautjánda": 17, # "átjándi": 18, # "átjánda": 18, # "nítjándi": 19, # "nítjánda": 19, # "tuttugasti": 20, # "tuttugasta": 20, # "þrítugasti": 30, # "þrítugasta": 30, # } # Time of day expressions spelled out CLOCK_NUMBERS: Mapping[str, Tuple[int, int, int]] = { "eitt": (1, 0, 0), "tvö": (2, 0, 0), "þrjú": (3, 0, 0), "fjögur": (4, 0, 0), "fimm": (5, 0, 0), "sex": (6, 0, 0), "sjö": (7, 0, 0), "átta": (8, 0, 0), "níu": (9, 0, 0), "tíu": (10, 0, 0), "ellefu": (11, 0, 0), "tólf": (12, 0, 0), "hálfeitt": (12, 30, 0), "hálftvö": (1, 30, 0), "hálfþrjú": (2, 30, 0), "hálffjögur": (3, 30, 0), "hálffimm": (4, 30, 0), "hálfsex": (5, 30, 0), "hálfsjö": (6, 30, 0), "hálfátta": (7, 30, 0), "hálfníu": (8, 30, 0), "hálftíu": (9, 30, 0), "hálfellefu": (10, 30, 0), "hálftólf": (11, 30, 0), } # Set of words only possible in temporal phrases CLOCK_HALF = frozenset( [ "hálfeitt", "hálftvö", "hálfþrjú", "hálffjögur", "hálffimm", "hálfsex", "hálfsjö", "hálfátta", "hálfníu", "hálftíu", "hálfellefu", "hálftólf", ] ) # 'Current Era', 'Before Current Era' CE = frozenset(("e.Kr", "e.Kr.")) # !!! Add AD and CE here? BCE = frozenset(("f.Kr", "f.Kr.")) # !!! Add BCE here? CE_BCE = CE | BCE # Supported ISO 4217 currency codes CURRENCY_ABBREV = frozenset( ( "ISK", # Icelandic króna "DKK", # Danish krone "NOK", # Norwegian krone "SEK", # Swedish krona "GBP", # British pounds sterling "USD", # US dollar "EUR", # Euro "CAD", # Canadian dollar "AUD", # Australian dollar "CHF", # Swiss franc "JPY", # Japanese yen "PLN", # Polish złoty "RUB", # Russian ruble "CZK", # Czech koruna "INR", # Indian rupee "IDR", # Indonesian rupiah "CNY", # Chinese renminbi "RMB", # Chinese renminbi (alternate) "HKD", # Hong Kong dollar "NZD", # New Zealand dollar "SGD", # Singapore dollar "MXN", # Mexican peso "ZAR", # South African rand ) ) # Map symbols to currency abbreviations CURRENCY_SYMBOLS = { "$": "USD", "€": "EUR", "£": "GBP", "¥": "JPY", # Also used for China's renminbi (yuan) "₽": "RUB", # Russian ruble } # Single-character vulgar fractions in Unicode SINGLECHAR_FRACTIONS = "↉⅒⅑⅛⅐⅙⅕¼⅓½⅖⅔⅜⅗¾⅘⅝⅚⅞" # Derived unit : (base SI unit, conversion factor/function) SI_UNITS: Dict[str, Tuple[str, Union[float, Callable[[float], float]]]] = { # Distance "m": ("m", 1.0), "mm": ("m", 1.0e-3), "μm": ("m", 1.0e-6), "cm": ("m", 1.0e-2), "sm": ("m", 1.0e-2), "km": ("m", 1.0e3), "ft": ("m", 0.3048), # feet "mi": ("m", 1609.34), # miles # Area "m²": ("m²", 1.0), "fm": ("m²", 1.0), "km²": ("m²", 1.0e6), "cm²": ("m²", 1.0e-2), "ha": ("m²", 1.0e4), # Volume "m³": ("m³", 1.0), "cm³": ("m³", 1.0e-6), "km³": ("m³", 1.0e9), "l": ("m³", 1.0e-3), "ltr": ("m³", 1.0e-3), "dl": ("m³", 1.0e-4), "cl": ("m³", 1.0e-5), "ml": ("m³", 1.0e-6), "gal": ("m³", 3.78541e-3), "bbl": ("m³", 158.987294928e-3), # Temperature "K": ("K", 1.0), "°K": ("K", 1.0), # Strictly speaking this should be K, not °K "°C": ("K", lambda x: x + 273.15), "°F": ("K", lambda x: (x + 459.67) * 5 / 9), # Mass "g": ("kg", 1.0e-3), "gr": ("kg", 1.0e-3), "kg": ("kg", 1.0), "t": ("kg", 1.0e3), "mg": ("kg", 1.0e-6), "μg": ("kg", 1.0e-9), "tn": ("kg", 1.0e3), "lb": ("kg", 0.453592), # Duration "s": ("s", 1.0), "ms": ("s", 1.0e-3), "μs": ("s", 1.0e-6), "klst": ("s", 3600.0), "mín": ("s", 60.0), # Force "N": ("N", 1.0), "kN": ("N", 1.0e3), # Energy "Nm": ("J", 1.0), "J": ("J", 1.0), "kJ": ("J", 1.0e3), "MJ": ("J", 1.0e6), "GJ": ("J", 1.0e9), "TJ": ("J", 1.0e12), "kWh": ("J", 3.6e6), "MWh": ("J", 3.6e9), "kWst": ("J", 3.6e6), "MWst": ("J", 3.6e9), "kcal": ("J", 4184.0), "cal": ("J", 4.184), # Power "W": ("W", 1.0), "mW": ("W", 1.0e-3), "kW": ("W", 1.0e3), "MW": ("W", 1.0e6), "GW": ("W", 1.0e9), "TW": ("W", 1.0e12), # Electric potential "V": ("V", 1.0), "mV": ("V", 1.0e-3), "kV": ("V", 1.0e3), # Electric current "A": ("A", 1.0), "mA": ("A", 1.0e-3), # Frequency "Hz": ("Hz", 1.0), "kHz": ("Hz", 1.0e3), "MHz": ("Hz", 1.0e6), "GHz": ("Hz", 1.0e9), # Pressure "Pa": ("Pa", 1.0), "hPa": ("Pa", 1.0e2), # Angle "°": ("°", 1.0), # Degree # Percentage and promille "%": ("%", 1.0), "‰": ("‰", 0.1), # Velocity "m/s": ("m/s", 1.0), "km/klst": ("m/s", 1000.0 / (60 * 60)), # "km/klst.": ("m/s", 1000.0/(60*60)), } DIRECTIONS = { "N": "Norður", } _unit_lambda: Callable[[str], str] = ( lambda unit: unit + r"(?!\w)" if unit[-1].isalpha() else unit ) SI_UNITS_SET: FrozenSet[str] = frozenset(SI_UNITS.keys()) SI_UNITS_REGEX_STRING = r"|".join( map( # If the unit ends with a letter, don't allow the next character # after it to be a letter (i.e. don't match '220Volts' as '220V') _unit_lambda, # Sort in descending order by length, so that longer strings # are matched before shorter ones sorted(SI_UNITS.keys(), key=len, reverse=True), ) ) SI_UNITS_REGEX = re.compile(r"({0})".format(SI_UNITS_REGEX_STRING), re.UNICODE) CURRENCY_REGEX_STRING = r"|".join( map( # Sort in descending order by length, so that longer strings # are matched before shorter ones _escape, sorted(CURRENCY_SYMBOLS.keys(), key=lambda s: len(s), reverse=True), ) ) # Combined pattern regex for SI units, percentage, promille and currency symbols UNIT_REGEX_STRING = SI_UNITS_REGEX_STRING + r"|" + CURRENCY_REGEX_STRING # Icelandic-style number, followed by a unit NUM_WITH_UNIT_REGEX1 = re.compile( r"([-+]?\d+(\.\d\d\d)*(,\d+)?)({0})".format(UNIT_REGEX_STRING), re.UNICODE ) # English-style number, followed by a unit NUM_WITH_UNIT_REGEX2 = re.compile( r"([-+]?\d+(,\d\d\d)*(\.\d+)?)({0})".format(UNIT_REGEX_STRING), re.UNICODE ) # One or more digits, followed by a unicode vulgar fraction char (e.g. '2½') # and a unit (SI, percent or currency symbol) NUM_WITH_UNIT_REGEX3 = re.compile( r"(\d+)([\u00BC-\u00BE\u2150-\u215E])({0})".format(UNIT_REGEX_STRING), re.UNICODE ) # If the handle_kludgy_ordinals option is set to # KLUDGY_ORDINALS_PASS_THROUGH, we do not convert # kludgy ordinals but pass them through as word tokens. KLUDGY_ORDINALS_PASS_THROUGH = 0 # If the handle_kludgy_ordinals option is set to # KLUDGY_ORDINALS_MODIFY, we convert '1sti' to 'fyrsti', etc., # and return the modified word as a token. KLUDGY_ORDINALS_MODIFY = 1 # If the handle_kludgy_ordinals option is set to # KLUDGY_ORDINALS_TRANSLATE, we convert '1sti' to TOK.Ordinal('1sti', 1), etc., # but otherwise pass the original word through as a word token ('2ja'). KLUDGY_ORDINALS_TRANSLATE = 2 # Incorrectly written ('kludgy') ordinals ORDINAL_ERRORS = { "1sti": "fyrsti", "1sta": "fyrsta", "1stu": "fyrstu", "3ji": "þriðji", # "3ja": "þriðja", # þriggja "3ju": "þriðju", "4ði": "fjórði", "4ða": "fjórða", "4ðu": "fjórðu", "5ti": "fimmti", "5ta": "fimmta", "5tu": "fimmtu", "2svar": "tvisvar", "3svar": "þrisvar", "2ja": "tveggja", "3ja": "þriggja", "4ra": "fjögurra", } # Translations of kludgy ordinal words into numbers ORDINAL_NUMBERS = { "1sti": 1, "1sta": 1, "1stu": 1, "3ji": 3, "3ja": 3, "3ju": 3, "4ði": 4, "4ða": 4, "4ðu": 4, "5ti": 5, "5ta": 5, "5tu": 5, } # Handling of Roman numerals RE_ROMAN_NUMERAL = re.compile( r"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" ) ROMAN_NUMERAL_MAP = tuple( zip( (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1), ("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"), ) ) def roman_to_int(s: str) -> int: """Quick and dirty conversion of an already validated Roman numeral to integer""" # Adapted from http://code.activestate.com/recipes/81611-roman-numerals/ i = result = 0 for integer, numeral in ROMAN_NUMERAL_MAP: while s[i : i + len(numeral)] == numeral: result += integer i += len(numeral) assert i == len(s) return result NUMBER_ABBREV = { "þús.": 1000, "millj.": 10**6, "mljó.": 10**6, "ma.": 10**9, "mrð.": 10**9, "billj.": 10**12, "bljó.": 10**12, "trillj.": 10**18, } # Recognize words for percentages PERCENTAGES = { "prósent": 1, "prósenta": 1, "prósenti": 1, "prósents": 1, "prósentur": 1, "prósentum": 1, "hundraðshluti": 1, "hundraðshluta": 1, "hundraðshlutar": 1, "hundraðshlutum": 1, "prósentustig": 1, "prósentustigi": 1, "prósentustigs": 1, "prósentustigum": 1, "prósentustiga": 1, } # Amount abbreviations including 'kr' for the ISK # Corresponding abbreviations are found in Abbrev.conf AMOUNT_ABBREV = { "kr.": 1, "kr": 1, "krónur": 1, "þ.kr.": 1e3, "þ.kr": 1e3, "þús.kr.": 1e3, "þús.kr": 1e3, "m.kr.": 1e6, "m.kr": 1e6, "mkr.": 1e6, "mkr": 1e6, "millj.kr.": 1e6, "millj.kr": 1e6, "mljó.kr.": 1e6, "mljó.kr": 1e6, "ma.kr.": 1e9, "ma.kr": 1e9, "mö.kr.": 1e9, "mö.kr": 1e9, "mlja.kr.": 1e9, "mlja.kr": 1e9, # "mrð.kr.": 1e9, # "mrð.kr": 1e9, # "billj.kr.": 1e12, # "billj.kr": 1e12, # "trillj.kr.": 1e18, # "trillj.kr": 1e18, } # Króna amount strings allowed before a number, e.g. "kr. 9.900" ISK_AMOUNT_PRECEDING = frozenset(("kr.", "kr", "krónur")) # URL prefixes. Note that this list should not contain www since # www.something.com is a domain token, not a URL token. URL_PREFIXES = ( "http://", "https://", "file://", "ftp://", "ssh://", "sftp://", "smb://", "git://", "svn://", "svn+ssh://", "imap://", "rtmp://", "telnet://", "udp://", "vnc://", ) TOP_LEVEL_DOMAINS = frozenset( ( "com", "org", "net", "edu", "gov", "mil", "int", "arpa", "eu", "biz", "info", "xyz", "online", "site", "tech", "top", "space", "news", "pro", "club", "loan", "win", "vip", "icu", "app", "blog", "shop", "work", "ltd", "mobi", "live", "store", "gdn", "art", "events", # ccTLDs "ac", "ad", "ae", "af", "ag", "ai", "al", "am", "ao", "aq", "ar", "as", "at", "au", "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bw", "by", "bz", "ca", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cu", "cv", "cw", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "er", "es", "et", "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", # "kr", # Clashes with "kr" abbreviation (e.g. "þús.kr" is a legitimate domain name) "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sk", "sl", "sm", "sn", "so", "sr", "ss", "st", "sv", "sx", "sy", "sz", "tc", "td", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tr", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "ye", "yt", "za", "zm", "zw", ) ) # Regex to recognise domain names MIN_DOMAIN_LENGTH = 4 # E.g. "t.co" DOMAIN_REGEX = re.compile( r"({0})({1}*)$".format( r"|".join(r"\w\." + d for d in map(_escape, TOP_LEVEL_DOMAINS)), PUNCTUATION_REGEX, ), re.UNICODE, ) # A list of the symbols of the natural elements. # Note that single-letter symbols should follow two-letter symbols, # so that regexes do not match the single-letter ones greedily before # the two-letter ones. ELEMENTS = ( "Ac", "Ag", "Al", "Am", "Ar", "As", "At", "Au", "Ba", "Be", "Bh", "Bi", "Bk", "Br", "B", "Ca", "Cd", "Ce", "Cf", "Cl", "Cm", "Cn", "Co", "Cr", "Cs", "Cu", "C", "Db", "Ds", "Dy", "Er", "Es", "Eu", "Fe", "Fl", "Fm", "Fr", "F", "Ga", "Gd", "Ge", "He", "Hf", "Hg", "Ho", "Hs", "H", "In", "Ir", "I", "Kr", "K", "La", "Li", "Lr", "Lu", "Lv", "Mc", "Md", "Mg", "Mn", "Mo", "Mt", "Na", "Nb", "Nd", "Ne", "Nh", "Ni", "No", "Np", "N", "Og", "Os", "O", "Pa", "Pb", "Pd", "Pm", "Po", "Pr", "Pt", "Pu", "P", "Ra", "Rb", "Re", "Rf", "Rg", "Rh", "Rn", "Ru", "Sb", "Sc", "Se", "Sg", "Si", "Sm", "Sn", "Sr", "S", "Ta", "Tb", "Tc", "Te", "Th", "Ti", "Tl", "Tm", "Ts", "U", "V", "W", "Xe", "Yb", "Y", "Zn", "Zr", ) # Regex to recognize molecules ('H2SO4') # Note that we place a further constraint on the token so that # it must contain at least one digit to qualify as a molecular formula ELEMENTS_REGEX = r"|".join(ELEMENTS) MOLECULE_REGEX = re.compile(r"^(({0})+\d*)+".format(ELEMENTS_REGEX)) MOLECULE_FILTER = re.compile(r"\d") # Validation of Icelandic social security numbers KT_MAGIC = [3, 2, 7, 6, 5, 4, 0, 3, 2] def valid_ssn(kt: str) -> bool: """Validate Icelandic social security number""" if not kt or len(kt) != 11 or kt[6] != "-": return False m = 11 - sum((ord(kt[i]) - 48) * KT_MAGIC[i] for i in range(9)) % 11 c = ord(kt[9]) - 48 return m == 11 if c == 0 else m == c # HTML escaped characters/ligatures, e.g. '&aacute;' meaning 'á'. # The following is a subset of HTML escape codes, roughly selected # by analyzing the content of the Icelandic Gigaword Corpus (Risamálheild). HTML_ESCAPES = { # Icelandic letters "aacute": "á", "eth": "ð", "eacute": "é", "iacute": "í", "oacute": "ó", "uacute": "ú", "yacute": "ý", "thorn": "þ", "aelig": "æ", "ouml": "ö", "Aacute": "Á", "ETH": "Ð", "Eacute": "É", "Iacute": "Í", "Oacute": "Ó", "Uacute": "Ú", "Yacute": "Ý", "THORN": "Þ", "AElig": "Æ", "Ouml": "Ö", # Punctuation "amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'", "bdquo": "„", "ldquo": "“", "rdquo": "”", "lsquo": "‘", "acute": "´", "lcub": "{", "rcub": "}", "darr": "↓", "uarr": "↑", "ring": "˚", "deg": "°", "diam": "⋄", "ordm": "º", "ogon": "˛", "hellip": "…", "copy": "©", "reg": "®", "trade": "™", # Spaces - all spaces are mapped to \x20 "nbsp": " ", "ensp": " ", "emsp": " ", "thinsp": " ", # Dashes and hyphens "ndash": "–", "mdash": "—", # The soft hyphen &shy; is mapped to an empty string "shy": "", # Other non-ASCII letters "uuml": "ü", "Uuml": "Ü", "zcaron": "ž", "Zcaron": "Ž", "lstrok": "ł", "Lstrok": "Ł", "ntilde": "ñ", "inodot": "ı", # Ligatures "filig": "fi", "fllig": "fl", } ESCAPES_REGEX = r"|".join(HTML_ESCAPES.keys()) HTML_ESCAPE_REGEX = re.compile( r"&((#x[0-9a-fA-F]{r1})|(#\d{r2})|({ex}))\;".format( r1="{1,8}", r2="{1,10}", ex=ESCAPES_REGEX ) )
27,539
20.787975
92
py
Tokenizer
Tokenizer-master/src/tokenizer/version.py
__version__ = "3.4.2"
22
10.5
21
py
Tokenizer
Tokenizer-master/src/tokenizer/tokenizer.py
""" Tokenizer for Icelandic text Copyright (C) 2022 Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. The function tokenize() consumes a text string and returns a generator of tokens. Each token is a named tuple, having the form (kind, txt, val), where kind is one of the constants specified in the TOK class, txt is the original source text, and val contains auxiliary information depending on the token type (such as the meaning of an abbreviation, or the day, month and year for dates). """ from typing import ( Any, Callable, Deque, FrozenSet, Iterable, Iterator, List, Mapping, Match, Optional, Tuple, Type, TypeVar, Union, cast, ) import datetime import re import unicodedata # type: ignore from collections import deque from .abbrev import Abbreviations from .definitions import * _T = TypeVar("_T", bound="Tok") # Set of punctuation characters that are grouped into one # normalized exclamation EXCLAMATIONS = frozenset(("!", "?")) # Global constants for readability SPAN_START = 0 SPAN_END = 1 class Tok: """Information about a single token""" def __init__( self, kind: int, txt: Optional[str], val: ValType, original: Optional[str] = None, origin_spans: Optional[List[int]] = None, ) -> None: # Type of token self.kind: int = kind # Text of the token self.txt: str = txt or "" # Value of the token (e.g. if it is a date or currency) self.val: ValType = val # The full original source string behind this token. # If this is None then we're not tracking origins. self.original: Optional[str] = original # origin_spans contains an integer for each character in 'txt'. # Each such integer index maps the corresponding character # (which may have substitutions) to its index in 'original'. # This is required to preserve 'original' correctly when splitting. self.origin_spans: Optional[List[int]] = origin_spans @classmethod def from_txt(cls: Type[_T], txt: str) -> _T: """Create a token from text""" return cls(TOK.RAW, txt, None, txt, list(range(len(txt)))) @classmethod def from_token(cls: Type[_T], t: "Tok") -> _T: """Create a new Tok instance by copying from a previously existing one""" return cls( t.kind, t.txt, t.val, t.original, None if t.origin_spans is None else t.origin_spans[:], ) @property def punctuation(self) -> str: """Return the punctuation symbol associated with the token, if it is in fact a punctuation token""" if self.kind != TOK.PUNCTUATION: # This is not a punctuation token. In that case, # we return the Unicode 'unrecognized character' # code, which will not match any 'x in s' checks # where s is a legitimate string or set. return "\ufffd" return cast(PunctuationTuple, self.val)[1] @property def number(self) -> float: """Return a float embedded in a Number or Year token""" if self.kind == TOK.YEAR: return float(cast(int, self.val)) if self.kind == TOK.NUMBER: return cast(NumberTuple, self.val)[0] raise ValueError("Expected NUMBER or YEAR token in Tok.number()") @property def integer(self) -> int: """Return an integer from a token, which is assumed to be a Number or a Year token""" if self.kind == TOK.YEAR: return cast(int, self.val) if self.kind == TOK.NUMBER: return int(cast(NumberTuple, self.val)[0]) raise ValueError("Expected NUMBER or YEAR token in Tok.integer()") @property def ordinal(self) -> int: """Return an ordinal number from a token, which is assumed to be a Number or an Ordinal token""" if self.kind == TOK.ORDINAL: return cast(int, self.val) if self.kind == TOK.NUMBER: return int(cast(NumberTuple, self.val)[0]) raise ValueError("Expected NUMBER or ORDINAL token in Tok.ordinal()") @property def has_meanings(self) -> bool: """Return True if this is a word token and has meanings, i.e. associated BIN_Tuple instances""" if self.kind != TOK.WORD: return False return bool(self.val) @property def meanings(self) -> BIN_TupleList: """Return the meanings of this token if it is a word, otherwise return an empty list""" if self.kind != TOK.WORD: return [] return cast(BIN_TupleList, self.val) or [] @property def person_names(self) -> PersonNameList: """Return the person names of this token if it denotes a PERSON, otherwise return an empty list""" if self.kind != TOK.PERSON: return [] return cast(PersonNameList, self.val) or [] def split(self, pos: int) -> Tuple["Tok", "Tok"]: """Split this token into two at 'pos'. The first token returned will have 'pos' characters and the second one will have the rest. """ # TODO: What happens if you split a token that has # txt=="" and original!=""? # TODO: What should we do with val? l: Tok r: Tok if self.origin_spans is not None and self.original is not None: if pos >= len(self.origin_spans): l = Tok( self.kind, self.txt, self.val, self.original, self.origin_spans, ) r = Tok(self.kind, "", None, "", []) else: l = Tok( self.kind, self.txt[:pos], self.val, self.original[: self.origin_spans[pos]], self.origin_spans[:pos], ) r = Tok( self.kind, self.txt[pos:], self.val, self.original[self.origin_spans[pos] :], [x - self.origin_spans[pos] for x in self.origin_spans[pos:]], ) else: l = Tok(self.kind, self.txt[:pos], self.val) r = Tok(self.kind, self.txt[pos:], self.val) return l, r def substitute(self, span: Tuple[int, int], new: str) -> None: """Substitute a span with a single or empty character 'new'.""" self.txt = self.txt[: span[0]] + new + self.txt[span[1] :] if self.origin_spans is not None: # Remove origin entries that correspond to characters that are gone. self.origin_spans = ( self.origin_spans[: span[0] + len(new)] + self.origin_spans[span[1] :] ) def substitute_longer(self, span: Tuple[int, int], new: str) -> None: """Substitute a span with a potentially longer string""" # This tracks origin differently from the regular # substitution function. # Due to the inobviousness of how to assign origin to # the new string we simply make it have an empty origin. # This will probably cause some weirdness if this string # later gets split or substituted but that should not # happen in the current implementation. self.txt = self.txt[: span[0]] + new + self.txt[span[1] :] if self.origin_spans is not None and self.original is not None: head = self.origin_spans[: span[0]] tail = self.origin_spans[span[1] :] # The origin span of the new stuff will be of length 0 since we can't # proprely attribute it to individual characters in the original string. if len(tail) == 0: # We're replacing the end of the string # Can't pick the next element after the removed string since it doesn't exist # Use the length instead new_origin = len(self.original) else: new_origin = self.origin_spans[span[1]] self.origin_spans = head + [new_origin] * len(new) + tail def substitute_all(self, old_str: str, new_char: str) -> None: """Substitute all occurrences of 'old_str' with 'new_char'. The new character may be empty. """ # NOTE: This implementation is worst-case-quadratic in the # length of the token text. # Fortunately tokens are almost always (?) short so # this is an acceptable tradeoff for a simple implementation. # TODO: Support arbitrary length substitutions? # What does that do to origin tracking? assert len(new_char) <= 1, f"'new_char' ({new_char}) was too long." while True: i = self.txt.find(old_str) if i == -1: # No occurences of 'old_str' remain break self.substitute((i, i + len(old_str)), new_char) def concatenate( self, other: "Tok", *, separator: str = "", metadata_from_other: bool = False, ) -> "Tok": """Return a new token that consists of self with other concatenated to the end. A separator can optionally be supplied. The new token will have metadata (kind and val) from self unless 'metadata_from_other' is True. """ new_kind = self.kind if not metadata_from_other else other.kind new_val = self.val if not metadata_from_other else other.val self_txt = self.txt or "" other_txt = other.txt or "" new_txt = self_txt + separator + other_txt self_original = self.original or "" other_original = other.original or "" new_original = self_original + other_original self_origin_spans = self.origin_spans or [] other_origin_spans = other.origin_spans or [] separator_origin_spans: List[int] = ( [len(self_original)] * len(separator) if len(other_origin_spans) > 0 else [] ) new_origin_spans = ( self_origin_spans + separator_origin_spans + [i + len(self_original) for i in other_origin_spans] ) return Tok(new_kind, new_txt, new_val, new_original, new_origin_spans) @property def as_tuple(self) -> Tuple[Any, ...]: """Return the contents of this token as a generic tuple, suitable e.g. for serialization""" return (self.kind, self.txt, self.val) def __getitem__(self, i: int) -> Union[int, str, ValType]: """Backwards compatibility for when Tok was a namedtuple.""" if i == 0: return self.kind elif i == 1: return self.txt elif i == 2: return self.val else: raise IndexError("Tok can only be indexed by 0, 1 or 2") def equal(self, other: "Tok") -> bool: """Equality of content between two tokens, i.e. ignoring the 'original' and 'origin_spans' attributes""" return ( self.kind == other.kind and self.txt == other.txt and self.val == other.val ) def __eq__(self, o: Any) -> bool: """Full equality between two Tok instances""" if not isinstance(o, Tok): return False return ( self.kind == o.kind and self.txt == o.txt and self.val == o.val and self.original == o.original and self.origin_spans == o.origin_spans ) def __repr__(self) -> str: def quoted_string_repr(obj: Any) -> str: if isinstance(obj, str): return f'"{obj}"' else: return str(obj) return ( f"Tok({self.kind}, {quoted_string_repr(self.txt)}, " f"{self.val}, {quoted_string_repr(self.original)}, {self.origin_spans})" ) class TOK: """ The TOK class contains constants that define token types and constructors for creating token instances. Each of the various constructors can accept as first parameter either a string or a Tok object. The string version is the old one (from versions 2 and earlier). These take in a string and sometimes value and return a token with that string and value. This should be preserved while there are downstream users that depend on this behavior. The tokenizer does not use this internally. The Tok version of the constructors isn't really a constructor but rather a converter. It takes in a token and returns a token with the given type and value but preserves other attributes, in particular origin tracking. Note that the current version modifies the input and returns it again. This particular detail should not be depended on (assume the input is eaten and something new is returned). If, at some point, we can be reasonably certain that downstream users are not using the string version any more we should consider removing it. """ # Token types # Raw minimally processed token RAW = -1 # Punctuation PUNCTUATION = 1 # Time hh:mm:ss TIME = 2 # Date yyyy-mm-dd DATE = 3 # Year, four digits YEAR = 4 # Number, integer or real NUMBER = 5 # Word, which may contain hyphens and apostrophes WORD = 6 # Telephone number: 7 digits, eventually preceded by country code TELNO = 7 # Percentage (number followed by percent or promille sign) PERCENT = 8 # A Uniform Resource Locator (URL): https://example.com/path?p=100 URL = 9 # An ordinal number, eventually using Roman numerals (1., XVII.) ORDINAL = 10 # A timestamp (not emitted by Tokenizer) TIMESTAMP = 11 # A currency sign or code CURRENCY = 12 # An amount, i.e. a quantity with a currency code AMOUNT = 13 # Person name (not used by Tokenizer) PERSON = 14 # E-mail address ([email protected]) EMAIL = 15 # Entity name (not used by Tokenizer) ENTITY = 16 # Unknown token type UNKNOWN = 17 # Absolute date DATEABS = 18 # Relative date DATEREL = 19 # Absolute time stamp, yyyy-mm-dd hh:mm:ss TIMESTAMPABS = 20 # Relative time stamp, yyyy-mm-dd hh:mm:ss # where at least of yyyy, mm or dd is missing TIMESTAMPREL = 21 # A measured quantity with its unit (220V, 0.5 km) MEASUREMENT = 22 # Number followed by letter (a-z), often seen in addresses (Skógarstígur 4B) NUMWLETTER = 23 # Internet domain name (an.example.com) DOMAIN = 24 # Hash tag (#metoo) HASHTAG = 25 # Chemical compound ('H2SO4') MOLECULE = 26 # Social security number ('kennitala') SSN = 27 # Social media user name ('@username_123') USERNAME = 28 # Serial number ('394-8362') SERIALNUMBER = 29 # Company name ('Google Inc.') COMPANY = 30 # Sentinel value to for metatokens. # Metatokens are tokens that are not directly based on characters in the text. # Users can compare a token's kind with META_BEGIN to distinguish between # metatokens and other tokens. # Regular token kinds have a value less than META_BEGIN and # metatokens have a kind greater than META_BEGIN. META_BEGIN = 9999 # Sentence split token S_SPLIT = 10000 # Paragraph begin P_BEGIN = 10001 # Paragraph end P_END = 10002 # Sentence begin S_BEGIN = 11001 # Sentence end S_END = 11002 # End sentinel X_END = 12001 END = frozenset((P_END, S_END, X_END, S_SPLIT)) BEGIN = frozenset((P_BEGIN, S_BEGIN)) TEXT = frozenset((WORD, PERSON, ENTITY, MOLECULE, COMPANY)) TEXT_EXCL_PERSON = frozenset((WORD, ENTITY, MOLECULE, COMPANY)) # Token descriptive names descr: Mapping[int, str] = { PUNCTUATION: "PUNCTUATION", TIME: "TIME", TIMESTAMP: "TIMESTAMP", TIMESTAMPABS: "TIMESTAMPABS", TIMESTAMPREL: "TIMESTAMPREL", DATE: "DATE", DATEABS: "DATEABS", DATEREL: "DATEREL", YEAR: "YEAR", NUMBER: "NUMBER", NUMWLETTER: "NUMWLETTER", CURRENCY: "CURRENCY", AMOUNT: "AMOUNT", MEASUREMENT: "MEASUREMENT", PERSON: "PERSON", WORD: "WORD", UNKNOWN: "UNKNOWN", TELNO: "TELNO", PERCENT: "PERCENT", URL: "URL", DOMAIN: "DOMAIN", HASHTAG: "HASHTAG", EMAIL: "EMAIL", ORDINAL: "ORDINAL", ENTITY: "ENTITY", MOLECULE: "MOLECULE", SSN: "SSN", USERNAME: "USERNAME", SERIALNUMBER: "SERIALNUMBER", COMPANY: "COMPANY", S_SPLIT: "SPLIT SENT", P_BEGIN: "BEGIN PARA", P_END: "END PARA", S_BEGIN: "BEGIN SENT", S_END: "END SENT", } # Token constructors @staticmethod def Punctuation(t: Union[Tok, str], normalized: Optional[str] = None) -> Tok: tp = TP_CENTER # Default punctuation type if normalized is None: if isinstance(t, str): normalized = t else: normalized = t.txt if normalized and len(normalized) == 1: if normalized in LEFT_PUNCTUATION: tp = TP_LEFT elif normalized in RIGHT_PUNCTUATION: tp = TP_RIGHT elif normalized in NONE_PUNCTUATION: tp = TP_NONE if isinstance(t, str): return Tok(TOK.PUNCTUATION, t, (tp, normalized)) t.kind = TOK.PUNCTUATION t.val = (tp, normalized) return t @staticmethod def Time(t: Union[Tok, str], h: int, m: int, s: int) -> Tok: if isinstance(t, str): return Tok(TOK.TIME, t, (h, m, s)) t.kind = TOK.TIME t.val = (h, m, s) return t @staticmethod def Date(t: Union[Tok, str], y: int, m: int, d: int) -> Tok: if isinstance(t, str): return Tok(TOK.DATE, t, (y, m, d)) t.kind = TOK.DATE t.val = (y, m, d) return t @staticmethod def Dateabs(t: Union[Tok, str], y: int, m: int, d: int) -> Tok: if isinstance(t, str): return Tok(TOK.DATEABS, t, (y, m, d)) t.kind = TOK.DATEABS t.val = (y, m, d) return t @staticmethod def Daterel(t: Union[Tok, str], y: int, m: int, d: int) -> Tok: if isinstance(t, str): return Tok(TOK.DATEREL, t, (y, m, d)) t.kind = TOK.DATEREL t.val = (y, m, d) return t @staticmethod def Timestamp( t: Union[Tok, str], y: int, mo: int, d: int, h: int, m: int, s: int ) -> Tok: if isinstance(t, str): return Tok(TOK.TIMESTAMP, t, (y, mo, d, h, m, s)) t.kind = TOK.TIMESTAMP t.val = (y, mo, d, h, m, s) return t @staticmethod def Timestampabs( t: Union[Tok, str], y: int, mo: int, d: int, h: int, m: int, s: int ) -> Tok: if isinstance(t, str): return Tok(TOK.TIMESTAMPABS, t, (y, mo, d, h, m, s)) t.kind = TOK.TIMESTAMPABS t.val = (y, mo, d, h, m, s) return t @staticmethod def Timestamprel( t: Union[Tok, str], y: int, mo: int, d: int, h: int, m: int, s: int ) -> Tok: if isinstance(t, str): return Tok(TOK.TIMESTAMPREL, t, (y, mo, d, h, m, s)) t.kind = TOK.TIMESTAMPREL t.val = (y, mo, d, h, m, s) return t @staticmethod def Year(t: Union[Tok, str], n: int) -> Tok: if isinstance(t, str): return Tok(TOK.YEAR, t, n) t.kind = TOK.YEAR t.val = n return t @staticmethod def Telno(t: Union[Tok, str], telno: str, cc: str = "354") -> Tok: # The t parameter is the original token text, # while telno has the standard form 'DDD-DDDD' (with hyphen) # cc is the country code if isinstance(t, str): return Tok(TOK.TELNO, t, (telno, cc)) t.kind = TOK.TELNO t.val = (telno, cc) return t @staticmethod def Email(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.EMAIL, t, None) t.kind = TOK.EMAIL t.val = None return t @staticmethod def Number( t: Union[Tok, str], n: float, cases: Optional[List[str]] = None, genders: Optional[List[str]] = None, ) -> Tok: # The cases parameter is a list of possible cases for this number # (if it was originally stated in words) if isinstance(t, str): return Tok(TOK.NUMBER, t, (n, cases, genders)) t.kind = TOK.NUMBER t.val = (n, cases, genders) return t @staticmethod def NumberWithLetter(t: Union[Tok, str], n: int, c: str) -> Tok: if isinstance(t, str): return Tok(TOK.NUMWLETTER, t, (n, c)) t.kind = TOK.NUMWLETTER t.val = (n, c) return t @staticmethod def Currency( t: Union[Tok, str], iso: str, cases: Optional[List[str]] = None, genders: Optional[List[str]] = None, ) -> Tok: # The cases parameter is a list of possible cases for this currency name # (if it was originally stated in words, i.e. not abbreviated) if isinstance(t, str): return Tok(TOK.CURRENCY, t, (iso, cases, genders)) t.kind = TOK.CURRENCY t.val = (iso, cases, genders) return t @staticmethod def Amount( t: Union[Tok, str], iso: str, n: float, cases: Optional[List[str]] = None, genders: Optional[List[str]] = None, ) -> Tok: # The cases parameter is a list of possible cases for this amount # (if it was originally stated in words) if isinstance(t, str): return Tok(TOK.AMOUNT, t, (n, iso, cases, genders)) t.kind = TOK.AMOUNT t.val = (n, iso, cases, genders) return t @staticmethod def Percent( t: Union[Tok, str], n: float, cases: Optional[List[str]] = None, genders: Optional[List[str]] = None, ) -> Tok: if isinstance(t, str): return Tok(TOK.PERCENT, t, (n, cases, genders)) t.kind = TOK.PERCENT t.val = (n, cases, genders) return t @staticmethod def Ordinal(t: Union[Tok, str], n: int) -> Tok: if isinstance(t, str): return Tok(TOK.ORDINAL, t, n) t.kind = TOK.ORDINAL t.val = n return t @staticmethod def Url(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.URL, t, None) t.kind = TOK.URL t.val = None return t @staticmethod def Domain(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.DOMAIN, t, None) t.kind = TOK.DOMAIN t.val = None return t @staticmethod def Hashtag(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.HASHTAG, t, None) t.kind = TOK.HASHTAG t.val = None return t @staticmethod def Ssn(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.SSN, t, None) t.kind = TOK.SSN t.val = None return t @staticmethod def Molecule(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.MOLECULE, t, None) t.kind = TOK.MOLECULE t.val = None return t @staticmethod def Username(t: Union[Tok, str], username: str) -> Tok: if isinstance(t, str): return Tok(TOK.USERNAME, t, username) t.kind = TOK.USERNAME t.val = username return t @staticmethod def SerialNumber(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.SERIALNUMBER, t, None) t.kind = TOK.SERIALNUMBER t.val = None return t @staticmethod def Measurement(t: Union[Tok, str], unit: str, val: float) -> Tok: if isinstance(t, str): return Tok(TOK.MEASUREMENT, t, (unit, val)) t.kind = TOK.MEASUREMENT t.val = (unit, val) return t @staticmethod def Word(t: Union[Tok, str], m: Optional[BIN_TupleList] = None) -> Tok: # The m parameter is intended for a list of BIN_Tuple instances # fetched from the BÍN database, in 'SHsnid' format if isinstance(t, str): return Tok(TOK.WORD, t, m) t.kind = TOK.WORD t.val = m return t @staticmethod def Unknown(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.UNKNOWN, t, None) t.kind = TOK.UNKNOWN t.val = None return t @staticmethod def Person(t: Union[Tok, str], m: Optional[PersonNameList] = None) -> Tok: # The m parameter is intended for a list of PersonName tuples: # (name, gender, case) if isinstance(t, str): return Tok(TOK.PERSON, t, m) t.kind = TOK.PERSON t.val = m return t @staticmethod def Entity(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.ENTITY, t, None) t.kind = TOK.ENTITY t.val = None return t @staticmethod def Company(t: Union[Tok, str]) -> Tok: if isinstance(t, str): return Tok(TOK.COMPANY, t, None) t.kind = TOK.COMPANY t.val = None return t @staticmethod def Begin_Paragraph() -> Tok: """Return a special paragraph begin marker token""" marker = Tok(TOK.P_BEGIN, "[[", None, "[[", list(range(2))) marker.substitute((0, 2), "") return marker @staticmethod def End_Paragraph() -> Tok: """Return a special paragraph end marker token""" marker = Tok(TOK.P_END, "]]", None, "]]", list(range(2))) marker.substitute((0, 2), "") return marker @staticmethod def Begin_Sentence( t: Optional[Tok] = None, num_parses: int = 0, err_index: Optional[int] = None, ) -> Tok: if t is None: return Tok(TOK.S_BEGIN, None, (num_parses, err_index)) t.kind = TOK.S_BEGIN t.val = (num_parses, err_index) return t @staticmethod def End_Sentence(t: Optional[Tok] = None) -> Tok: if t is None: return Tok(TOK.S_END, None, None) t.kind = TOK.S_END t.val = None return t @staticmethod def End_Sentinel(t: Optional[Tok] = None) -> Tok: if t is None: return Tok(TOK.X_END, None, None) t.kind = TOK.X_END t.val = None return t @staticmethod def Split_Sentence(t: Optional[Tok] = None) -> Tok: if t is None: return Tok(TOK.S_SPLIT, None, None) t.kind = TOK.S_SPLIT t.val = None return t class TokenStream: """Wrapper for token iterator allowing lookahead.""" def __init__(self, token_it: Iterator[Tok], *, lookahead_size: int = 2): """Initialize from token iterator.""" self.__it: Iterator[Tok] = token_it if lookahead_size <= 0: lookahead_size = 1 self.__lookahead: Deque[Tok] = deque(maxlen=lookahead_size) self.__max_lookahead: int = lookahead_size def __next__(self) -> Tok: if self.__lookahead: return self.__lookahead.popleft() return next(self.__it) def __iter__(self): return self def __getitem__(self, i: int) -> Optional[Tok]: if 0 <= i < self.__max_lookahead: l = len(self.__lookahead) try: while l <= i: # Extend deque to lookahead self.__lookahead.append(next(self.__it)) l += 1 return self.__lookahead[i] except StopIteration: pass return None def txt(self, i: int = 0) -> Optional[str]: """Return token.txt for token at index i.""" t = self[i] return t.txt if t else None def kind(self, i: int = 0) -> Optional[int]: """Return token.kind for token at index i.""" t = self[i] return t.kind if t else None def punctuation(self, i: int = 0) -> Optional[str]: """Return token.punctuation for token at index i.""" t = self[i] return t.punctuation if t else None def number(self, i: int = 0) -> Optional[float]: """Return token.number for token at index i.""" t = self[i] return t.number if t else None def integer(self, i: int = 0) -> Optional[int]: """Return token.integer for token at index i.""" t = self[i] return t.integer if t else None def ordinal(self, i: int = 0) -> Optional[int]: """Return token.ordinal for token at index i.""" t = self[i] return t.ordinal if t else None def has_meanings(self, i: int = 0) -> Optional[bool]: """Return token.has_meanings for token at index i.""" t = self[i] return t.has_meanings if t else None def meanings(self, i: int = 0) -> Optional[BIN_TupleList]: """Return token.meanings for token at index i.""" t = self[i] return t.meanings if t else None def person_names(self, i: int = 0) -> Optional[PersonNameList]: """Return token.person_names for token at index i.""" t = self[i] return t.person_names if t else None def as_tuple(self, i: int = 0) -> Optional[Tuple[Any, ...]]: """Return token.as_tuple for token at index i.""" t = self[i] return t.as_tuple if t else None def could_be_end_of_sentence(self, i: int = 0, *args: Any) -> bool: """Wrapper to safely check if token at index i could be end of sentence.""" t = self[i] return could_be_end_of_sentence(t, *args) if t else False def normalized_text(token: Tok) -> str: """Returns token text after normalizing punctuation""" return ( cast(Tuple[int, str], token.val)[1] if token.kind == TOK.PUNCTUATION else token.txt ) def text_from_tokens(tokens: Iterable[Tok]) -> str: """Return text from a list of tokens, without normalization""" return " ".join(t.txt for t in tokens if t.txt) def normalized_text_from_tokens(tokens: Iterable[Tok]) -> str: """Return text from a list of tokens, with normalization""" return " ".join(filter(None, map(normalized_text, tokens))) def is_valid_date(y: int, m: int, d: int) -> bool: """Returns True if y, m, d is a valid date""" if (1776 <= y <= 2100) and (1 <= m <= 12) and (1 <= d <= DAYS_IN_MONTH[m]): try: datetime.datetime(year=y, month=m, day=d) return True except ValueError: pass return False def parse_digits(tok: Tok, convert_numbers: bool) -> Tuple[Tok, Tok]: """Parse a raw token starting with a digit""" w = tok.txt s: Optional[Match[str]] = re.match(r"\d{1,2}:\d\d:\d\d,\d\d(?!\d)", w) g: str n: str if s: # Looks like a 24-hour clock with milliseconds, H:M:S:MS # TODO use millisecond information in token g = s.group() p = g.split(":") h = int(p[0]) m = int(p[1]) sec = int(p[2].split(",")[0]) if (0 <= h < 24) and (0 <= m < 60) and (0 <= sec < 60): t, rest = tok.split(s.end()) return TOK.Time(t, h, m, sec), rest s = re.match(r"\d{1,2}:\d\d:\d\d(?!\d)", w) if s: # Looks like a 24-hour clock, H:M:S g = s.group() p = g.split(":") h = int(p[0]) m = int(p[1]) sec = int(p[2]) if (0 <= h < 24) and (0 <= m < 60) and (0 <= sec < 60): t, rest = tok.split(s.end()) return TOK.Time(t, h, m, sec), rest s = re.match(r"\d{1,2}:\d\d(?!\d)", w) if s: # Looks like a 24-hour clock, H:M g = s.group() p = g.split(":") h = int(p[0]) m = int(p[1]) if (0 <= h < 24) and (0 <= m < 60): t, rest = tok.split(s.end()) return TOK.Time(t, h, m, 0), rest s = re.match(r"((\d{4}-\d\d-\d\d)|(\d{4}/\d\d/\d\d))(?!\d)", w) if s: # Looks like an ISO format date: YYYY-MM-DD or YYYY/MM/DD g = s.group() if "-" in g: p = g.split("-") else: p = g.split("/") y = int(p[0]) m = int(p[1]) d = int(p[2]) if is_valid_date(y, m, d): t, rest = tok.split(s.end()) return TOK.Date(t, y, m, d), rest s = ( re.match(r"\d{1,2}\.\d{1,2}\.\d{2,4}(?!\d)", w) or re.match(r"\d{1,2}/\d{1,2}/\d{2,4}(?!\d)", w) or re.match(r"\d{1,2}-\d{1,2}-\d{2,4}(?!\d)", w) ) if s: # Looks like a date with day, month and year parts g = s.group() if "/" in g: p = g.split("/") elif "-" in g: p = g.split("-") else: p = g.split(".") y = int(p[2]) if y <= 99: # 50 means 2050, but 51 means 1951 y += 1900 if y > 50 else 2000 m = int(p[1]) d = int(p[0]) if m > 12 >= d: # Probably wrong way (i.e. U.S. American way) around m, d = d, m if is_valid_date(y, m, d): t, rest = tok.split(s.end()) return TOK.Date(t, y, m, d), rest s = re.match(r"(\d{2})\.(\d{2})(?!\d)", w) if s: # A date in the form dd.mm # (Allowing hyphens here would interfere with for instance # sports scores and phrases such as 'Það voru 10-12 manns þarna.') g = s.group() d = int(s.group(1)) m = int(s.group(2)) if (1 <= m <= 12) and (1 <= d <= DAYS_IN_MONTH[m]): t, rest = tok.split(s.end()) return TOK.Daterel(t, y=0, m=m, d=d), rest s = re.match(r"(\d{2})[-.](\d{4})(?!\d)", w) if s: # A date in the form of mm.yyyy or mm-yyyy g = s.group() m = int(s.group(1)) y = int(s.group(2)) if (1776 <= y <= 2100) and (1 <= m <= 12): t, rest = tok.split(s.end()) return TOK.Daterel(t, y=y, m=m, d=0), rest # Note: the following must use re.UNICODE to make sure that # \w matches all Icelandic characters under Python 2 s = re.match(r"\d+([a-zA-Z])(?!\w)", w, re.UNICODE) if s: # Looks like a number with a single trailing character, e.g. 14b, 33C, 1122f g = s.group() c = g[-1:] # Only match if the single character is not a # unit of measurement (e.g. 'A', 'l', 'V') if c not in SI_UNITS_SET: nw = int(g[:-1]) t, rest = tok.split(s.end()) return TOK.NumberWithLetter(t, nw, c), rest s = NUM_WITH_UNIT_REGEX1.match(w) if s: # Icelandic-style number followed by an SI unit, or degree/percentage, # or currency symbol g = s.group() val = float(s.group(1).replace(".", "").replace(",", ".")) unit = s.group(4) if unit in CURRENCY_SYMBOLS: # This is an amount with a currency symbol at the end iso = CURRENCY_SYMBOLS[unit] t, rest = tok.split(s.end()) return TOK.Amount(t, iso, val), rest unit, factor = SI_UNITS[unit] if callable(factor): val = factor(val) else: # Simple scaling factor val *= factor if unit in ("%", "‰"): t, rest = tok.split(s.end()) return TOK.Percent(t, val), rest t, rest = tok.split(s.end()) return TOK.Measurement(t, unit, val), rest s = NUM_WITH_UNIT_REGEX2.match(w) if s: # English-style number followed by an SI unit, or degree/percentage, # or currency symbol g = s.group() val = float(s.group(1).replace(",", "")) unit = s.group(4) if unit in CURRENCY_SYMBOLS: # This is an amount with a currency symbol at the end iso = CURRENCY_SYMBOLS[unit] t, rest = tok.split(s.end()) return TOK.Amount(t, iso, val), rest unit, factor = SI_UNITS[unit] if callable(factor): val = factor(val) else: # Simple scaling factor val *= factor t, rest = tok.split(s.end()) if convert_numbers: t.substitute_all(",", "x") # Change thousands separator to 'x' t.substitute_all(".", ",") # Change decimal separator to ',' t.substitute_all("x", ".") # Change 'x' to '.' if unit in ("%", "‰"): return TOK.Percent(t, val), rest return TOK.Measurement(t, unit, val), rest s = NUM_WITH_UNIT_REGEX3.match(w) if s: # One or more digits, followed by a unicode # vulgar fraction char (e.g. '2½') and an SI unit, # percent/promille, or currency code g = s.group() ln = s.group(1) vf = s.group(2) orig_unit = s.group(3) value = float(ln) + unicodedata.numeric(vf) if orig_unit in CURRENCY_SYMBOLS: # This is an amount with a currency symbol at the end iso = CURRENCY_SYMBOLS[orig_unit] t, rest = tok.split(s.end()) return TOK.Amount(t, iso, value), rest unit, factor = SI_UNITS[orig_unit] if callable(factor): value = factor(value) else: # Simple scaling factor value *= factor if unit in ("%", "‰"): t, rest = tok.split(s.end()) return TOK.Percent(t, value), rest t, rest = tok.split(s.end()) return TOK.Measurement(t, unit, value), rest s = re.match(r"(\d+)([\u00BC-\u00BE\u2150-\u215E])", w, re.UNICODE) if s: # One or more digits, followed by a unicode vulgar fraction char (e.g. '2½') g = s.group() ln = s.group(1) vf = s.group(2) val = float(ln) + unicodedata.numeric(vf) t, rest = tok.split(s.end()) return TOK.Number(t, val), rest # Can't end with digits.digits s = re.match(r"[\+\-]?\d+(\.\d\d\d)*,\d+(?!\d*\.\d)", w) if s: # Icelandic-style real number formatted with decimal comma (,) # and possibly thousands separators (.) # (we need to check this before checking integers) g = s.group() if re.match(r",\d+", w[len(g) :]): # English-style thousand separator multiple times s = None else: n = re.sub(r"\.", "", g) # Eliminate thousands separators n = re.sub(",", ".", n) # Convert decimal comma to point t, rest = tok.split(s.end()) return TOK.Number(t, float(n)), rest s = re.match(r"[\+\-]?\d+(\.\d\d\d)+(?!\d)", w) if s: # Integer with a '.' thousands separator # (we need to check this before checking dd.mm dates) g = s.group() n = re.sub(r"\.", "", g) # Eliminate thousands separators t, rest = tok.split(s.end()) return TOK.Number(t, int(n)), rest s = re.match(r"\d{1,2}/\d{1,2}(?!\d)", w) if s: # Looks like a date (and not something like 10/2007) g = s.group() p = g.split("/") m = int(p[1]) d = int(p[0]) if ( p[0][0] != "0" and p[1][0] != "0" and ((d <= 5 and m <= 6) or (d == 1 and m <= 10)) ): # This is probably a fraction, not a date # (1/2, 1/3, 1/4, 1/5, 1/6, 2/3, 2/5, 5/6 etc.) # Return a number t, rest = tok.split(s.end()) return TOK.Number(t, float(d) / m), rest if m > 12 >= d: # Date is probably wrong way around m, d = d, m if (1 <= m <= 12) and (1 <= d <= DAYS_IN_MONTH[m]): # Looks like a (roughly) valid date t, rest = tok.split(s.end()) return TOK.Daterel(t, y=0, m=m, d=d), rest s = re.match(r"\d\d\d\d(?!\d)", w) if s: nn = int(s.group()) if 1776 <= nn <= 2100: # Looks like a year t, rest = tok.split(4) return TOK.Year(t, nn), rest s = re.match(r"\d{6}\-\d{4}(?!\d)", w) if s: # Looks like a social security number g = s.group() if valid_ssn(g): t, rest = tok.split(11) return TOK.Ssn(t), rest s = re.match(r"\d\d\d\-\d\d\d\d(?!\d)", w) if s and w[0] in TELNO_PREFIXES: # Looks like a telephone number telno = s.group() t, rest = tok.split(8) return TOK.Telno(t, telno), rest if s: # Most likely some sort of serial number # Unknown token for now, don't want it separated t, rest = tok.split(s.end()) return TOK.SerialNumber(t), rest s = re.match(r"\d+\-\d+(\-\d+)+", w) if s: # Multi-component serial number t, rest = tok.split(s.end()) return TOK.SerialNumber(t), rest s = re.match(r"\d\d\d\d\d\d\d(?!\d)", w) if s and w[0] in TELNO_PREFIXES: # Looks like a telephone number telno = w[0:3] + "-" + w[3:7] t, rest = tok.split(7) return TOK.Telno(t, telno), rest s = re.match(r"\d+\.\d+(\.\d+)+", w) if s: # Some kind of ordinal chapter number: 2.5.1 etc. # (we need to check this before numbers with decimal points) g = s.group() # !!! TODO: A better solution would be to convert 2.5.1 to (2,5,1) n = re.sub(r"\.", "", g) # Eliminate dots, 2.5.1 -> 251 t, rest = tok.split(s.end()) return TOK.Ordinal(t, int(n)), rest s = re.match(r"[\+\-]?\d+(,\d\d\d)*\.\d+", w) if s: # English-style real number with a decimal point (.), # and possibly commas as thousands separators (,) g = s.group() n = re.sub(",", "", g) # Eliminate thousands separators # !!! TODO: May want to mark this as an error t, rest = tok.split(s.end()) if convert_numbers: t.substitute_all(",", "x") # Change thousands separator to 'x' t.substitute_all(".", ",") # Change decimal separator to ',' t.substitute_all("x", ".") # Change 'x' to '.' return TOK.Number(t, float(n)), rest s = re.match(r"[\+\-]?\d+(,\d\d\d)*(?!\d)", w) if s: # Integer, possibly with a ',' thousands separator g = s.group() n = re.sub(",", "", g) # Eliminate thousands separators # !!! TODO: May want to mark this as an error t, rest = tok.split(s.end()) if convert_numbers: # Change thousands separator to a dot t.substitute_all(",", ".") return TOK.Number(t, int(n)), rest # Strange thing # !!! TODO: May want to mark this as an error # !!! TODO: is this the correct thing for the rest token? return ( TOK.Unknown(tok), Tok(TOK.RAW, "", None, "", []), ) def html_escape(match: Match[str]) -> Tuple[Tuple[int, int], str]: """Regex substitution function for HTML escape codes""" g = match.group(4) if g is not None: # HTML escape string: 'acute' return match.span(), HTML_ESCAPES[g] g = match.group(2) if g is not None: # Hex code: '#xABCD' return match.span(), chr(int(g[2:], base=16)) g = match.group(3) assert g is not None # Decimal code: '#8930' return match.span(), chr(int(g[1:])) def unicode_replacement(token: Tok) -> Tok: """Replace some composite glyphs with single code points""" total_reduction = 0 for m in UNICODE_REGEX.finditer(token.txt): span, new_letter = m.span(), UNICODE_REPLACEMENTS[m.group(0)] token.substitute( (span[0] - total_reduction, span[1] - total_reduction), new_letter ) total_reduction += span[1] - span[0] - len(new_letter) return token def html_replacement(token: Tok) -> Tok: """Replace html escape sequences with their proper characters""" total_reduction = 0 for m in HTML_ESCAPE_REGEX.finditer(token.txt): span, new_letter = html_escape(m) token.substitute( (span[0] - total_reduction, span[1] - total_reduction), new_letter ) total_reduction += span[1] - span[0] - len(new_letter) return token def generate_rough_tokens_from_txt(text: str) -> Iterator[Tok]: """Generate rough tokens from a string.""" # Rough tokens are tokens that are separated by white space, i.e. the regex (\\s*).""" # pos tracks the index in the text we have covered so far. # We want to track pos, instead of treating text as a buffer, # since that would lead to a lot of unnecessary copying. pos = 0 while pos < len(text): match = ROUGH_TOKEN_REGEX.match(text, pos) assert match is not None match_span = match.span(ROUGH_TOKEN_REGEX_ENTIRE_MATCH) tok = Tok.from_txt(text[match_span[SPAN_START] : match_span[SPAN_END]]) pos = match_span[SPAN_END] yield tok def generate_rough_tokens_from_tok(tok: Tok) -> Iterator[Tok]: """Generate rough tokens from a token.""" # Some tokens might have whitespace characters after we replace composite unicode glyphs # and replace HTML escapes. # This function further splits those tokens into multiple tokens. # Rough tokens are tokens that are separated by white space, i.e. the regex (\\s*).""" def shift_span(span: Tuple[int, int], pos: int): """Shift a span by a given amount""" return (span[SPAN_START] + pos, span[SPAN_END] + pos) text = tok.txt # pos tracks the index in the text we have covered so far. # We want to track pos, instead of treating text as a buffer, # since that would lead to a lot of unnecessary copying. pos = 0 while pos < len(text): match = ROUGH_TOKEN_REGEX.match(text, pos) assert match is not None # Since the match indexes the text of the original token, # we need to shift the indices so that they match the current token. shifted_all_group_span = shift_span( match.span(ROUGH_TOKEN_REGEX_ENTIRE_MATCH), -pos ) shifted_white_space_span = shift_span( match.span(ROUGH_TOKEN_REGEX_WHITE_SPACE_GROUP), -pos ) # Then we split the current token using the shifted spans small_tok, tok = tok.split(shifted_all_group_span[SPAN_END]) # Remove whitespace characters from the start of the token small_tok.substitute(shifted_white_space_span, "") # The pos is not shifted pos = match.span(ROUGH_TOKEN_REGEX_ENTIRE_MATCH)[SPAN_END] yield small_tok def generate_raw_tokens( text_or_gen: Union[str, Iterable[str]], replace_composite_glyphs: bool = True, replace_html_escapes: bool = False, one_sent_per_line: bool = False, ) -> Iterator[Tok]: """Generate raw tokens from a string or an iterable that contains strings""" if isinstance(text_or_gen, str): if not text_or_gen: # Empty string: yield nothing return # The parameter is a single string: wrap it in an iterable text_or_gen = [text_or_gen] # Iterate through text_or_gen, which is assumed to yield strings saved: Optional[Tok] = None # The following declaration seems to be required for Pylance big_text: str for big_text in text_or_gen: if not one_sent_per_line and not big_text: # An explicit empty string in the input always # causes a sentence split yield TOK.Split_Sentence(saved) saved = None continue if saved is not None: # The following strange code satisfies Pylance so: Optional[str] = saved.original big_text = (so or "") + big_text saved = None # Force sentence splits # Case 1: Two newlines with only whitespace between appear anywhere in 'big_text'. # I.e. force sentence split when we see an empty line. # Case 2: 'big_txt' contains only whitespace. # This only means "empty line" if each element in text_or_gen is assumed to # be a line (even if they don't contain any newline characters). # That does not strictly have to be true and is not a declared assumption, # except in tests, but the tokenizer has had this behavior for a long time. if one_sent_per_line: # We know there's a single sentence per line # Only split on newline sentence_split_pattern = r"(\n)" else: # Split on empty lines, eventually containing whitespace, # but also on paragraph splits within a line sentence_split_pattern = r"(\n\s*\n|^\s+$|\]\]\[\[)" splits = re.split(sentence_split_pattern, big_text) # We know that splits will contain alternatively useful text and the splitting # pattern, starting and ending with useful text. See the documentation on # re.split. is_text = True for text in splits: if is_text: # 'text' is text to be tokenized paragraph_end = 0 if not one_sent_per_line: # Convert paragraph separators to TOK.P_BEGIN and TOK.P_END tokens while text.startswith("[["): # Begin paragraph text = text[2:] yield TOK.Begin_Paragraph() while text.endswith("]]"): # End paragraph text = text[:-2] # Postpone the yield until after the raw token loop paragraph_end += 1 for tok in generate_rough_tokens_from_txt(text): if replace_composite_glyphs: # Replace composite glyphs with single code points tok = unicode_replacement(tok) if replace_html_escapes: # Replace HTML escapes: '&aacute;' -> 'á' tok = html_replacement(tok) # The HTML escapes and unicode possibly contain whitespace characters # e.g. Em space '&#8195;' and non-breaking space '&nbsp;' # Here we split those tokens into multiple tokens. for small_tok in generate_rough_tokens_from_tok(tok): if small_tok.txt == "": # There was whitespace at the end of the last token. # We do not want to yield a token with empty text if possible. # We want to attach it in front of the next token, if there is one. # If there is no next token, we attach it in front of the next 'big_text'. # This will happen when: # 1. When 'text' has whitespace at the end # 2. When we have replaced a composite glyph or an HTML escape with whitespace. # See ROUGH_TOKEN_REGEX to convince yourself this is true. saved = small_tok else: if saved is not None: # Attach the saved token in front of the current token small_tok = saved.concatenate(small_tok) saved = None yield small_tok while paragraph_end: # Yield the postponed TOK.P_END token yield TOK.End_Paragraph() paragraph_end -= 1 elif text == "]][[": # Paragraph split: Yield TOK.P_BEGIN and TOK.P_END tokens yield TOK.End_Paragraph() yield TOK.Begin_Paragraph() else: # Sentence split: 'text' is the split pattern tok_split = Tok.from_txt(text) # This token should have no output text, but we still want to preserve # the original text. tok_split.substitute((0, len(text)), "") yield TOK.Split_Sentence(tok_split) is_text = not is_text if saved is not None: # There is trailing whitespace at the end of everything. # The only option to conserve this is to emit a token with empty text. # Set the type to S_SPLIT to get proper sentence detection in later phases. yield TOK.Split_Sentence(saved) def could_be_end_of_sentence( next_token: Tok, test_set: FrozenSet[int] = TOK.TEXT, multiplier: bool = False, ) -> bool: """Return True if next_token could be ending the current sentence or starting the next one""" return next_token.kind in TOK.END or ( # Check whether the next token is an uppercase word, except if # it is a month name (frequently misspelled in uppercase) or # roman numeral, or a currency abbreviation if preceded by a # multiplier (for example þ. USD for thousands of USD) next_token.kind in test_set and next_token.txt[0].isupper() and next_token.txt.lower() not in MONTHS and not RE_ROMAN_NUMERAL.match(next_token.txt) and not (next_token.txt in CURRENCY_ABBREV and multiplier) ) class LetterParser: """Parses a sequence of alphabetic characters off the front of a raw token""" def __init__(self, rt: Tok) -> None: self.rt = rt def parse(self) -> Iterable[Tok]: """Parse the raw token, yielding result tokens""" rt = self.rt lw = len(rt.txt) i = 1 while i < lw and ( rt.txt[i].isalpha() or ( rt.txt[i] in PUNCT_INSIDE_WORD and i + 1 < lw and rt.txt[i + 1].isalpha() ) ): # We allow dots to occur inside words in the case of # abbreviations; also apostrophes are allowed within # words and at the end (albeit not consecutively) # (O'Malley, Mary's, it's, childrens', O‘Donnell). # The same goes for ² and ³ i += 1 if i < lw and rt.txt[i] in PUNCT_ENDING_WORD: i += 1 # Make a special check for the occasional erroneous source text # case where sentences run together over a period without a space: # 'sjávarútvegi.Það' # TODO STILLING Viljum merkja sem villu fyrir málrýni, og hafa # sem mögulega stillingu. ww: str = rt.txt[0:i] a = ww.split(".") if ( len(a) == 2 # First part must be more than one letter for us to split and len(a[0]) > 1 # The first part may start with an uppercase or lowercase letter # but the rest of it must be lowercase and a[0][1:].islower() and a[1] # The second part must start with an uppercase letter and a[1][0].isupper() # Corner case: an abbrev such as 'f.Kr' should not be split and rt.txt[0 : i + 1] not in Abbreviations.DICT ): # We have a lowercase word immediately followed by a period # and an uppercase word word1, rt = rt.split(len(a[0])) punct, rt = rt.split(1) word2, rt = rt.split(len(a[1])) yield TOK.Word(word1) yield TOK.Punctuation(punct) yield TOK.Word(word2) elif ww.endswith("-og") or ww.endswith("-eða"): # Handle missing space before 'og'/'eða', # such as 'fjármála-og efnahagsráðuneyti' a = ww.split("-") word1, rt = rt.split(len(a[0])) punct, rt = rt.split(1) word2, rt = rt.split(len(a[1])) yield TOK.Word(word1) yield TOK.Punctuation(punct, normalized=COMPOSITE_HYPHEN) yield TOK.Word(word2) else: word, rt = rt.split(i) yield TOK.Word(word) if rt.txt and rt.txt[0] in COMPOSITE_HYPHENS: # This is a hyphen or en dash directly appended to a word: # might be a continuation ('fjármála- og efnahagsráðuneyti') # Yield a special hyphen as a marker punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized=COMPOSITE_HYPHEN) self.rt = rt class NumberParser: """Parses a sequence of digits off the front of a raw token""" def __init__( self, rt: Tok, handle_kludgy_ordinals: int, convert_numbers: bool ) -> None: self.rt = rt self.handle_kludgy_ordinals = handle_kludgy_ordinals self.convert_numbers = convert_numbers def parse(self) -> Iterable[Tok]: """Parse the raw token, yielding result tokens""" # Handle kludgy ordinals: '3ji', '5ti', etc. rt = self.rt handle_kludgy_ordinals = self.handle_kludgy_ordinals convert_numbers = self.convert_numbers for key, val in ORDINAL_ERRORS.items(): rtxt = rt.txt if rtxt.startswith(key): # This is a kludgy ordinal key_tok, rt = rt.split(len(key)) if handle_kludgy_ordinals == KLUDGY_ORDINALS_MODIFY: # Convert ordinals to corresponding word tokens: # '1sti' -> 'fyrsti', '3ji' -> 'þriðji', etc. key_tok.substitute_longer((0, len(key)), val) yield TOK.Word(key_tok) elif ( handle_kludgy_ordinals == KLUDGY_ORDINALS_TRANSLATE and key in ORDINAL_NUMBERS ): # Convert word-form ordinals into ordinal tokens, # i.e. '1sti' -> TOK.Ordinal('1sti', 1), # but leave other kludgy constructs ('2ja') # as word tokens yield TOK.Ordinal(key_tok, ORDINAL_NUMBERS[key]) else: # No special handling of kludgy ordinals: # yield them unchanged as word tokens yield TOK.Word(key_tok) break # This skips the for loop 'else' else: # Not a kludgy ordinal: eat tokens starting with a digit t, rt = parse_digits(rt, convert_numbers) yield t # Continue where the digits parser left off if rt.txt: # Check for an SI unit immediately following a number r = SI_UNITS_REGEX.match(rt.txt) if r: # Handle the case where a measurement unit is # immediately following a number, without an intervening space # (note that some of them contain nonalphabetic characters, # so they won't be caught by the isalpha() check below) unit, rt = rt.split(r.end()) yield TOK.Word(unit) self.rt = rt class PunctuationParser: """Parses a sequence of punctuation off the front of a raw token""" def __init__(self) -> None: self.rt = cast(Tok, None) self.ate = False def parse(self, rt: Tok) -> Iterable[Tok]: """Parse the raw token, yielding result tokens""" ate = False while rt.txt and rt.txt[0] in PUNCTUATION: ate = True rtxt = rt.txt lw = len(rtxt) if rtxt.startswith("[...]"): punct, rt = rt.split(5) yield TOK.Punctuation(punct, normalized="[…]") elif rtxt.startswith("[…]"): punct, rt = rt.split(3) yield TOK.Punctuation(punct) elif rtxt.startswith("...") or rtxt.startswith("…"): # Treat >= 3 periods as ellipsis, one piece of punctuation numdots = 0 for c in rtxt: if c == "." or c == "…": numdots += 1 else: break dots, rt = rt.split(numdots) yield TOK.Punctuation(dots, normalized="…") elif rtxt.startswith(".."): # Normalize two periods to one dots, rt = rt.split(2) yield TOK.Punctuation(dots, normalized=".") elif rtxt.startswith(",,"): if rtxt[2:3].isalnum(): # Probably someone trying to type opening double quotes with commas punct, rt = rt.split(2) yield TOK.Punctuation(punct, normalized="„") else: # Coalesce multiple commas into one normalized comma numcommas = 2 for c in rtxt[2:]: if c == ",": numcommas += 1 else: break punct, rt = rt.split(numcommas) yield TOK.Punctuation(punct, normalized=",") elif rtxt[0] in HYPHENS: # Normalize all hyphens the same way punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized=HYPHEN) elif rtxt[0] in DQUOTES: # Convert to a proper closing double quote punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized="“") elif rtxt[0] in SQUOTES: # Left with a single quote, convert to proper closing quote punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized="‘") elif lw > 1 and rtxt.startswith("#"): # Might be a hashtag, processed later ate = False break elif lw > 1 and rtxt.startswith("@"): # Username on Twitter or other social media platforms # User names may contain alphabetic characters, digits # and embedded periods (but not consecutive ones) s = re.match(r"\@[0-9a-zA-Z_]+(\.[0-9a-zA-Z_]+)*", rtxt) if s: g = s.group() username, rt = rt.split(s.end()) yield TOK.Username(username, g[1:]) else: # Return the @-sign and leave the rest punct, rt = rt.split(1) yield TOK.Punctuation(punct) elif len(rtxt) >= 2 and frozenset(rtxt) <= EXCLAMATIONS: # Possibly '???!!!' or something of the sort numpunct = 2 for p in rtxt[2:]: if p in EXCLAMATIONS: numpunct += 1 else: break punct, rt = rt.split(numpunct) yield TOK.Punctuation(punct, normalized=rtxt[0]) else: punct, rt = rt.split(1) yield TOK.Punctuation(punct) # End of punctuation loop self.rt = rt self.ate = ate def parse_mixed( rt: Tok, handle_kludgy_ordinals: int, convert_numbers: bool ) -> Iterable[Tok]: """Parse a mixed raw token string, from the token rt""" # Initialize a singleton parser for punctuation pp = PunctuationParser() while rt.txt: # Handle punctuation yield from pp.parse(rt) rt, ate = pp.rt, pp.ate # Check for specific token types other than punctuation rtxt = rt.txt if rtxt and "@" in rtxt: # Check for valid e-mail # Note: we don't allow double quotes (simple or closing ones) in e-mails here # even though they're technically allowed according to the RFCs s = re.match(r"[^@\s]+@[^@\s]+(\.[^@\s\.,/:;\"\(\)%#!\?”]+)+", rtxt) if s: email, rt = rt.split(s.end()) yield TOK.Email(email) ate = True # Unicode single-char vulgar fractions # TODO: Support multiple-char unicode fractions that # use super/subscript w. DIVISION SLASH (U+2215) if rt.txt and rt.txt[0] in SINGLECHAR_FRACTIONS: num, rt = rt.split(1) yield TOK.Number(num, unicodedata.numeric(num.txt[0])) ate = True rtxt = rt.txt if rtxt and rtxt.startswith(URL_PREFIXES): # Handle URL: cut RIGHT_PUNCTUATION characters off its end, # even though many of them are actually allowed according to # the IETF RFC endp = "" w = rtxt while w and w[-1] in RIGHT_PUNCTUATION: endp = w[-1] + endp w = w[:-1] url, rt = rt.split(len(w)) yield TOK.Url(url) ate = True if rtxt and len(rtxt) >= 2 and re.match(r"#\w", rtxt, re.UNICODE): # Handle hashtags. Eat all text up to next punctuation character # so we can handle strings like "#MeToo-hreyfingin" as two words w = rtxt tag = w[:1] w = w[1:] while w and w[0] not in PUNCTUATION: tag += w[0] w = w[1:] tag_tok, rt = rt.split(len(tag)) if re.match(r"#\d+$", tag): # Hash is being used as a number sign, e.g. "#12" yield TOK.Ordinal(tag_tok, int(tag[1:])) else: yield TOK.Hashtag(tag_tok) ate = True rtxt = rt.txt # Domain name (e.g. greynir.is) if ( rtxt and len(rtxt) >= MIN_DOMAIN_LENGTH and rtxt[0].isalnum() # All domains start with an alphanumeric char and "." in rtxt[1:-2] # Optimization, TLD is at least 2 chars and DOMAIN_REGEX.search(rtxt) ): w = rtxt endp = "" while w and w[-1] in PUNCTUATION: endp = w[-1] + endp w = w[:-1] domain, rt = rt.split(len(w)) yield TOK.Domain(domain) ate = True rtxt = rt.txt # Numbers or other stuff starting with a digit # (eventually prefixed by a '+' or '-') if rtxt and ( rtxt[0] in DIGITS_PREFIX or (rtxt[0] in SIGN_PREFIX and len(rtxt) >= 2 and rtxt[1] in DIGITS_PREFIX) ): np = NumberParser(rt, handle_kludgy_ordinals, convert_numbers) yield from np.parse() rt = np.rt ate = True # Check for molecular formula ('H2SO4') if rt.txt: r = MOLECULE_REGEX.match(rt.txt) if r is not None: g = r.group() if g not in Abbreviations.DICT and MOLECULE_FILTER.search(g): # Correct format, containing at least one digit # and not separately defined as an abbreviation: # We assume that this is a molecular formula molecule, rt = rt.split(r.end()) yield TOK.Molecule(molecule) ate = True # Check for currency abbreviations immediately followed by a number if len(rt.txt) > 3 and rt.txt[0:3] in CURRENCY_ABBREV and rt.txt[3].isdigit(): # XXX: This feels a little hacky temp_tok = Tok(TOK.RAW, rt.txt[3:], None) digit_tok, _ = parse_digits(temp_tok, convert_numbers) if digit_tok.kind == TOK.NUMBER: amount, rt = rt.split(3 + len(digit_tok.txt)) yield TOK.Amount(amount, amount.txt[:3], digit_tok.number) ate = True # Alphabetic characters if rt.txt and rt.txt[0].isalpha(): lp = LetterParser(rt) yield from lp.parse() rt = lp.rt ate = True # Special case for quotes attached on the right hand side to other stuff, # assumed to be closing quotes rather than opening ones if rt.txt: if rt.txt[0] in SQUOTES: punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized="‘") ate = True elif rt.txt[0] in DQUOTES: punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized="“") ate = True if not ate: # Ensure that we eat everything, even unknown stuff unk, rt = rt.split(1) yield TOK.Unknown(unk) def parse_tokens(txt: Union[str, Iterable[str]], **options: Any) -> Iterator[Tok]: """Generator that parses contiguous text into a stream of tokens""" # Obtain individual flags from the options dict convert_numbers: bool = options.get("convert_numbers", False) replace_composite_glyphs: bool = options.get("replace_composite_glyphs", True) replace_html_escapes: bool = options.get("replace_html_escapes", False) one_sent_per_line: bool = options.get("one_sent_per_line", False) # The default behavior for kludgy ordinals is to pass them # through as word tokens handle_kludgy_ordinals: int = options.get( "handle_kludgy_ordinals", KLUDGY_ORDINALS_PASS_THROUGH ) # This code proceeds roughly as follows: # 1) The text is split into raw tokens on whitespace boundaries. # 2) (By far the most common case:) Raw tokens that are purely # alphabetic are yielded as word tokens. # 3) Punctuation from the front of the remaining raw token is identified # and yielded. A special case applies for quotes. # 4) A set of checks is applied to the rest of the raw token, identifying # tokens such as e-mail addresses, domains and @usernames. These can # start with digits, so the checks must occur before step 5. # 5) Tokens starting with a digit (eventually preceded # by a + or - sign) are sent off to a separate function that identifies # integers, real numbers, dates, telephone numbers, etc. via regexes. # 6) After such checks, alphabetic sequences (words) at the start of the # raw token are identified. Such a sequence can, by the way, also # contain embedded apostrophes and hyphens (Dunkin' Donuts, Mary's, # marg-ítrekaðri). # 7) The process is repeated from step 4) until the current raw token is # exhausted. At that point, we obtain the next token and start from 2). rtxt: str = "" for rt in generate_raw_tokens( txt, replace_composite_glyphs, replace_html_escapes, one_sent_per_line ): # rt: raw token if rt.kind in {TOK.S_SPLIT, TOK.P_BEGIN, TOK.P_END}: # Sentence split markers and paragraph separators require # no further processing. Yield them immediately. yield rt continue rtxt = rt.txt if rtxt.isalpha() or rtxt in SI_UNITS: # Shortcut for most common case: pure word yield TOK.Word(rt) continue if len(rtxt) > 1: if rtxt[0] in SIGN_PREFIX and rtxt[1] in DIGITS_PREFIX: # Digit, preceded by sign (+/-): parse as a number # Note that we can't immediately parse a non-signed number # here since kludges such as '3ja' and domain names such as '4chan.com' # need to be handled separately below t, rt = parse_digits(rt, convert_numbers) yield t if not rt.txt: continue elif rtxt[0] in COMPOSITE_HYPHENS and rtxt[1].isalpha(): # This may be something like '-menn' in 'þingkonur og -menn' i = 2 while i < len(rtxt) and rtxt[i].isalpha(): i += 1 # We allow -menn and -MENN, but not -Menn or -mEnn # We don't allow -Á or -Í, i.e. single-letter uppercase combos if rtxt[:i].islower() or (i > 2 and rtxt[:i].isupper()): head, rt = rt.split(i) yield TOK.Word(head) rtxt = rt.txt # Shortcut for quotes around a single word if len(rtxt) >= 3: if rtxt[0] in DQUOTES and rtxt[-1] in DQUOTES: # Convert to matching Icelandic quotes # yield TOK.Punctuation("„") if rtxt[1:-1].isalpha(): first_punct, rt = rt.split(1) word, last_punct = rt.split(-1) yield TOK.Punctuation(first_punct, normalized="„") yield TOK.Word(word) yield TOK.Punctuation(last_punct, normalized="“") continue elif rtxt[0] in SQUOTES and rtxt[-1] in SQUOTES: # Convert to matching Icelandic quotes # yield TOK.Punctuation("‚") if rtxt[1:-1].isalpha(): first_punct, rt = rt.split(1) word, last_punct = rt.split(-1) yield TOK.Punctuation(first_punct, normalized="‚") yield TOK.Word(word) yield TOK.Punctuation(last_punct, normalized="‘") continue # Special case for leading quotes, which are interpreted # as opening quotes if len(rtxt) > 1: if rtxt[0] in DQUOTES: # Convert simple quotes to proper opening quotes punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized="„") elif rt.txt[0] in SQUOTES: # Convert simple quotes to proper opening quotes punct, rt = rt.split(1) yield TOK.Punctuation(punct, normalized="‚") # More complex case of mixed punctuation, letters and numbers yield from parse_mixed(rt, handle_kludgy_ordinals, convert_numbers) # Yield a sentinel token at the end that will be cut off by the final generator yield TOK.End_Sentinel() def parse_particles(token_stream: Iterator[Tok], **options: Any) -> Iterator[Tok]: """Parse a stream of tokens looking for 'particles' (simple token pairs and abbreviations) and making substitutions""" convert_measurements = options.pop("convert_measurements", False) def is_abbr_with_period(txt: str) -> bool: """Return True if the given token text is an abbreviation when followed by a period""" if "." in txt: # There is already a period in it: must be an abbreviation # (this applies for instance to "t.d" but not to "mbl.is") return True if txt in Abbreviations.SINGLES: # The token's literal text is defined as an abbreviation # followed by a single period return True if txt.lower() in Abbreviations.SINGLES: # The token is in upper or mixed case: # We allow it as an abbreviation unless the exact form # (most often uppercase) is an abbreviation that doesn't # require a period (i.e. isn't in SINGLES). # This applies for instance to DR which means # "Danmark's Radio" instead of "doktor" (dr.) return txt not in Abbreviations.DICT return False def lookup(abbrev: str) -> Optional[List[BIN_Tuple]]: """Look up an abbreviation, both in original case and in lower case, and return either None if not found or a meaning list having one entry""" m = Abbreviations.DICT.get(abbrev) if not m: m = Abbreviations.DICT.get(abbrev.lower()) return list(m) if m else None token = cast(Tok, None) try: # Use TokenStream wrapper for this phase (for lookahead) token_stream = TokenStream(token_stream) # Maintain a one-token lookahead token = next(token_stream) while True: next_token = next(token_stream) # Make the lookahead checks we're interested in # Check for currency symbol followed by number, e.g. $10 if ( token.kind == TOK.PUNCTUATION and token.txt in CURRENCY_SYMBOLS and (next_token.kind == TOK.NUMBER or next_token.kind == TOK.YEAR) ): currabbr = CURRENCY_SYMBOLS[token.txt] token = TOK.Amount( token.concatenate(next_token), currabbr, next_token.number ) next_token = next(token_stream) # Special case for a DATEREL token of the form "25.10.", # i.e. with a trailing period: It can end a sentence if token.kind == TOK.DATEREL and "." in token.txt: if ( next_token.txt == "." and not token_stream.could_be_end_of_sentence() ): # This is something like 'Ég fæddist 25.9. í Svarfaðardal.' y, m, d = cast(Tuple[int, int, int], token.val) token = TOK.Daterel(token.concatenate(next_token), y, m, d) next_token = next(token_stream) # Coalesce abbreviations ending with a period into a single # abbreviation token if next_token.punctuation == ".": if ( token.kind == TOK.WORD and token.txt[-1] != "." and is_abbr_with_period(token.txt) ): # Abbreviation ending with period: make a special token for it # and advance the input stream follow_token = next(token_stream) abbrev = token.txt + "." # Check whether we might be at the end of a sentence, i.e. # the following token is an end-of-sentence or end-of-paragraph, # or uppercase (and not a month name misspelled in upper case). if abbrev in Abbreviations.NAME_FINISHERS: # For name finishers (such as 'próf.') we don't consider a # following person name as an indicator of an end-of-sentence # !!! TODO: This does not work as intended because person names # !!! have not been recognized at this phase in the token pipeline. test_set = TOK.TEXT_EXCL_PERSON else: test_set = TOK.TEXT # TODO STILLING í MONTHS eru einhverjar villur eins og "septembers", # þær þarf að vera hægt að sameina í þessa flóknari tóka en viljum # geta merkt það sem villu. Ætti líklega að setja í sérlista, # WRONG_MONTHS, og sérif-lykkju og setja inn villu í tókann. finish = could_be_end_of_sentence( follow_token, test_set, abbrev in NUMBER_ABBREV ) if finish: # Potentially at the end of a sentence if abbrev in Abbreviations.FINISHERS: # We see this as an abbreviation even if the next sentence # seems to be starting just after it. # Yield the abbreviation without a trailing dot, # and then an 'extra' period token to end the current sentence. token = TOK.Word(token, lookup(abbrev)) yield token # Set token to the period token = next_token elif ( abbrev in Abbreviations.NOT_FINISHERS or abbrev.lower() in Abbreviations.NOT_FINISHERS ): # This is a potential abbreviation that we don't interpret # as such if it's at the end of a sentence # ('dags.', 'próf.', 'mín.'). Note that this also # applies for uppercase versions: 'Örn.', 'Próf.' yield token token = next_token else: # Substitute the abbreviation and eat the period token = TOK.Word( token.concatenate(next_token), lookup(abbrev) ) else: # 'Regular' abbreviation in the middle of a sentence: # Eat the period and yield the abbreviation as a single token token = TOK.Word(token.concatenate(next_token), lookup(abbrev)) next_token = follow_token # Coalesce 'klukkan'/[kl.] + time or number into a time if next_token.kind == TOK.TIME or next_token.kind == TOK.NUMBER: if token.kind == TOK.WORD and token.txt.lower() in CLOCK_ABBREVS: # Match: coalesce and step to next token if next_token.kind == TOK.NUMBER: # next_token.txt may be a real number, i.e. 13,40, # which may have been converted from 13.40 # If we now have hh.mm, parse it as such a = "{0:.2f}".format(next_token.number).split(".") h, m = int(a[0]), int(a[1]) token = TOK.Time( token.concatenate(next_token, separator=" "), h, m, 0, ) else: # next_token.kind is TOK.TIME dt = cast(DateTimeTuple, next_token.val) token = TOK.Time( token.concatenate(next_token, separator=" "), dt[0], dt[1], dt[2], ) next_token = next(token_stream) # Coalesce 'klukkan/kl. átta/hálfátta' into a time elif ( next_token.kind == TOK.WORD and next_token.txt.lower() in CLOCK_NUMBERS ): if token.kind == TOK.WORD and token.txt.lower() in CLOCK_ABBREVS: # Match: coalesce and step to next token next_txt = next_token.txt.lower() token = TOK.Time( token.concatenate(next_token, separator=" "), *CLOCK_NUMBERS.get(next_txt, (0, 0, 0)), ) next_token = next(token_stream) # Coalesce 'klukkan/kl. hálf átta' into a time elif next_token.kind == TOK.WORD and next_token.txt.lower() == "hálf": if token.kind == TOK.WORD and token.txt.lower() in CLOCK_ABBREVS: time_token = next(token_stream) time_txt = time_token.txt.lower() if time_token.txt else "" if time_txt in CLOCK_NUMBERS and not time_txt.startswith("hálf"): # Match temp_tok = token.concatenate(next_token, separator=" ") temp_tok = temp_tok.concatenate(time_token, separator=" ") token = TOK.Time(temp_tok, *CLOCK_NUMBERS["hálf" + time_txt]) next_token = next(token_stream) else: # Not a match: must retreat yield token token = next_token next_token = time_token # Words like 'hálftólf' are only used in temporal expressions # so can stand alone if token.txt in CLOCK_HALF: token = TOK.Time(token, *CLOCK_NUMBERS.get(token.txt, (0, 0, 0))) # Coalesce 'árið' + [year|number] into year if (token.kind == TOK.WORD and token.txt.lower() in YEAR_WORD) and ( next_token.kind == TOK.YEAR or next_token.kind == TOK.NUMBER ): token = TOK.Year( token.concatenate(next_token, separator=" "), next_token.integer, ) next_token = next(token_stream) # Coalesece 3-digit number followed by 4-digit number into tel. no. if ( token.kind == TOK.NUMBER and (next_token.kind == TOK.NUMBER or next_token.kind == TOK.YEAR) and token.txt[0] in TELNO_PREFIXES and re.search(r"^\d\d\d$", token.txt) and re.search(r"^\d\d\d\d$", next_token.txt) ): telno = token.txt + "-" + next_token.txt token = TOK.Telno(token.concatenate(next_token, separator=" "), telno) next_token = next(token_stream) # Coalesce percentages or promilles into a single token if next_token.punctuation in ("%", "‰"): if token.kind == TOK.NUMBER: # Percentage: convert to a single 'tight' percentage token # In this case, there are no cases and no gender sign = next_token.txt # Store promille as one-tenth of a percentage factor = 1.0 if sign == "%" else 0.1 token = TOK.Percent( token.concatenate(next_token), token.number * factor ) next_token = next(token_stream) # Coalesce ordinals (1. = first, 2. = second...) into a single token if next_token.punctuation == ".": if (token.kind == TOK.NUMBER and not "," in token.txt) or ( token.kind == TOK.WORD and RE_ROMAN_NUMERAL.match(token.txt) # Don't interpret a known abbreviation as a Roman numeral, # for instance the newspaper 'DV' and token.txt not in Abbreviations.DICT ): # Ordinal, i.e. whole number or Roman numeral followed by period: # convert to an ordinal token ord_token: Optional[Tok] = token_stream[0] if ord_token and not ( ord_token.kind in TOK.END or ord_token.punctuation in {"„", '"'} or ( ord_token.kind == TOK.WORD and ord_token.txt[0].isupper() and month_for_token(ord_token, True) is None ) ): # OK: replace the number/Roman numeral and the period # with an ordinal token num = ( token.integer if token.kind == TOK.NUMBER else roman_to_int(token.txt) ) token = TOK.Ordinal(token.concatenate(next_token), num) # Continue with the following word next_token = next(token_stream) # Convert "1920 mm" or "30 °C" to a single measurement token if ( token.kind == TOK.NUMBER or token.kind == TOK.YEAR ) and next_token.txt in SI_UNITS: value = token.number orig_unit = next_token.txt unit: str unit, factor_func = SI_UNITS.get(orig_unit, ("", 1.0)) if callable(factor_func): # We have a lambda conversion function value = factor_func(value) else: # Simple scaling factor assert isinstance(factor_func, float) value *= factor_func if unit in ("%", "‰"): token = TOK.Percent( token.concatenate(next_token, separator=" "), value ) else: token = TOK.Measurement( token.concatenate(next_token, separator=" "), unit, value, ) next_token = next(token_stream) # Special case for km/klst. if ( token.kind == TOK.MEASUREMENT and orig_unit == "km" and next_token.txt == "/" and token_stream.txt(0) == "klst" ): slashtok = next_token next_token = next(token_stream) unit = token.txt + "/" + next_token.txt temp_tok = token.concatenate(slashtok) temp_tok = temp_tok.concatenate(next_token) token = TOK.Measurement(temp_tok, unit, value) # Eat extra unit next_token = next(token_stream) if ( token.kind == TOK.MEASUREMENT and cast(MeasurementTuple, token.val)[0] == "°" and next_token.kind == TOK.WORD and next_token.txt in {"C", "F", "K"} ): # Handle 200° C new_unit = "°" + next_token.txt unit, factor_func = SI_UNITS.get(new_unit, ("", 1.0)) v = cast(MeasurementTuple, token.val)[1] if callable(factor_func): val = factor_func(v) else: assert isinstance(factor_func, float) val = factor_func * v if convert_measurements: txt: str = token.txt lentoken = len(txt) degree_symbol_span = (lentoken - 1, lentoken) # Remove the ° symbol token.substitute(degree_symbol_span, "") # Add it again in the correct place along with the unit token = token.concatenate(next_token, separator=" °") token = TOK.Measurement( token, unit, val, ) else: token = TOK.Measurement( token.concatenate(next_token, separator=" "), unit, val, ) next_token = next(token_stream) # Special case for measurement abbreviations # erroneously ending with a period. # We only allow this for measurements that end with # an alphabetic character, i.e. not for ², ³, °, %, ‰. # [ Uncomment the last condition for this behavior: # We don't do this for measurement units which # have other meanings - such as 'gr' (grams), as # 'gr.' is probably the abbreviation for 'grein'. ] txt = token.txt if ( token.kind == TOK.MEASUREMENT and next_token.kind == TOK.PUNCTUATION and next_token.txt == "." and txt[-1].isalpha() # and token.txt.split()[-1] + "." not in Abbreviations.DICT and not token_stream.could_be_end_of_sentence() ): unit, value = cast(MeasurementTuple, token.val) # Add the period to the token text token = TOK.Measurement(token.concatenate(next_token), unit, value) next_token = next(token_stream) # Cases such as USD. 44 if ( token.txt in CURRENCY_ABBREV and next_token.kind == TOK.PUNCTUATION and next_token.txt == "." and not token_stream.could_be_end_of_sentence() ): txt = token.txt # Hack to avoid Pylance/Pyright message token = TOK.Currency(token.concatenate(next_token), txt) next_token = next(token_stream) # Cases such as 19 $, 199.99 $ if ( token.kind == TOK.NUMBER and next_token.kind == TOK.PUNCTUATION and next_token.txt in CURRENCY_SYMBOLS ): token = TOK.Amount( token.concatenate(next_token, separator=" "), CURRENCY_SYMBOLS.get(next_token.txt, ""), token.number, ) next_token = next(token_stream) # Replace straight abbreviations # (i.e. those that don't end with a period) if token.kind == TOK.WORD and token.val is None: txt = token.txt if Abbreviations.has_meaning(txt): # Add a meaning to the token token = TOK.Word(token, Abbreviations.get_meaning(txt)) # Yield the current token and advance to the lookahead yield token token = next_token except StopIteration: # Final token (previous lookahead) if token: yield token def parse_sentences(token_stream: Iterator[Tok]) -> Iterator[Tok]: """Parse a stream of tokens looking for sentences, i.e. substreams within blocks delimited by sentence finishers (periods, question marks, exclamation marks, etc.)""" in_sentence = False token = cast(Tok, None) tok_begin_sentence = TOK.Begin_Sentence() tok_end_sentence = TOK.End_Sentence() try: # Maintain a one-token lookahead token = next(token_stream) while True: next_token = next(token_stream) if token.kind == TOK.P_BEGIN or token.kind == TOK.P_END: # Block start or end: finish the current sentence, if any if in_sentence: # If there's whitespace (or something else) hanging on token, # then move it to the end of sentence token. yield tok_end_sentence in_sentence = False if token.kind == TOK.P_BEGIN and next_token.kind == TOK.P_END: # P_BEGIN immediately followed by P_END: skip both and continue # The double assignment to token is necessary to ensure that # we are in a correct state if next() raises StopIteration # To preserve origin tracking through this operation we must: # 1. squish the two tokens together _skip_me = token.concatenate(next_token, metadata_from_other=True) # 2. replace their text with nothing (while preserving the original text) _skip_me.substitute((0, len(_skip_me.txt)), "") token = cast(Tok, None) # 3. attach them to the front of the next token token = _skip_me.concatenate( next(token_stream), metadata_from_other=True ) continue elif token.kind == TOK.X_END: assert not in_sentence elif token.kind == TOK.S_SPLIT: # Empty line in input: make sure to finish the current # sentence, if any, even if no ending punctuation has # been encountered if in_sentence: yield TOK.End_Sentence(token) in_sentence = False token = next_token else: # Swallow the S_SPLIT token but preserve any origin whitespace token = token.concatenate(next_token, metadata_from_other=True) continue else: if not in_sentence: # This token starts a new sentence yield tok_begin_sentence in_sentence = True if ( token.punctuation in PUNCT_INDIRECT_SPEECH and next_token.punctuation in DQUOTES ): yield token token = next_token next_token = next(token_stream) if next_token.txt.islower(): # Probably indirect speech # „Er einhver þarna?“ sagði konan. yield token token = next_token next_token = next(token_stream) else: yield token token = tok_end_sentence in_sentence = False if token.punctuation in END_OF_SENTENCE and not ( token.punctuation == "…" and not could_be_end_of_sentence( next_token ) # Excluding sentences with ellipsis in the middle ): # Combining punctuation ('??!!!') while ( token.punctuation in PUNCT_COMBINATIONS and next_token.punctuation in PUNCT_COMBINATIONS ): # The normalized form comes from the first token except with "…?" v = token.punctuation if v == "…" and next_token.punctuation == "?": v = next_token.punctuation token = TOK.Punctuation(token.concatenate(next_token), v) next_token = next(token_stream) # We may be finishing a sentence with not only a period but also # right parenthesis and quotation marks while next_token.punctuation in SENTENCE_FINISHERS: yield token token = next_token next_token = next(token_stream) # The sentence is definitely finished now yield token token = tok_end_sentence in_sentence = False yield token token = next_token except StopIteration: pass # Final token (previous lookahead) if token is not None and token.kind != TOK.S_SPLIT: if not in_sentence and token.kind not in TOK.END: # Starting something here yield tok_begin_sentence in_sentence = True yield token if in_sentence and token.kind in {TOK.S_END, TOK.P_END}: in_sentence = False # Done with the input stream # If still inside a sentence, finish it if in_sentence: yield tok_end_sentence def match_stem_list(token: Tok, stems: Mapping[str, float]) -> Optional[float]: """Find the stem of a word token in given dict, or return None if not found""" if token.kind != TOK.WORD: return None return stems.get(token.txt.lower(), None) def month_for_token(token: Tok, after_ordinal: bool = False) -> Optional[int]: """Return a number, 1..12, corresponding to a month name, or None if the token does not contain a month name""" if not after_ordinal and token.txt in MONTH_BLACKLIST: # Special case for 'Ágúst', which we do not recognize # as a month name unless it follows an ordinal number return None m = match_stem_list(token, MONTHS) return None if m is None else int(m) def parse_phrases_1(token_stream: Iterator[Tok]) -> Iterator[Tok]: """Handle dates and times""" token = cast(Tok, None) try: # Maintain a one-token lookahead token = next(token_stream) while True: next_token = next(token_stream) # Coalesce abbreviations and trailing period if token.kind == TOK.WORD and next_token.txt == ".": abbrev = token.txt + next_token.txt if abbrev in Abbreviations.FINISHERS: token = TOK.Word( token.concatenate(next_token), cast(Optional[List[BIN_Tuple]], token.val), ) next_token = next(token_stream) # Coalesce [year|number] + ['e.Kr.'|'f.Kr.'] into year if token.kind == TOK.YEAR or token.kind == TOK.NUMBER: val = token.integer nval = None if next_token.txt in BCE: # f.Kr. # Yes, we set year X BCE as year -X ;-) nval = -val elif next_token.txt in CE: # e.Kr. nval = val if nval is not None: token = TOK.Year(token.concatenate(next_token, separator=" "), nval) next_token = next(token_stream) if next_token.txt == ".": token = TOK.Year(token.concatenate(next_token), nval) next_token = next(token_stream) # Check for [number | ordinal] [month name] if ( token.kind == TOK.ORDINAL or token.kind == TOK.NUMBER ) and next_token.kind == TOK.WORD: if next_token.txt == "gr.": # Corner case: If we have an ordinal followed by # the abbreviation "gr.", we assume that the only # interpretation of the abbreviation is "grein". next_token = TOK.Word( next_token, [BIN_Tuple("grein", 0, "kvk", "skst", "gr.", "-")], ) month = month_for_token(next_token, True) if month is not None: if token.kind == TOK.NUMBER and not "." in token.txt: # Cases such as "5 mars" token.txt = token.txt + "." token = TOK.Date( token.concatenate(next_token, separator=" "), y=0, m=month, d=token.ordinal, ) # Eat the month name token next_token = next(token_stream) # Check for [date] [year] if token.kind == TOK.DATE and next_token.kind == TOK.YEAR: dt = cast(DateTimeTuple, token.val) if not dt[0]: # No year yet: add it token = TOK.Date( token.concatenate(next_token, separator=" "), y=cast(int, next_token.val), m=dt[1], d=dt[2], ) # Eat the year token next_token = next(token_stream) # Check for [date] [time] if token.kind == TOK.DATE and next_token.kind == TOK.TIME: # Create a time stamp y, mo, d = cast(DateTimeTuple, token.val) h, m, s = cast(DateTimeTuple, next_token.val) token = TOK.Timestamp( token.concatenate(next_token, separator=" "), y=y, mo=mo, d=d, h=h, m=m, s=s, ) # Eat the time token next_token = next(token_stream) if ( token.kind == TOK.NUMBER and next_token.kind == TOK.TELNO and token.txt in COUNTRY_CODES ): # Check for country code in front of telephone number token = TOK.Telno( token.concatenate(next_token, separator=" "), cast(TelnoTuple, next_token.val)[0], cc=token.txt, ) next_token = next(token_stream) # Yield the current token and advance to the lookahead yield token token = next_token except StopIteration: pass # Final token (previous lookahead) if token: yield token def parse_date_and_time(token_stream: Iterator[Tok]) -> Iterator[Tok]: """Handle dates and times, absolute and relative.""" token = cast(Tok, None) try: # Maintain a one-token lookahead token = next(token_stream) while True: next_token = next(token_stream) # DATEABS and DATEREL made # Check for [number | ordinal] [month name] if ( token.kind == TOK.ORDINAL or token.kind == TOK.NUMBER ) and next_token.kind == TOK.WORD: month = month_for_token(next_token, True) if month is not None: token = TOK.Date( token.concatenate(next_token, separator=" "), y=0, m=month, d=token.ordinal, ) # Eat the month name token next_token = next(token_stream) # Check for [DATE] [year] if token.kind == TOK.DATE and ( next_token.kind == TOK.NUMBER or next_token.kind == TOK.YEAR ): dt = cast(DateTimeTuple, token.val) if not dt[0]: # No year yet: add it year = next_token.integer if next_token.kind == TOK.NUMBER and not (1776 <= year <= 2100): # If the year is specified by a number, don't # accept it if it is outside the range 1776-2100 year = 0 if year != 0: token = TOK.Date( token.concatenate(next_token, separator=" "), y=year, m=dt[1], d=dt[2], ) # Eat the year token next_token = next(token_stream) # Check for [month name] [year|YEAR] if token.kind == TOK.WORD and ( next_token.kind == TOK.NUMBER or next_token.kind == TOK.YEAR ): month = month_for_token(token) if month is not None: year = next_token.integer if next_token.kind == TOK.NUMBER and not (1776 <= year <= 2100): year = 0 if year != 0: token = TOK.Date( token.concatenate(next_token, separator=" "), y=year, m=month, d=0, ) # Eat the year token next_token = next(token_stream) # Check for a single month, change to DATEREL if token.kind == TOK.WORD: month = month_for_token(token) # Don't automatically interpret "mar", etc. as month names, # since they are ambiguous if month is not None and token.txt not in AMBIGUOUS_MONTH_NAMES: token = TOK.Daterel(token, y=0, m=month, d=0) # Split DATE into DATEABS and DATEREL if token.kind == TOK.DATE: dt = cast(DateTimeTuple, token.val) if dt[0] and dt[1] and dt[2]: token = TOK.Dateabs(token, y=dt[0], m=dt[1], d=dt[2]) else: token = TOK.Daterel(token, y=dt[0], m=dt[1], d=dt[2]) # Split TIMESTAMP into TIMESTAMPABS and TIMESTAMPREL if token.kind == TOK.TIMESTAMP: ts: TimeStampTuple = cast(TimeStampTuple, token.val) if all(x != 0 for x in ts[0:3]): # Year, month and day all non-zero (h, m, s can be zero) token = TOK.Timestampabs(token, *ts) else: token = TOK.Timestamprel(token, *ts) # Swallow "e.Kr." and "f.Kr." postfixes if token.kind == TOK.DATEABS: dt = cast(DateTimeTuple, token.val) if next_token.kind == TOK.WORD and next_token.txt in CE_BCE: y = dt[0] if next_token.txt in BCE: # Change year to negative number y = -y token = TOK.Dateabs( token.concatenate(next_token, separator=" "), y=y, m=dt[1], d=dt[2], ) # Swallow the postfix next_token = next(token_stream) # Check for [date] [time] (absolute) if token.kind == TOK.DATEABS: if next_token.kind == TOK.TIME: # Create an absolute time stamp y, mo, d = cast(DateTimeTuple, token.val) h, m, s = cast(DateTimeTuple, next_token.val) token = TOK.Timestampabs( token.concatenate(next_token, separator=" "), y=y, mo=mo, d=d, h=h, m=m, s=s, ) # Eat the time token next_token = next(token_stream) # Check for [date] [time] (relative) if token.kind == TOK.DATEREL: if next_token.kind == TOK.TIME: # Create a time stamp y, mo, d = cast(DateTimeTuple, token.val) h, m, s = cast(DateTimeTuple, next_token.val) token = TOK.Timestamprel( token.concatenate(next_token, separator=" "), y=y, mo=mo, d=d, h=h, m=m, s=s, ) # Eat the time token next_token = next(token_stream) # Yield the current token and advance to the lookahead yield token token = next_token except StopIteration: pass # Final token (previous lookahead) if token: yield token def parse_phrases_2( token_stream: Iterator[Tok], coalesce_percent: bool = False ) -> Iterator[Tok]: """Handle numbers, amounts and composite words.""" token = cast(Tok, None) try: # Maintain a one-token lookahead token = next(token_stream) while True: next_token = next(token_stream) # Logic for numbers and fractions that are partially or entirely # written out in words # Check for [CURRENCY] [number] (e.g. kr. 9.900 or USD 50) if next_token.kind == TOK.NUMBER and ( token.txt in ISK_AMOUNT_PRECEDING or token.txt in CURRENCY_ABBREV ): curr = "ISK" if token.txt in ISK_AMOUNT_PRECEDING else token.txt token = TOK.Amount( token.concatenate(next_token, separator=" "), curr, next_token.number, ) next_token = next(token_stream) # Check for [number] [ISK_AMOUNT|CURRENCY|PERCENTAGE] elif token.kind == TOK.NUMBER and next_token.kind == TOK.WORD: if next_token.txt in AMOUNT_ABBREV: # Abbreviations for ISK amounts # For abbreviations, we do not know the case, # but we try to retain the previous case information if any token = TOK.Amount( token.concatenate(next_token, separator=" "), "ISK", token.number * AMOUNT_ABBREV[next_token.txt], ) next_token = next(token_stream) elif next_token.txt in CURRENCY_ABBREV: # A number followed by an ISO currency abbreviation token = TOK.Amount( token.concatenate(next_token, separator=" "), next_token.txt, token.number, ) next_token = next(token_stream) else: # Check for [number] 'prósent/prósentustig/hundraðshlutar' if coalesce_percent: percentage = match_stem_list(next_token, PERCENTAGES) else: percentage = None if percentage is not None: # We have '17 prósent': coalesce into a single token token = TOK.Percent( token.concatenate(next_token, separator=" "), token.number, ) # Eat the percent word token next_token = next(token_stream) # Check for composites: # 'stjórnskipunar- og eftirlitsnefnd' # 'dómsmála-, viðskipta- og iðnaðarráðherra' tq: List[Tok] = [] while token.kind == TOK.WORD and next_token.punctuation == COMPOSITE_HYPHEN: # Accumulate the prefix in tq tq.append(token) tq.append(TOK.Punctuation(next_token, normalized=HYPHEN)) # Check for optional comma after the prefix comma_token = next(token_stream) if comma_token.punctuation == ",": # A comma is present: append it to the queue # and skip to the next token tq.append(comma_token) comma_token = next(token_stream) # Reset our two lookahead tokens token = comma_token next_token = next(token_stream) if tq: # We have accumulated one or more prefixes # ('dómsmála-, viðskipta-') if token.kind == TOK.WORD and token.txt in ("og", "eða"): # We have 'viðskipta- og' if next_token.kind != TOK.WORD: # Incorrect: yield the accumulated token # queue and keep the current token and the # next_token lookahead unchanged for t in tq: yield t else: # We have 'viðskipta- og iðnaðarráðherra' # Return a single token with the meanings of # the last word, but an amalgamated token text. # Note: there is no meaning check for the first # part of the composition, so it can be an unknown word. _acc = tq[0] for t in tq[1:] + [token, next_token]: _acc = _acc.concatenate( t, separator=" ", metadata_from_other=True ) _acc.substitute_all(" -", "-") _acc.substitute_all(" ,", ",") token = _acc next_token = next(token_stream) else: # Incorrect prediction: make amends and continue for t in tq: yield t # Yield the current token and advance to the lookahead yield token token = next_token except StopIteration: pass # Final token (previous lookahead) if token: yield token def tokenize(text_or_gen: Union[str, Iterable[str]], **options: Any) -> Iterator[Tok]: """Tokenize text in several phases, returning a generator (iterable sequence) of tokens that processes tokens on-demand.""" # Thank you Python for enabling this programming pattern ;-) # Make sure that the abbreviation config file has been read Abbreviations.initialize() with_annotation = options.pop("with_annotation", True) coalesce_percent = options.pop("coalesce_percent", False) token_stream = parse_tokens(text_or_gen, **options) token_stream = parse_particles(token_stream, **options) token_stream = parse_sentences(token_stream) token_stream = parse_phrases_1(token_stream) token_stream = parse_date_and_time(token_stream) # Skip the parse_phrases_2 pass if the with_annotation option is False if with_annotation: token_stream = parse_phrases_2(token_stream, coalesce_percent=coalesce_percent) return (t for t in token_stream if t.kind != TOK.X_END) def tokenize_without_annotation( text_or_gen: Union[str, Iterable[str]], **options: Any ) -> Iterator[Tok]: """Tokenize without the last pass which can be done more thoroughly if BÍN annotation is available, for instance in GreynirPackage.""" return tokenize(text_or_gen, with_annotation=False, **options) def split_into_sentences( text_or_gen: Union[str, Iterable[str]], **options: Any ) -> Iterator[str]: """Shallow tokenization of the input text, which can be either a text string or a generator of lines of text (such as a file). This function returns a generator of strings, where each string is a sentence, and tokens are separated by spaces.""" to_text: Callable[[Tok], str] og = options.pop("original", False) if options.pop("normalize", False): to_text = normalized_text elif og: to_text = lambda t: t.original or t.txt else: to_text = lambda t: t.txt curr_sent: List[str] = [] for t in tokenize_without_annotation(text_or_gen, **options): if t.kind in TOK.END: # End of sentence/paragraph # Note that curr_sent can be an empty list, # and in that case we yield an empty string if t.kind == TOK.S_END or t.kind == TOK.S_SPLIT: if og: yield "".join(curr_sent) else: yield " ".join(curr_sent) curr_sent = [] elif t.kind not in TOK.BEGIN: txt = to_text(t) if txt: curr_sent.append(txt) if curr_sent: if og: yield "".join(curr_sent) else: yield " ".join(curr_sent) def mark_paragraphs(txt: str) -> str: """Insert paragraph markers into plaintext, by newlines""" if not txt: return "[[]]" return "[[" + "]][[".join(t for t in txt.split("\n") if t) + "]]" def paragraphs(tokens: Iterable[Tok]) -> Iterator[List[Tuple[int, List[Tok]]]]: """Generator yielding paragraphs from token iterable. Each paragraph is a list of sentence tuples. Sentence tuples consist of the index of the first token of the sentence (the TOK.S_BEGIN token) and a list of the tokens within the sentence, not including the starting TOK.S_BEGIN or the terminating TOK.S_END tokens.""" def valid_sent(sent: Optional[List[Tok]]) -> bool: """Return True if the token list in sent is a proper sentence that we want to process further""" if not sent: return False # A sentence with only punctuation is not valid return any(t[0] != TOK.PUNCTUATION for t in sent) sent: List[Tok] = [] # Current sentence sent_begin = 0 current_p: List[Tuple[int, List[Tok]]] = [] # Current paragraph for ix, t in enumerate(tokens): t0 = t[0] if t0 == TOK.S_BEGIN: sent = [] sent_begin = ix elif t0 == TOK.S_END: if valid_sent(sent): # Do not include or count zero-length sentences current_p.append((sent_begin, sent)) sent = [] elif t0 == TOK.P_BEGIN or t0 == TOK.P_END: # New paragraph marker: Start a new paragraph if we didn't have one before # or if we already had one with some content if valid_sent(sent): current_p.append((sent_begin, sent)) sent = [] if current_p: yield current_p current_p = [] else: sent.append(t) if valid_sent(sent): current_p.append((sent_begin, sent)) if current_p: yield current_p RE_SPLIT_STR = ( # The following regex catches Icelandic numbers with dots and a comma r"([\+\-\$€]?\d{1,3}(?:\.\d\d\d)+\,\d+)" # +123.456,789 # The following regex catches English numbers with commas and a dot r"|([\+\-\$€]?\d{1,3}(?:\,\d\d\d)+\.\d+)" # +123,456.789 # The following regex catches Icelandic numbers with a comma only r"|([\+\-\$€]?\d+\,\d+(?!\.\d))" # -1234,56 # The following regex catches English numbers with a dot only r"|([\+\-\$€]?\d+\.\d+(?!\,\d))" # -1234.56 # Finally, space and punctuation r"|([~\s" + "".join("\\" + c for c in PUNCTUATION) + r"])" ) RE_SPLIT = re.compile(RE_SPLIT_STR) def correct_spaces(s: str) -> str: """Utility function to split and re-compose a string with correct spacing between tokens. NOTE that this function uses a quick-and-dirty approach which may not handle all edge cases!""" r: List[str] = [] last = TP_NONE double_quote_count = 0 for w in RE_SPLIT.split(s): if w is None: continue w = w.strip() if not w: continue if len(w) > 1: this = TP_WORD elif w == '"': # For English-type double quotes, we glue them alternatively # to the right and to the left token this = (TP_LEFT, TP_RIGHT)[double_quote_count % 2] double_quote_count += 1 elif w in LEFT_PUNCTUATION: this = TP_LEFT elif w in RIGHT_PUNCTUATION: this = TP_RIGHT elif w in NONE_PUNCTUATION: this = TP_NONE elif w in CENTER_PUNCTUATION: this = TP_CENTER else: this = TP_WORD if ( (w == "og" or w == "eða") and len(r) >= 2 and r[-1] == "-" and r[-2].lstrip().isalpha() ): # Special case for compounds such as "fjármála- og efnahagsráðuneytið" # and "Iðnaðar-, ferðamála- og atvinnuráðuneytið": # detach the hyphen from "og"/"eða" r.append(" " + w) elif ( this == TP_WORD and len(r) >= 2 and r[-1] == "-" and w.isalpha() and (r[-2] == "," or r[-2].lstrip() in ("og", "eða")) ): # Special case for compounds such as # "bensínstöðvar, -dælur og -tankar" r[-1] = " -" r.append(w) elif TP_SPACE[last - 1][this - 1] and r: r.append(" " + w) else: r.append(w) last = this return "".join(r) def detokenize(tokens: Iterable[Tok], normalize: bool = False) -> str: """Utility function to convert an iterable of tokens back to a correctly spaced string. If normalize is True, punctuation is normalized before assembling the string.""" to_text: Callable[[Tok], str] = normalized_text if normalize else lambda t: t.txt r: List[str] = [] last = TP_NONE double_quote_count = 0 for t in tokens: w = to_text(t) if not w: continue this = TP_WORD if t.kind == TOK.PUNCTUATION: if len(w) > 1: pass elif w == '"': # For English-type double quotes, we glue them alternatively # to the right and to the left token this = (TP_LEFT, TP_RIGHT)[double_quote_count % 2] double_quote_count += 1 elif w in LEFT_PUNCTUATION: this = TP_LEFT elif w in RIGHT_PUNCTUATION: this = TP_RIGHT elif w in NONE_PUNCTUATION: this = TP_NONE elif w in CENTER_PUNCTUATION: this = TP_CENTER if TP_SPACE[last - 1][this - 1] and r: r.append(" " + w) else: r.append(w) last = this return "".join(r) def calculate_indexes( tokens: Iterable[Tok], last_is_end: bool = False ) -> Tuple[List[int], List[int]]: """Calculate character and byte indexes for a token stream. The indexes are the start positions of each token in the original text that was tokenized. 'last_is_end' determines whether to include a "past-the-end" index at the end. This index is also the total length of the sequence. """ def byte_len(string: str) -> int: return len(bytes(string, encoding="utf-8")) char_indexes = [0] byte_indexes = [0] for t in tokens: if t.original: char_indexes.append(char_indexes[-1] + len(t.original)) byte_indexes.append(byte_indexes[-1] + byte_len(t.original)) else: if t.txt: # Origin tracking failed for this token. # TODO: Can we do something better here? Or guarantee that it doesn't happen? raise ValueError( f"Origin tracking failed at {t.txt} near index {char_indexes[-1]}" ) else: # This is some marker token that has no text pass if not last_is_end: char_indexes = char_indexes[:-1] byte_indexes = byte_indexes[:-1] return char_indexes, byte_indexes
128,327
37.618116
107
py
Tokenizer
Tokenizer-master/src/tokenizer/__init__.py
""" Copyright(C) 2022 Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. """ from .definitions import ( TP_LEFT, TP_CENTER, TP_RIGHT, TP_NONE, TP_WORD, EN_DASH, EM_DASH, KLUDGY_ORDINALS_PASS_THROUGH, KLUDGY_ORDINALS_MODIFY, KLUDGY_ORDINALS_TRANSLATE, BIN_Tuple, BIN_TupleList, ) from .tokenizer import ( TOK, Tok, tokenize, tokenize_without_annotation, split_into_sentences, parse_tokens, correct_spaces, detokenize, mark_paragraphs, paragraphs, normalized_text, normalized_text_from_tokens, text_from_tokens, calculate_indexes, generate_raw_tokens, TokenStream, ) from .abbrev import Abbreviations, ConfigError from .version import __version__ __author__ = "Miðeind ehf" __copyright__ = "(C) 2022 Miðeind ehf." __all__ = ( "__author__", "__copyright__", "__version__", "Abbreviations", "BIN_Tuple", "BIN_TupleList", "calculate_indexes", "ConfigError", "correct_spaces", "detokenize", "EM_DASH", "EN_DASH", "generate_raw_tokens", "KLUDGY_ORDINALS_MODIFY", "KLUDGY_ORDINALS_PASS_THROUGH", "KLUDGY_ORDINALS_TRANSLATE", "mark_paragraphs", "normalized_text_from_tokens", "normalized_text", "paragraphs", "parse_tokens", "split_into_sentences", "text_from_tokens", "Tok", "TOK", "tokenize_without_annotation", "tokenize", "TokenStream", "TP_CENTER", "TP_LEFT", "TP_NONE", "TP_RIGHT", "TP_WORD", )
2,759
25.796117
78
py
Tokenizer
Tokenizer-master/test/test_tokenizer_tok.py
# type: ignore """ Tests for Tokenizer module Copyright (C) 2022 by Miðeind ehf. This software is licensed under the MIT License: 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. """ import tokenizer Tok = tokenizer.Tok TOK = tokenizer.TOK ACCENT = chr(769) UMLAUT = chr(776) SOFT_HYPHEN = chr(173) ZEROWIDTH_SPACE = chr(8203) ZEROWIDTH_NBSP = chr(65279) def test_split_simple() -> None: t = Tok(TOK.RAW, "boat", None) l, r = t.split(2) assert l == Tok(TOK.RAW, "bo", None) assert r == Tok(TOK.RAW, "at", None) def test_split_simple_original() -> None: t = Tok(TOK.RAW, "boat", None, "boat", [0, 1, 2, 3]) l, r = t.split(2) assert l == Tok(TOK.RAW, "bo", None, "bo", [0, 1]) assert r == Tok(TOK.RAW, "at", None, "at", [0, 1]) def test_split_with_substitutions() -> None: # original: "a&123b". replace "&123" with "x" and end up with "axb" t = Tok(TOK.RAW, "axb", None, "a&123b", [0, 1, 5]) l1, r1 = t.split(1) assert l1 == Tok(TOK.RAW, "a", None, "a", [0]) assert r1 == Tok(TOK.RAW, "xb", None, "&123b", [0, 4]) l2, r2 = t.split(2) assert l2 == Tok(TOK.RAW, "ax", None, "a&123", [0, 1]) assert r2 == Tok(TOK.RAW, "b", None, "b", [0]) def test_split_with_substitutions_with_whitespace_prefix() -> None: # original: " a&123b". strip whitespace and replace "&123" with "x" and end up with "axb" t = Tok(TOK.RAW, "axb", None, " a&123b", [2, 3, 7]) l1, r1 = t.split(1) assert l1 == Tok(TOK.RAW, "a", None, " a", [2]) assert r1 == Tok(TOK.RAW, "xb", None, "&123b", [0, 4]) l2, r2 = t.split(2) assert l2 == Tok(TOK.RAW, "ax", None, " a&123", [2, 3]) assert r2 == Tok(TOK.RAW, "b", None, "b", [0]) def test_split_with_whitespace_prefix() -> None: t = Tok(TOK.RAW, "boat", None, " boat", [3, 4, 5, 6]) l, r = t.split(2) assert l == Tok(TOK.RAW, "bo", None, " bo", [3, 4]) assert r == Tok(TOK.RAW, "at", None, "at", [0, 1]) def test_split_at_ends() -> None: t = Tok(TOK.RAW, "ab", None, "ab", [0, 1]) l, r = t.split(0) assert l == Tok(TOK.RAW, "", None, "", []) assert r == Tok(TOK.RAW, "ab", None, "ab", [0, 1]) t = Tok(TOK.RAW, "ab", None, "ab", [0, 1]) l, r = t.split(2) assert l == Tok(TOK.RAW, "ab", None, "ab", [0, 1]) assert r == Tok(TOK.RAW, "", None, "", []) t = Tok(TOK.RAW, "ab", None) l, r = t.split(0) assert l == Tok(TOK.RAW, "", None) assert r == Tok(TOK.RAW, "ab", None) t = Tok(TOK.RAW, "ab", None) l, r = t.split(2) assert l == Tok(TOK.RAW, "ab", None) assert r == Tok(TOK.RAW, "", None) def test_split_with_negative_index() -> None: test_string = "abcde" t = Tok(TOK.RAW, test_string, None, test_string, list(range(len(test_string)))) l, r = t.split(-2) assert l == Tok(TOK.RAW, "abc", None, "abc", [0, 1, 2]) assert r == Tok(TOK.RAW, "de", None, "de", [0, 1]) """ TODO: Haven't decided what's the correct behavior. def test_split_on_empty_txt(): t = Tok(TOK.RAW, "", None, "this got removed", []) l, r = t.split(0) assert l == Tok(TOK.RAW, "", None, "", []) assert r == Tok(TOK.RAW, "", None, "this got removed", []) l, r = t.split(1) assert l == Tok(TOK.RAW, "", None, "this got removed", []) assert r == Tok(TOK.RAW, "", None, "", []) """ def test_substitute() -> None: t = Tok(TOK.RAW, "a&123b", None, "a&123b", [0, 1, 2, 3, 4, 5]) t.substitute((1, 5), "x") assert t == Tok(TOK.RAW, "axb", None, "a&123b", [0, 1, 5]) t = Tok(TOK.RAW, "ab&123", None, "ab&123", [0, 1, 2, 3, 4, 5]) t.substitute((2, 6), "x") assert t == Tok(TOK.RAW, "abx", None, "ab&123", [0, 1, 2]) t = Tok(TOK.RAW, "&123ab", None, "&123ab", [0, 1, 2, 3, 4, 5]) t.substitute((0, 4), "x") assert t == Tok(TOK.RAW, "xab", None, "&123ab", [0, 4, 5]) def test_substitute_bugfix_1() -> None: test_string = "xya" + ACCENT + "zu" + ACCENT + "w&aacute;o" + UMLAUT + "b" # 012 3 45 6 7890123456 7 8 # 0123456789012345 t = Tok( kind=-1, txt=test_string, val=None, original=test_string, origin_spans=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18], ) t.substitute((2, 4), "á") assert t == Tok( kind=-1, txt="xyázu" + ACCENT + "w&aacute;o" + UMLAUT + "b", val=None, original=test_string, origin_spans=[0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18], ) t.substitute((4, 6), "ú") assert t == Tok( kind=-1, txt="xyázúw&aacute;o" + UMLAUT + "b", val=None, original=test_string, origin_spans=[0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18], ) t.substitute((14, 16), "ö") assert t == Tok( kind=-1, txt="xyázúw&aacute;öb", val=None, original=test_string, origin_spans=[0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18], ) # bug was here t.substitute((6, 14), "á") assert t == Tok( kind=-1, txt="xyázúwáöb", val=None, original=test_string, origin_spans=[0, 1, 2, 4, 5, 7, 8, 16, 18], ) def test_multiple_substitutions() -> None: t = Tok( TOK.RAW, "a&123b&456&789c", None, "a&123b&456&789c", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], ) t.substitute((1, 5), "x") assert t == Tok( TOK.RAW, "axb&456&789c", None, "a&123b&456&789c", [0, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], ) t.substitute((3, 7), "y") assert t == Tok( TOK.RAW, "axby&789c", None, "a&123b&456&789c", [0, 1, 5, 6, 10, 11, 12, 13, 14] ) t.substitute((4, 8), "z") assert t == Tok(TOK.RAW, "axbyzc", None, "a&123b&456&789c", [0, 1, 5, 6, 10, 14]) def test_substitute_without_origin_tracking() -> None: t = Tok(TOK.RAW, "a&123b", None) t.substitute((1, 5), "x") assert t == Tok(TOK.RAW, "axb", None) t = Tok(TOK.RAW, "ab&123", None) t.substitute((2, 6), "x") assert t == Tok(TOK.RAW, "abx", None) t = Tok(TOK.RAW, "&123ab", None) t.substitute((0, 4), "x") assert t == Tok(TOK.RAW, "xab", None) t = Tok(TOK.RAW, "a&123b&456c", None) t.substitute((1, 5), "x") assert t == Tok(TOK.RAW, "axb&456c", None) t.substitute((3, 7), "y") assert t == Tok(TOK.RAW, "axbyc", None) def test_substitute_that_removes() -> None: t = Tok(TOK.RAW, "a&123b", None, "a&123b", [0, 1, 2, 3, 4, 5]) t.substitute((1, 5), "") assert t == Tok(TOK.RAW, "ab", None, "a&123b", [0, 5]) t = Tok(TOK.RAW, "&123ab", None, "&123ab", [0, 1, 2, 3, 4, 5]) t.substitute((0, 4), "") assert t == Tok(TOK.RAW, "ab", None, "&123ab", [4, 5]) t = Tok(TOK.RAW, "ab&123", None, "ab&123", [0, 1, 2, 3, 4, 5]) t.substitute((2, 6), "") assert t == Tok(TOK.RAW, "ab", None, "ab&123", [0, 1]) def test_split_without_origin_tracking() -> None: t = Tok(TOK.RAW, "boat", None) l, r = t.split(2) assert l == Tok(TOK.RAW, "bo", None) assert r == Tok(TOK.RAW, "at", None) ### # original: "a&123b". replace "&123" with "x" and end up with "axb" t = Tok(TOK.RAW, "axb", None) l1, r1 = t.split(1) assert l1 == Tok(TOK.RAW, "a", None) assert r1 == Tok(TOK.RAW, "xb", None) l2, r2 = t.split(2) assert l2 == Tok(TOK.RAW, "ax", None) assert r2 == Tok(TOK.RAW, "b", None) ### # original: " a&123b". strip whitespace and replace "&123" with "x" and end up with "axb" t = Tok(TOK.RAW, "axb", None) l1, r1 = t.split(1) assert l1 == Tok(TOK.RAW, "a", None) assert r1 == Tok(TOK.RAW, "xb", None) l2, r2 = t.split(2) assert l2 == Tok(TOK.RAW, "ax", None) assert r2 == Tok(TOK.RAW, "b", None) ### t = Tok(TOK.RAW, "boat", None) l, r = t.split(2) assert l == Tok(TOK.RAW, "bo", None) assert r == Tok(TOK.RAW, "at", None) def test_html_escapes_with_origin_tracking() -> None: test_string = "xy&#x61;z&aacute;w&#97;b" tokens = list(tokenizer.generate_raw_tokens(test_string, replace_html_escapes=True)) assert len(tokens) == 1 assert tokens[0] == Tok( kind=TOK.RAW, txt="xyazáwab", val=None, original=test_string, origin_spans=[0, 1, 2, 8, 9, 17, 18, 23], ) # Note the space after &nbsp; test_string = "Ég&nbsp; fór út." # Here we show in comments when a new token starts in the string with "|" (inclusive). # | | | # We also show the character indices for each token. # 0101234567890123 # And where the 'txt' is. # ^^ ^^^ ^^^ tokens = list(tokenizer.generate_raw_tokens(test_string, replace_html_escapes=True)) assert len(tokens) == 3 assert tokens == [ Tok(kind=TOK.RAW, txt="Ég", val=None, original="Ég", origin_spans=[0, 1]), Tok( kind=TOK.RAW, txt="fór", val=None, original="&nbsp; fór", origin_spans=[7, 8, 9], ), Tok(kind=TOK.RAW, txt="út.", val=None, original=" út.", origin_spans=[1, 2, 3]), ] test_string = "Ég&nbsp;&nbsp;fór út." # | | | # 010123456789012340123 # ^^ ^^^ ^^^ tokens = list(tokenizer.generate_raw_tokens(test_string, replace_html_escapes=True)) assert len(tokens) == 3 assert tokens == [ Tok(kind=TOK.RAW, txt="Ég", val=None, original="Ég", origin_spans=[0, 1]), Tok( kind=TOK.RAW, txt="fór", val=None, original="&nbsp;&nbsp;fór", origin_spans=[12, 13, 14], ), Tok(kind=TOK.RAW, txt="út.", val=None, original=" út.", origin_spans=[1, 2, 3]), ] test_string = "Ég&nbsp;fór&nbsp;út." # | | | # 01012345678012345678 # ^^ ^^^ ^^^ tokens = list(tokenizer.generate_raw_tokens(test_string, replace_html_escapes=True)) assert len(tokens) == 3 assert tokens == [ Tok(kind=TOK.RAW, txt="Ég", val=None, original="Ég", origin_spans=[0, 1]), Tok( kind=TOK.RAW, txt="fór", val=None, original="&nbsp;fór", origin_spans=[6, 7, 8], ), Tok( kind=TOK.RAW, txt="út.", val=None, original="&nbsp;út.", origin_spans=[6, 7, 8], ), ] test_string = "Ég fór út.&nbsp;" # | | | # 0101230123012345 # ^^ ^^^ ^^^ tokens = list(tokenizer.generate_raw_tokens(test_string, replace_html_escapes=True)) assert len(tokens) == 4 assert tokens == [ Tok(kind=TOK.RAW, txt="Ég", val=None, original="Ég", origin_spans=[0, 1]), Tok(kind=TOK.RAW, txt="fór", val=None, original=" fór", origin_spans=[1, 2, 3]), Tok(kind=TOK.RAW, txt="út.", val=None, original=" út.", origin_spans=[1, 2, 3]), Tok(kind=TOK.S_SPLIT, txt="", val=None, original="&nbsp;", origin_spans=[]), ] test_string = "&nbsp;Ég fór út." # | | | # 0123456701230123 # ^^ ^^^ ^^^ tokens = list(tokenizer.generate_raw_tokens(test_string, replace_html_escapes=True)) assert len(tokens) == 3 assert tokens == [ Tok(kind=TOK.RAW, txt="Ég", val=None, original="&nbsp;Ég", origin_spans=[6, 7]), Tok(kind=TOK.RAW, txt="fór", val=None, original=" fór", origin_spans=[1, 2, 3]), Tok(kind=TOK.RAW, txt="út.", val=None, original=" út.", origin_spans=[1, 2, 3]), ] def test_unicode_escapes_with_origin_tracking() -> None: test_string = "xya" + ACCENT + "zu" + ACCENT + "wo" + UMLAUT + "b" tokens = list( tokenizer.generate_raw_tokens(test_string, replace_composite_glyphs=True) ) assert len(tokens) == 1 assert tokens[0] == Tok( kind=TOK.RAW, txt="xyázúwöb", val=None, original=test_string, origin_spans=[0, 1, 2, 4, 5, 7, 8, 10], ) test_string = ( "þetta" + ZEROWIDTH_SPACE + "er" + ZEROWIDTH_NBSP + "eitt" + SOFT_HYPHEN + "orð" ) tokens = list( tokenizer.generate_raw_tokens(test_string, replace_composite_glyphs=True) ) assert len(tokens) == 1 assert tokens[0] == Tok( kind=TOK.RAW, txt="þettaereittorð", val=None, original=test_string, origin_spans=[0, 1, 2, 3, 4, 6, 7, 9, 10, 11, 12, 14, 15, 16], ) def test_unicode_escapes_that_are_removed() -> None: test_string = "a\xadb\xadc" tokens = list( tokenizer.generate_raw_tokens(test_string, replace_composite_glyphs=True) ) assert len(tokens) == 1 assert tokens[0] == Tok( kind=TOK.RAW, txt="abc", val=None, original=test_string, origin_spans=[0, 2, 4] ) def test_html_unicode_mix() -> None: test_string = "xya" + ACCENT + "zu" + ACCENT + "w&aacute;o" + UMLAUT + "b" # 012 3 45 6 7890123456 7 8 tokens = list( tokenizer.generate_raw_tokens( test_string, replace_composite_glyphs=True, replace_html_escapes=True ) ) assert len(tokens) == 1 assert tokens[0] == Tok( kind=TOK.RAW, txt="xyázúwáöb", val=None, original=test_string, origin_spans=[0, 1, 2, 4, 5, 7, 8, 16, 18], ) def test_tok_concatenation() -> None: str1 = "asdf" tok1 = Tok(TOK.RAW, str1, None, str1, list(range(len(str1)))) str2 = "jklæ" tok2 = Tok(TOK.RAW, str2, None, str2, list(range(len(str1)))) assert tok1.concatenate(tok2) == Tok( TOK.RAW, str1 + str2, None, str1 + str2, list(range(len(str1 + str2))) ) str1 = "abc" or1 = "&123&456&789" str2 = "xyz" or2 = "&xx&yy&zz" tok1 = Tok(TOK.RAW, str1, None, or1, [0, 4, 8]) tok2 = Tok(TOK.RAW, str2, None, or2, [0, 2, 4]) assert tok1.concatenate(tok2) == Tok( TOK.RAW, str1 + str2, None, or1 + or2, [0, 4, 8, 12, 14, 16] ) def test_tok_concatenation_with_separator() -> None: str1 = "asdf" tok1 = Tok(TOK.RAW, str1, None, str1, list(range(len(str1)))) str2 = "jklæ" tok2 = Tok(TOK.RAW, str2, None, str2, list(range(len(str1)))) sep = "WOLOLO" assert tok1.concatenate(tok2, separator=sep) == Tok( TOK.RAW, str1 + sep + str2, None, str1 + str2, [0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 5, 6, 7], ) str1 = "abc" or1 = "&123&456&789" str2 = "xyz" or2 = "&xx&yy&zz" tok1 = Tok(TOK.RAW, str1, None, or1, [0, 4, 8]) tok2 = Tok(TOK.RAW, str2, None, or2, [0, 2, 4]) sep = "WOLOLO" assert tok1.concatenate(tok2, separator=sep) == Tok( TOK.RAW, str1 + sep + str2, None, or1 + or2, [0, 4, 8, 12, 12, 12, 12, 12, 12, 12, 14, 16], ) def test_tok_substitute_all() -> None: s = "asdf" t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_all("d", "x") assert t == Tok(TOK.RAW, "asxf", None, s, [0, 1, 2, 3]) s = "Þetta er lengri strengur." t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_all("e", "x") assert t == Tok(TOK.RAW, "Þxtta xr lxngri strxngur.", None, s, list(range(len(s)))) s = "asdf" t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_all("d", "") assert t == Tok(TOK.RAW, "asf", None, s, [0, 1, 3]) s = "Þessi verður lengri." # 01234567890123456789 t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_all("r", "") assert t == Tok( TOK.RAW, "Þessi veðu lengi.", None, s, [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 12, 13, 14, 15, 16, 18, 19], ) def test_tok_substitute_longer() -> None: s = "asdf" t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_longer((1, 2), "xyz") assert t == Tok(TOK.RAW, "axyzdf", None, s, [0, 2, 2, 2, 2, 3]) s = "asdf" t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_longer((3, 4), "xyz") assert t == Tok(TOK.RAW, "asdxyz", None, s, [0, 1, 2, 4, 4, 4]) s = "asdf" t = Tok(TOK.RAW, s, None, s, list(range(len(s)))) t.substitute_longer((0, 1), "xyz") assert t == Tok(TOK.RAW, "xyzsdf", None, s, [1, 1, 1, 1, 2, 3]) def test_tok_from_txt() -> None: s = "asdf" t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s)))) s = " asdf" t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s)))) s = "asdf " t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s)))) s = " asdf " t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s)))) s = "Tok getur alveg verið heil setning." t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s)))) s = "HTML&nbsp;&amp; er líka óbreytt" t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s)))) s = ( "unicode" + ZEROWIDTH_SPACE + "er" + ZEROWIDTH_NBSP + "líka" + SOFT_HYPHEN + "óbreytt" ) t = Tok.from_txt(s) assert t == Tok(TOK.RAW, s, None, s, list(range(len(s))))
18,605
30.589134
94
py
Tokenizer
Tokenizer-master/test/test_detokenize.py
# type: ignore """ test_detokenize.py Tests for Tokenizer module Copyright (C) 2022 by Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. """ import tokenizer as t def test_detokenize() -> None: options = { "normalize": True } def should_be_equal(s: str) -> None: toklist = t.tokenize(s, **options) assert s == t.detokenize(toklist, **options) def should_be(s1: str, s2: str) -> None: toklist = t.tokenize(s1, **options) assert s2 == t.detokenize(toklist, **options) should_be_equal("Jón átti 1.234,56 kr. í vasanum t.a.m. og 12. gr. átti ekki við.") should_be_equal("o.s.frv.") should_be_equal("http://www.malfong.is") should_be_equal("Páll skoðaði t.d. http://www.malfong.is.") should_be_equal("Páll var með netfangið [email protected].") should_be_equal("Páll var með „netfangið“ [email protected].") should_be_equal("Páll var m.a. [[email protected]] þann 10. 12. 1998.") should_be_equal("Páll var m.a. [[email protected]] þann 10.12.1998.") should_be_equal("Páll veiddi 74 cm. lax í Norðurá þann 1.3.") should_be( "Páll var með \"netfangið\" [email protected].", "Páll var með „netfangið“ [email protected]." ) # !!! BUG #should_be( # "Páll var með \"netfangið\", þ.e.a.s. (\"þetta\").", # "Páll var með „netfangið“, þ.e.a.s. („þetta“).", #) options = { "normalize": False } should_be_equal("Páll var með „netfangið“, þ.e.a.s. („þetta“).") should_be_equal("Páll var með \"netfangið\" [email protected].") should_be_equal("Páll var með \"netfangið\", þ.e.a.s. (\"þetta\").")
2,916
36.883117
87
py
Tokenizer
Tokenizer-master/test/test_index_calculation.py
# type: ignore """ test_index_calculation.py Tests for Tokenizer module Copyright (C) 2022 by Miðeind ehf. This software is licensed under the MIT License: 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. This module tests the token index generation of the tokenizer. """ import tokenizer Tok = tokenizer.Tok TOK = tokenizer.TOK ACCENT = chr(769) UMLAUT = chr(776) EM_DASH = "\u2014" def test_small_easy_cases() -> None: s = "Bara ASCII." # 01234567890 # ^ ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 4, 10] assert byte_indexes == [0, 4, 10] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 4, 10, 11] assert byte_indexes == [0, 4, 10, 11] s = "Á bát." # char: # 012345 # ^^ ^ # byte: # two-byte letters: # x x # indexes: # 023467 # ^^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 1, 5] assert byte_indexes == [0, 2, 7] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 1, 5, 6] assert byte_indexes == [0, 2, 7, 8] s = "endar á ö" # 012345678 # ^ ^ ^ # x x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 5, 7] assert byte_indexes == [0, 5, 8] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 5, 7, 9] assert byte_indexes == [0, 5, 8, 11] def test_small_difficult_cases() -> None: s = "" toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [] assert byte_indexes == [] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0] assert byte_indexes == [0] s = " " toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 1] assert byte_indexes == [0, 1] # Single byte characters for x in ["a", "A", ".", "?", "!"]: s = x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 1] assert byte_indexes == [0, 1] s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2] assert byte_indexes == [0, 2] s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3] assert byte_indexes == [0, 3] s = " " + x + " " # example: # " a " # 0123 # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 3] assert byte_indexes == [0, 3] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3, 4] assert byte_indexes == [0, 3, 4] s = " " + x + " " + x # example: # " a a" # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 2] assert byte_indexes == [0, 2] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2, 4] assert byte_indexes == [0, 2, 4] # Two byte characters for x in ["þ", "æ", "á"]: s = x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0], s assert byte_indexes == [0], s toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 1], s assert byte_indexes == [0, 2], s s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2] assert byte_indexes == [0, 3] s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3] assert byte_indexes == [0, 4] s = " " + x + " " # example bytes: # " þ_ " # 01234 # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 3] assert byte_indexes == [0, 4] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3, 4] assert byte_indexes == [0, 4, 5] s = " " + x + " " + x # example bytes: # " þ_ þ_" # 012345 # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 2] assert byte_indexes == [0, 3] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2, 4] assert byte_indexes == [0, 3, 6] # Two character characters # These strings contain two unicode code points that are rendered as one letter. # They are counted as two characters in python. # In addition the accent and umlaut characters are two bytes. for x in ["a"+ACCENT, "o"+UMLAUT]: s = x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0], s assert byte_indexes == [0], s toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2], s assert byte_indexes == [0, 3], s s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3] assert byte_indexes == [0, 4] s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 4] assert byte_indexes == [0, 5] s = " " + x + " " # example chars: # " a´ " # 01234 # ^ ^^ # example bytes: # " a´_ " # 012345 # ^ ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 4] assert byte_indexes == [0, 5] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 4, 5] assert byte_indexes == [0, 5, 6] s = " " + x + " " + x # example chars: # " a´ a´" # 012345 # ^ ^ # example bytes: # " a´_ a´_" # 01234567 # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 3] assert byte_indexes == [0, 4] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3, 6] assert byte_indexes == [0, 4, 8] # The em-dash is 3 bytes for x in [EM_DASH]: s = x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0], s assert byte_indexes == [0], s toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 1], s assert byte_indexes == [0, 3], s s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2] assert byte_indexes == [0, 4] s = " " + x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0] assert byte_indexes == [0] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3] assert byte_indexes == [0, 5] s = " " + x + " " # example chars: # " a " # 0123 # ^ ^ # example bytes: # " a__ " # 012345 # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 3] assert byte_indexes == [0, 5] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 3, 4] assert byte_indexes == [0, 5, 6] s = " " + x + " " + x # example chars: # " a a" # 0123 # ^ ^ # example bytes: # " a__ a__" # 01234567 # ^ ^ toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 2] assert byte_indexes == [0, 4] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2, 4] assert byte_indexes == [0, 4, 8] def test_larger_case() -> None: s = "Þessi setning er í lengra lagi og er með bæði eins og tveggja bæta stafi." # 0123456789012345678901234567890123456789012345678901234567890123456789012 # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # x x x xx x toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 5, 13, 16, 18, 25, 30, 33, 36, 40, 45, 50, 53, 61, 66, 72] assert byte_indexes == [0, 6, 14, 17, 20, 27, 32, 35, 38, 43, 50, 55, 58, 66, 72, 78] toks = tokenizer.parse_tokens([s]) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 5, 13, 16, 18, 25, 30, 33, 36, 40, 45, 50, 53, 61, 66, 72, 73] assert byte_indexes == [0, 6, 14, 17, 20, 27, 32, 35, 38, 43, 50, 55, 58, 66, 72, 78, 79] def test_iterator_cases() -> None: s = ["Þessi ", "setning ", "er ", "í ", "lengra ", "lagi ", "og ", "er ", "með ", "bæði ", "eins ", "og ", "tveggja ", "bæta ", "stafi."] # (char and byte indexes in a similar test above) toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 5, 13, 16, 18, 25, 30, 33, 36, 40, 45, 50, 53, 61, 66, 72] assert byte_indexes == [0, 6, 14, 17, 20, 27, 32, 35, 38, 43, 50, 55, 58, 66, 72, 78] toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 5, 13, 16, 18, 25, 30, 33, 36, 40, 45, 50, 53, 61, 66, 72, 73] assert byte_indexes == [0, 6, 14, 17, 20, 27, 32, 35, 38, 43, 50, 55, 58, 66, 72, 78, 79] s = ["Stutt setning.", "", "Önnur setning."] # 01234567890123 45678901234567 # ^ ^ ^ ^ ^ ^ # x toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 5, 13, 14, 19, 27] assert byte_indexes == [0, 5, 13, 14, 20, 28] toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 5, 13, 14, 19, 27, 28] assert byte_indexes == [0, 5, 13, 14, 20, 28, 29] # parse_tokens does some implentation-detail-stuff here. Use tokenize instead. s = [" Stutt setning. ", "\n \n", "Önnur setning."] # 0123456789012345 6 78 90123456789012 # ^ ^ ^^ ^ ^ # x toks = tokenizer.tokenize(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 6, 14, 15, 24, 32] assert byte_indexes == [0, 6, 14, 15, 25, 33] toks = tokenizer.tokenize(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 6, 14, 15, 24, 32, 33] assert byte_indexes == [0, 6, 14, 15, 25, 33, 34] def test_paragraph_markers() -> None: s = "[[Stutt setning.]][[]][[Önnur setning.]]" # 012345678901234567890123456789012345678901234567 # ^^^ ^ ^^ ^ ^ ^ ^ ^ ^^ # x toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 2, 7, 15, 16, 18, 20, 22, 24, 29, 37, 38] assert byte_indexes == [0, 2, 7, 15, 16, 18, 20, 22, 24, 30, 38, 39] toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2, 7, 15, 16, 18, 20, 22, 24, 29, 37, 38, 40] assert byte_indexes == [0, 2, 7, 15, 16, 18, 20, 22, 24, 30, 38, 39, 41] # The tokenize functions does stuff to paragraph markers. Test that the # indexes are properly calculated after that. # Note that the text of the dropped empty paragraph markers disappears. s = "[[Stutt setning.]][[]][[Önnur setning.]]" # 012345678901234567890123456789012345678901234567 # ^ ^ ^ ^^ ^ ^ ^ ^^ # x toks = tokenizer.tokenize(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 2, 7, 15, 16, 18, 24, 29, 37, 38] assert byte_indexes == [0, 2, 7, 15, 16, 18, 24, 30, 38, 39] toks = tokenizer.tokenize(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 2, 7, 15, 16, 18, 24, 29, 37, 38, 40] assert byte_indexes == [0, 2, 7, 15, 16, 18, 24, 30, 38, 39, 41] def test_composite_phrases() -> None: s = "Orða- og tengingasetning." # 0123456789012345678901234 # ^ ^^ ^ ^ # x toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 4, 5, 8, 24] assert byte_indexes == [0, 5, 6, 9, 25] toks = tokenizer.parse_tokens(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 4, 5, 8, 24, 25] assert byte_indexes == [0, 5, 6, 9, 25, 26] # The whole thing gets squished together into a single token. s = "Orða- og tengingasetning." # 0123456789012345678901234 # ^ ^ # x toks = tokenizer.tokenize(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 24] assert byte_indexes == [0, 25] toks = tokenizer.tokenize(s) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 24, 25] assert byte_indexes == [0, 25, 26] def test_lengthening_substitutions() -> None: s = "Þetta er 3ji báturinn!" # 0123456789012345678901 # ^ ^ ^ ^ ^ # x x # ! lengthening happens here (3ji->þriðji) toks = tokenizer.parse_tokens(s, handle_kludgy_ordinals=tokenizer.KLUDGY_ORDINALS_MODIFY) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 5, 8, 12, 21] assert byte_indexes == [0, 6, 9, 13, 23] toks = tokenizer.parse_tokens(s, handle_kludgy_ordinals=tokenizer.KLUDGY_ORDINALS_MODIFY) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 5, 8, 12, 21, 22] assert byte_indexes == [0, 6, 9, 13, 23, 24] def test_converted_measurements() -> None: s = "Stillið ofninn á 12° C til að baka kökuna." # 012345678901234567890123456789012345678901 # ^ ^ ^ ^ ^ ^ ^ ^ ^ # x x x x x toks = tokenizer.tokenize(s, convert_measurements=True) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks) assert char_indexes == [0, 7, 14, 16, 22, 26, 29, 34, 41] assert byte_indexes == [0, 8, 15, 18, 25, 29, 33, 38, 46] toks = tokenizer.tokenize(s, convert_measurements=True) char_indexes, byte_indexes = tokenizer.calculate_indexes(toks, last_is_end=True) assert char_indexes == [0, 7, 14, 16, 22, 26, 29, 34, 41, 42] assert byte_indexes == [0, 8, 15, 18, 25, 29, 33, 38, 46, 47] def test_compound() -> None: s = " Katrín Júlíusdóttir var iðnaðar- \n\t og \t\t viðskiptaráðherra" tlist = list(tokenizer.tokenize(s)) assert sum(len(t.original or "") for t in tlist) == len(s)
21,320
39.611429
141
py
Tokenizer
Tokenizer-master/test/test_tokenizer.py
# type: ignore """ test_tokenizer.py Tests for Tokenizer module Copyright (C) 2022 by Miðeind ehf. Original author: Vilhjálmur Þorsteinsson This software is licensed under the MIT License: 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. """ from typing import Any, Iterable, Iterator, List, Tuple, Union, cast import tokenizer as t from tokenizer.definitions import BIN_Tuple, ValType TOK = t.TOK Tok = t.Tok TestCase = Union[Tuple[str, int], Tuple[str, int, ValType], Tuple[str, List[Tok]]] def strip_originals(tokens: List[Tok]) -> List[Tok]: """Remove origin tracking info from a list of tokens. This is useful for simplifying tests where we don't care about tracking origins. XXX: This could be removed if we get a feature to disable origin tracking during tokenization. """ for t in tokens: t.original = None t.origin_spans = None return tokens def get_text_and_norm(orig: str) -> Tuple[str, str]: toklist = list(t.tokenize(orig)) return t.text_from_tokens(toklist), t.normalized_text_from_tokens(toklist) def test_single_tokens() -> None: TEST_CASES = [ (".", TOK.PUNCTUATION), (",", TOK.PUNCTUATION), ("!", TOK.PUNCTUATION), ('"', [Tok(TOK.PUNCTUATION, "“", None)]), ("13:45", [Tok(TOK.TIME, "13:45", (13, 45, 0))]), ( "13:450", [ Tok(TOK.NUMBER, "13", (13, None, None)), Tok(TOK.PUNCTUATION, ":", None), Tok(TOK.NUMBER, "450", (450, None, None)), ], ), ("kl. 13:45", [Tok(TOK.TIME, "kl. 13:45", (13, 45, 0))]), ("klukkan 13:45", [Tok(TOK.TIME, "klukkan 13:45", (13, 45, 0))]), ("Klukkan 13:45", [Tok(TOK.TIME, "Klukkan 13:45", (13, 45, 0))]), ("hálftólf", [Tok(TOK.TIME, "hálftólf", (11, 30, 0))]), ("kl. hálfátta", [Tok(TOK.TIME, "kl. hálfátta", (7, 30, 0))]), ("kl. hálf átta", [Tok(TOK.TIME, "kl. hálf átta", (7, 30, 0))]), ("klukkan hálfátta", [Tok(TOK.TIME, "klukkan hálfátta", (7, 30, 0))]), ("klukkan hálf átta", [Tok(TOK.TIME, "klukkan hálf átta", (7, 30, 0))]), ("klukkan þrjú", [Tok(TOK.TIME, "klukkan þrjú", (3, 00, 0))]), ("Kl. hálfátta", [Tok(TOK.TIME, "Kl. hálfátta", (7, 30, 0))]), ("Kl. hálf átta", [Tok(TOK.TIME, "Kl. hálf átta", (7, 30, 0))]), ("Klukkan hálfátta", [Tok(TOK.TIME, "Klukkan hálfátta", (7, 30, 0))]), ("Klukkan hálf átta", [Tok(TOK.TIME, "Klukkan hálf átta", (7, 30, 0))]), ("Klukkan þrjú", [Tok(TOK.TIME, "Klukkan þrjú", (3, 00, 0))]), ("17/6", [Tok(TOK.DATEREL, "17/6", (0, 6, 17))]), ( "17.6.", [ Tok(TOK.NUMBER, "17.6", (17.6, None, None)), Tok(TOK.PUNCTUATION, ".", None), ], ), ( "17.16.", [ Tok(TOK.NUMBER, "17.16", (17.16, None, None)), Tok(TOK.PUNCTUATION, ".", None), ], ), ( "30.9.", [ Tok(TOK.NUMBER, "30.9", (30.9, None, None)), Tok(TOK.PUNCTUATION, ".", None), ], ), ( "31.9.", [ Tok(TOK.NUMBER, "31.9", (31.9, None, None)), Tok(TOK.PUNCTUATION, ".", None), ], ), ( "17/60", [ Tok(TOK.NUMBER, "17", (17, None, None)), Tok(TOK.PUNCTUATION, "/", None), Tok(TOK.NUMBER, "60", (60, None, None)), ], ), ("3. maí", [Tok(TOK.DATEREL, "3. maí", (0, 5, 3))]), ("Ágúst", TOK.WORD), # Not month name if capitalized ("13. ágúst", [Tok(TOK.DATEREL, "13. ágúst", (0, 8, 13))]), ("nóvember 1918", [Tok(TOK.DATEREL, "nóvember 1918", (1918, 11, 0))]), ( "nóvember 19180", [ Tok(TOK.DATEREL, "nóvember", (0, 11, 0)), Tok(TOK.NUMBER, "19180", (19180, None, None)), ], ), ( "sautjánda júní", [ Tok(TOK.WORD, "sautjánda", None), Tok(TOK.DATEREL, "júní", (0, 6, 0)), ], ), ( "sautjánda júní 1811", [ Tok(TOK.WORD, "sautjánda", None), Tok(TOK.DATEREL, "júní 1811", (1811, 6, 0)), ], ), ( "Sautjánda júní árið 1811", [ Tok(TOK.WORD, "Sautjánda", None), Tok(TOK.DATEREL, "júní árið 1811", (1811, 6, 0)), ], ), ( "Fimmtánda mars árið 44 f.Kr.", [ Tok(TOK.WORD, "Fimmtánda", None), Tok(TOK.DATEREL, "mars árið 44 f.Kr.", (-44, 3, 0)), ], ), ("17/6/2013", [Tok(TOK.DATEABS, "17/6/2013", (2013, 6, 17))]), ( "17/6/20130", [ Tok(TOK.DATEREL, "17/6", (0, 6, 17)), Tok(TOK.PUNCTUATION, "/", None), Tok(TOK.NUMBER, "20130", (20130, None, None)), ], ), ("2013-06-17", [Tok(TOK.DATEABS, "2013-06-17", (2013, 6, 17))]), ("2013/06/17", [Tok(TOK.DATEABS, "2013/06/17", (2013, 6, 17))]), ( "2013-06-170", [ Tok(TOK.YEAR, "2013", 2013), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.NUMBER, "06", (6, None, None)), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.NUMBER, "170", (170, None, None)), ], ), ("2013", [Tok(TOK.YEAR, "2013", 2013)]), ("20130", [Tok(TOK.NUMBER, "20130", (20130, None, None))]), ("874 e.Kr.", [Tok(TOK.YEAR, "874 e.Kr.", 874)]), ("2013 f.Kr.", [Tok(TOK.YEAR, "2013 f.Kr.", -2013)]), ("árið 2013", [Tok(TOK.YEAR, "árið 2013", 2013)]), ("árinu 874", [Tok(TOK.YEAR, "árinu 874", 874)]), ("ársins 2013", [Tok(TOK.YEAR, "ársins 2013", 2013)]), ("ársins 320 f.Kr.", [Tok(TOK.YEAR, "ársins 320 f.Kr.", -320)]), ("213", [Tok(TOK.NUMBER, "213", (213, None, None))]), ("2.013", [Tok(TOK.NUMBER, "2.013", (2013, None, None))]), ("2,013", [Tok(TOK.NUMBER, "2,013", (2.013, None, None))]), ("2.013,45", [Tok(TOK.NUMBER, "2.013,45", (2013.45, None, None))]), ( "2.0134,45", [ Tok(TOK.NUMBER, "2.0134", (2.0134, None, None)), Tok(TOK.PUNCTUATION, ",", None), Tok(TOK.NUMBER, "45", (45, None, None)), ], ), ("2,013.45", [Tok(TOK.NUMBER, "2,013.45", (2013.45, None, None))]), ( "2,0134.45", [ Tok(TOK.NUMBER, "2", (2, None, None)), Tok(TOK.PUNCTUATION, ",", None), Tok(TOK.NUMBER, "0134.45", (134.45, None, None)), ], ), ("1/2", [Tok(TOK.NUMBER, "1/2", (0.5, None, None))]), ("1/20", [Tok(TOK.DATEREL, "1/20", (0, 1, 20))]), ( "1/37", [ Tok(TOK.NUMBER, "1", (1, None, None)), Tok(TOK.PUNCTUATION, "/", None), Tok(TOK.NUMBER, "37", (37, None, None)), ], ), ("1/4", [Tok(TOK.NUMBER, "1/4", (0.25, None, None))]), ("¼", [Tok(TOK.NUMBER, "¼", (0.25, None, None))]), ("2⅞", [Tok(TOK.NUMBER, "2⅞", (2.875, None, None))]), ("33⅗", [Tok(TOK.NUMBER, "33⅗", (33.6, None, None))]), ("1sti", [Tok(TOK.WORD, "1sti", None)]), ("4ðu", [Tok(TOK.WORD, "4ðu", None)]), ("2svar", [Tok(TOK.WORD, "2svar", None)]), ("4ra", [Tok(TOK.WORD, "4ra", None)]), ("2ja", [Tok(TOK.WORD, "2ja", None)]), ("þjóðhátíð", TOK.WORD), ("Þjóðhátíð", TOK.WORD), ("marg-ítrekað", TOK.WORD), ("full-ítarlegur", TOK.WORD), ("hálf-óviðbúinn", TOK.WORD), ("750 þús.kr.", [Tok(TOK.AMOUNT, "750 þús.kr.", (750e3, "ISK", None, None))]), ("750 þús.kr", [Tok(TOK.AMOUNT, "750 þús.kr", (750e3, "ISK", None, None))]), ("10 m.kr", [Tok(TOK.AMOUNT, "10 m.kr", (1e7, "ISK", None, None))]), ( "m.kr.", [ Tok( TOK.WORD, "m.kr.", [BIN_Tuple("milljónir króna", 0, "kvk", "skst", "m.kr.", "-")], ), ], ), ( "ma.kr.", [ Tok( TOK.WORD, "ma.kr.", [BIN_Tuple("milljarðar króna", 0, "kk", "skst", "ma.kr.", "-")], ), ], ), ( "30,7 mö.kr.", [Tok(TOK.AMOUNT, "30,7 mö.kr.", (30.7e9, "ISK", None, None))], ), ("sjötíu", [Tok(TOK.WORD, "sjötíu", None)]), ("hundrað", [Tok(TOK.WORD, "hundrað", None)]), ("hundruð", [Tok(TOK.WORD, "hundruð", None)]), ("þúsund", [Tok(TOK.WORD, "þúsund", None)]), ("milljón", [Tok(TOK.WORD, "milljón", None)]), ("milljarður", [Tok(TOK.WORD, "milljarður", None)]), ("billjón", [Tok(TOK.WORD, "billjón", None)]), ( "kvintilljón", [Tok(TOK.WORD, "kvintilljón", None)], ), ( "t.d.", [ Tok( TOK.WORD, "t.d.", [BIN_Tuple("til dæmis", 0, "ao", "frasi", "t.d.", "-")], ) ], ), ("hr.", TOK.WORD, [BIN_Tuple("herra", 0, "kk", "skst", "hr.", "-")]), ( "dags. 10/7", [ Tok( TOK.WORD, "dags.", [ BIN_Tuple("dagsetja", 0, "so", "skst", "dags.", "-"), BIN_Tuple("dagsettur", 0, "lo", "skst", "dags.", "-"), ], ), Tok(TOK.DATEREL, "10/7", (0, 7, 10)), ], ), ("Hr.", TOK.WORD, [BIN_Tuple("herra", 0, "kk", "skst", "hr.", "-")]), ( "nk.", [ Tok( TOK.WORD, "nk.", [BIN_Tuple("næstkomandi", 0, "lo", "skst", "nk.", "-")], ), ], ), ( "sl.", [ Tok( TOK.WORD, "sl.", [BIN_Tuple("síðastliðinn", 0, "lo", "skst", "sl.", "-")], ), ], ), ( "o.s.frv.", [ Tok( TOK.WORD, "o.s.frv.", [BIN_Tuple("og svo framvegis", 0, "ao", "frasi", "o.s.frv.", "-")], ), ], ), ("BSRB", TOK.WORD), ("stjórnskipunar- og eftirlitsnefnd", TOK.WORD), ("dómsmála-, viðskipta- og iðnaðarráðherra", TOK.WORD), ("dómsmála- viðskipta- og iðnaðarráðherra", TOK.WORD), ("ferðamála- dómsmála- viðskipta- og iðnaðarráðherra", TOK.WORD), ("ferðamála-, dómsmála-, viðskipta- og iðnaðarráðherra", TOK.WORD), # Test backoff if composition is not successful ( "ferðamála- ráðherra", [ Tok(TOK.WORD, "ferðamála", None), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.WORD, "ráðherra", None), ], ), ( "ferðamála-, iðnaðar- ráðherra", [ Tok(TOK.WORD, "ferðamála", None), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.PUNCTUATION, ",", None), Tok(TOK.WORD, "iðnaðar", None), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.WORD, "ráðherra", None), ], ), ( "ferðamála- og 500", [ Tok(TOK.WORD, "ferðamála", None), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.WORD, "og", None), Tok(TOK.NUMBER, "500", (500, None, None)), ], ), ("591213-1480", TOK.SSN), ( "591214-1480", [ Tok(TOK.NUMBER, "591214", (591214, None, None)), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.NUMBER, "1480", (1480, None, None)), ], ), ( "591213-14803", [ Tok(TOK.NUMBER, "591213", (591213, None, None)), Tok(TOK.PUNCTUATION, "-", None), Tok(TOK.NUMBER, "14803", (14803, None, None)), ], ), ("9000000", TOK.NUMBER), ("1234567", TOK.NUMBER), ("1965", TOK.YEAR), ("525-4764", [Tok(TOK.TELNO, "525-4764", ("525-4764", "354"))]), ("4204200", [Tok(TOK.TELNO, "4204200", ("420-4200", "354"))]), ("699 2422", [Tok(TOK.TELNO, "699 2422", ("699-2422", "354"))]), ("354 699 2422", [Tok(TOK.TELNO, "354 699 2422", ("699-2422", "354"))]), ("+354 699 2422", [Tok(TOK.TELNO, "+354 699 2422", ("699-2422", "+354"))]), ("12,3%", TOK.PERCENT), ("12,3 %", [Tok(TOK.PERCENT, "12,3 %", (12.3, None, None))]), ("http://www.greynir.is", TOK.URL), ("https://greynir.is", TOK.URL), ("https://pypi.org/project/tokenizer/", TOK.URL), ("http://tiny.cc/28695y", TOK.URL), ("www.greynir.is", TOK.DOMAIN), ("mbl.is", TOK.DOMAIN), ("RÚV.is", TOK.DOMAIN), ("Eitthvað.org", TOK.DOMAIN), ("9gag.com", TOK.DOMAIN), ("SannLeikurinn.com", TOK.DOMAIN), ("ílénumeruíslenskir.stafir-leyfilegir.net", TOK.DOMAIN), ("#MeToo", TOK.HASHTAG), ("#12stig12", TOK.HASHTAG), ("#égermeðíslenskastafi", TOK.HASHTAG), ("#", TOK.PUNCTUATION), ( "19/3/1977 14:56:10", [Tok(TOK.TIMESTAMPABS, "19/3/1977 14:56:10", (1977, 3, 19, 14, 56, 10))], ), ( "19/3/1977 kl. 14:56:10", [ Tok( TOK.TIMESTAMPABS, "19/3/1977 kl. 14:56:10", (1977, 3, 19, 14, 56, 10), ) ], ), ("¥212,11", TOK.AMOUNT), ("EUR 200", TOK.AMOUNT), ("kr. 5.999", TOK.AMOUNT), ("$472,64", [Tok(TOK.AMOUNT, "$472,64", (472.64, "USD", None, None))]), ("€472,64", [Tok(TOK.AMOUNT, "€472,64", (472.64, "EUR", None, None))]), ("£199,99", [Tok(TOK.AMOUNT, "£199,99", (199.99, "GBP", None, None))]), ("$472.64", [Tok(TOK.AMOUNT, "$472.64", (472.64, "USD", None, None))]), ("€472.64", [Tok(TOK.AMOUNT, "€472.64", (472.64, "EUR", None, None))]), ("£199.99", [Tok(TOK.AMOUNT, "£199.99", (199.99, "GBP", None, None))]), ("$1,472.64", [Tok(TOK.AMOUNT, "$1,472.64", (1472.64, "USD", None, None))]), ("€3,472.64", [Tok(TOK.AMOUNT, "€3,472.64", (3472.64, "EUR", None, None))]), ("£5,199.99", [Tok(TOK.AMOUNT, "£5,199.99", (5199.99, "GBP", None, None))]), ("$1.472,64", [Tok(TOK.AMOUNT, "$1.472,64", (1472.64, "USD", None, None))]), ("€3.472,64", [Tok(TOK.AMOUNT, "€3.472,64", (3472.64, "EUR", None, None))]), ("£5.199,99", [Tok(TOK.AMOUNT, "£5.199,99", (5199.99, "GBP", None, None))]), ("$1,472", [Tok(TOK.AMOUNT, "$1,472", (1.472, "USD", None, None))]), ("€3,472", [Tok(TOK.AMOUNT, "€3,472", (3.472, "EUR", None, None))]), ("£5,199", [Tok(TOK.AMOUNT, "£5,199", (5.199, "GBP", None, None))]), ("$1.472", [Tok(TOK.AMOUNT, "$1.472", (1472, "USD", None, None))]), ("€3.472", [Tok(TOK.AMOUNT, "€3.472", (3472, "EUR", None, None))]), ("£5.199", [Tok(TOK.AMOUNT, "£5.199", (5199, "GBP", None, None))]), ("$1965", [Tok(TOK.AMOUNT, "$1965", (1965.0, "USD", None, None))]), ("€1965", [Tok(TOK.AMOUNT, "€1965", (1965.0, "EUR", None, None))]), ("¥1965", [Tok(TOK.AMOUNT, "¥1965", (1965.0, "JPY", None, None))]), ("[email protected]", TOK.EMAIL), ("[email protected]", TOK.EMAIL), ("[email protected]", TOK.EMAIL), ("7a", [Tok(TOK.NUMWLETTER, "7a", (7, "a"))]), ("33B", [Tok(TOK.NUMWLETTER, "33B", (33, "B"))]), ("1129c", [Tok(TOK.NUMWLETTER, "1129c", (1129, "c"))]), ("1965c", [Tok(TOK.NUMWLETTER, "1965c", (1965, "c"))]), ("7l", [Tok(TOK.MEASUREMENT, "7l", ("m³", 0.007))]), ("1965l", [Tok(TOK.MEASUREMENT, "1965l", ("m³", 1.965))]), ("17 ltr", [Tok(TOK.MEASUREMENT, "17 ltr", ("m³", 17.0e-3))]), ("150m", [Tok(TOK.MEASUREMENT, "150m", ("m", 150))]), ("1965m", [Tok(TOK.MEASUREMENT, "1965m", ("m", 1965))]), ("220V", [Tok(TOK.MEASUREMENT, "220V", ("V", 220))]), ( "220Volt", [Tok(TOK.NUMBER, "220", (220, None, None)), Tok(TOK.WORD, "Volt", None)], ), ("11A", [Tok(TOK.MEASUREMENT, "11A", ("A", 11))]), ("100 mm", [Tok(TOK.MEASUREMENT, "100 mm", ("m", 0.1))]), ("30,7°C", [Tok(TOK.MEASUREMENT, "30,7°C", ("K", 273.15 + 30.7))]), ("30,7 °C", [Tok(TOK.MEASUREMENT, "30,7 °C", ("K", 273.15 + 30.7))]), ("30,7° C", [Tok(TOK.MEASUREMENT, "30,7° C", ("K", 273.15 + 30.7))]), ("30,7 ° C", [Tok(TOK.MEASUREMENT, "30,7 ° C", ("K", 273.15 + 30.7))]), ("32°F", [Tok(TOK.MEASUREMENT, "32°F", ("K", 273.15))]), ("32 °F", [Tok(TOK.MEASUREMENT, "32 °F", ("K", 273.15))]), ("32° F", [Tok(TOK.MEASUREMENT, "32° F", ("K", 273.15))]), ("32 ° F", [Tok(TOK.MEASUREMENT, "32 ° F", ("K", 273.15))]), ("1965°C", [Tok(TOK.MEASUREMENT, "1965°C", ("K", 273.15 + 1965.0))]), ("1965 °C", [Tok(TOK.MEASUREMENT, "1965 °C", ("K", 273.15 + 1965.0))]), ("1965° C", [Tok(TOK.MEASUREMENT, "1965° C", ("K", 273.15 + 1965.0))]), ("1965 ° C", [Tok(TOK.MEASUREMENT, "1965 ° C", ("K", 273.15 + 1965.0))]), ("180°", [Tok(TOK.MEASUREMENT, "180°", ("°", 180))]), ("180 °", [Tok(TOK.MEASUREMENT, "180 °", ("°", 180))]), ("6.500 kg", [Tok(TOK.MEASUREMENT, "6.500 kg", ("kg", 6.5e3))]), ("690 MW", [Tok(TOK.MEASUREMENT, "690 MW", ("W", 690e6))]), ("1800 MWst", [Tok(TOK.MEASUREMENT, "1800 MWst", ("J", 6480e9))]), ("1976kWst", [Tok(TOK.MEASUREMENT, "1976kWst", ("J", 7113.6e6))]), ("CO2", TOK.MOLECULE), ("CO", TOK.WORD), ("H2O", TOK.MOLECULE), ("B5", TOK.MOLECULE), ("H2SO4", TOK.MOLECULE), ("350-6678", TOK.SERIALNUMBER), ("123-456-7890", TOK.SERIALNUMBER), ("1-45-7890", TOK.SERIALNUMBER), ("1-800-1234", TOK.SERIALNUMBER), ("1-800-1234-545566", TOK.SERIALNUMBER), ] TEST_CASES_KLUDGY_MODIFY = [ ("1sti", [Tok(TOK.WORD, "fyrsti", None)]), ("4ðu", [Tok(TOK.WORD, "fjórðu", None)]), ("2svar", [Tok(TOK.WORD, "tvisvar", None)]), ("4ra", [Tok(TOK.WORD, "fjögurra", None)]), ("2ja", [Tok(TOK.WORD, "tveggja", None)]), ] TEST_CASES_KLUDGY_TRANSLATE = [ ("1sti", [Tok(TOK.ORDINAL, "1sti", 1)]), ("4ðu", [Tok(TOK.ORDINAL, "4ðu", 4)]), ("2svar", [Tok(TOK.WORD, "2svar", None)]), ("4ra", [Tok(TOK.WORD, "4ra", None)]), ] TEST_CASES_CONVERT_TELNOS = [ ("525-4764", TOK.TELNO), ("4204200", [Tok(TOK.TELNO, "4204200", ("420-4200", "354"))]), ("699 2422", [Tok(TOK.TELNO, "699 2422", ("699-2422", "354"))]), ("699 2012", [Tok(TOK.TELNO, "699 2012", ("699-2012", "354"))]), ("354 699 2012", [Tok(TOK.TELNO, "354 699 2012", ("699-2012", "354"))]), ("+354 699 2012", [Tok(TOK.TELNO, "+354 699 2012", ("699-2012", "+354"))]), ] TEST_CASES_CONVERT_NUMBERS = [ ("$472,64", [Tok(TOK.AMOUNT, "$472,64", (472.64, "USD", None, None))]), ("€472,64", [Tok(TOK.AMOUNT, "€472,64", (472.64, "EUR", None, None))]), ("£199,99", [Tok(TOK.AMOUNT, "£199,99", (199.99, "GBP", None, None))]), ("$472.64", [Tok(TOK.AMOUNT, "$472,64", (472.64, "USD", None, None))]), ("€472.64", [Tok(TOK.AMOUNT, "€472,64", (472.64, "EUR", None, None))]), ("£199.99", [Tok(TOK.AMOUNT, "£199,99", (199.99, "GBP", None, None))]), ("$1,472.64", [Tok(TOK.AMOUNT, "$1.472,64", (1472.64, "USD", None, None))]), ("€3,472.64", [Tok(TOK.AMOUNT, "€3.472,64", (3472.64, "EUR", None, None))]), ("£5,199.99", [Tok(TOK.AMOUNT, "£5.199,99", (5199.99, "GBP", None, None))]), ("$1.472,64", [Tok(TOK.AMOUNT, "$1.472,64", (1472.64, "USD", None, None))]), ("€3.472,64", [Tok(TOK.AMOUNT, "€3.472,64", (3472.64, "EUR", None, None))]), ("£5.199,99", [Tok(TOK.AMOUNT, "£5.199,99", (5199.99, "GBP", None, None))]), ("$1,472", [Tok(TOK.AMOUNT, "$1,472", (1.472, "USD", None, None))]), ("€3,472", [Tok(TOK.AMOUNT, "€3,472", (3.472, "EUR", None, None))]), ("£5,199", [Tok(TOK.AMOUNT, "£5,199", (5.199, "GBP", None, None))]), ("$1.472", [Tok(TOK.AMOUNT, "$1.472", (1472, "USD", None, None))]), ("€3.472", [Tok(TOK.AMOUNT, "€3.472", (3472, "EUR", None, None))]), ("£5.199", [Tok(TOK.AMOUNT, "£5.199", (5199, "GBP", None, None))]), ] TEST_CASES_COALESCE_PERCENT = [ ("12,3prósent", [Tok(TOK.PERCENT, "12,3 prósent", (12.3, None, None))]), ("12,3 prósent", TOK.PERCENT), ( "12,3hundraðshlutar", [Tok(TOK.PERCENT, "12,3 hundraðshlutar", (12.3, None, None))], ), ("12,3 hundraðshlutar", TOK.PERCENT), ("12,3 prósentustig", TOK.PERCENT), ] TEST_CASES_CONVERT_MEASUREMENTS = [ ("200° C", [Tok(TOK.MEASUREMENT, "200 °C", ("K", 473.15))]), ("80° F", [Tok(TOK.MEASUREMENT, "80 °F", ("K", 299.8166666666667))]), ] def run_test(test_cases: Iterable[TestCase], **options: Any) -> None: for test_case in test_cases: if len(test_case) == 3: txt, kind, val = cast(Tuple[str, int, ValType], test_case) c = [Tok(kind, txt, val)] elif isinstance(test_case[1], list): txt, c = cast(Tuple[str, List[Tok]], test_case) else: txt, kind = cast(Tuple[str, int], test_case) c = [Tok(kind, txt, None)] l = list(t.tokenize(txt, **options)) assert len(l) == len(c) + 2, repr(l) assert l[0].kind == TOK.S_BEGIN, repr(l[0]) assert l[-1].kind == TOK.S_END, repr(l[-1]) for tok, check in zip(l[1:-1], c): assert tok.kind == check.kind, ( tok.txt + ": " + repr(TOK.descr[tok.kind]) + " " + repr(TOK.descr[check.kind]) ) if check.kind == TOK.PUNCTUATION and check.val is None: # Check normalized form of token assert tok.punctuation == check.txt, ( tok.punctuation + " != " + check.txt ) else: assert tok.txt == check.txt, tok.txt + " != " + check.txt if check.val is not None: if check.kind == TOK.WORD: # Test set equivalence, since the order of word meanings # is not deterministic assert set(cast(List[BIN_Tuple], tok.val) or []) == set( cast(List[BIN_Tuple], check.val) or [] ), (repr(tok.val) + " != " + repr(check.val)) else: assert tok.val == check.val, ( repr(tok.val) + " != " + repr(check.val) ) run_test(cast(Iterable[TestCase], TEST_CASES)) run_test(cast(Iterable[TestCase], TEST_CASES_CONVERT_TELNOS)) run_test(TEST_CASES_KLUDGY_MODIFY, handle_kludgy_ordinals=t.KLUDGY_ORDINALS_MODIFY) run_test( TEST_CASES_KLUDGY_TRANSLATE, handle_kludgy_ordinals=t.KLUDGY_ORDINALS_TRANSLATE ) run_test(TEST_CASES_CONVERT_NUMBERS, convert_numbers=True) run_test( cast(Iterable[TestCase], TEST_CASES_COALESCE_PERCENT), coalesce_percent=True ) run_test(TEST_CASES_CONVERT_MEASUREMENTS, convert_measurements=True) def test_sentences() -> None: KIND = { "B": TOK.S_BEGIN, "E": TOK.S_END, "W": TOK.WORD, "P": TOK.PUNCTUATION, "T": TOK.TIME, "DR": TOK.DATEREL, "DA": TOK.DATEABS, "Y": TOK.YEAR, "N": TOK.NUMBER, "NL": TOK.NUMWLETTER, "TEL": TOK.TELNO, "PC": TOK.PERCENT, "U": TOK.URL, "O": TOK.ORDINAL, "TS": TOK.TIMESTAMP, "C": TOK.CURRENCY, "A": TOK.AMOUNT, "M": TOK.EMAIL, "ME": TOK.MEASUREMENT, "DM": TOK.DOMAIN, "HT": TOK.HASHTAG, "K": TOK.SSN, "MO": TOK.MOLECULE, "SE": TOK.SERIALNUMBER, "X": TOK.UNKNOWN, } def test_sentence(text: str, expected: str, **options: Any) -> None: exp = expected.split() s = list(t.tokenize(text, **options)) assert len(s) == len(exp) for token, e in zip(s, exp): assert e in KIND ekind = KIND[e] assert token.kind == ekind, "%s should be %s, not %s" % ( token.txt, TOK.descr[ekind], TOK.descr[token.kind], ) test_sentence( " Málinu var vísað til stjórnskipunar- og eftirlitsnefndar " "skv. 3. gr. XVII. kafla laga nr. 10/2007 þann 3. janúar 2010.", "B W W W W W " "W O W O W W W N P Y W DA P E", ) test_sentence( " Góðan daginn! Ég á 10.000 kr. í vasanum, €100 og $40.Gengi USD er 103,45. " "Í dag er 10. júlí. Klukkan er 15:40 núna.Ég fer kl. 13 niður á Hlemm o.s.frv. ", "B W W P E B W W A W W P A W A P E B W W W N P E " "B W W W DR P E B W W T W P E B W W T W W W W E", ) test_sentence( "Jæja, bjór í Bretlandi kominn upp í £4.29 (ISK 652). Dýrt! Í Japan er hann bara ¥600.", "B W P W W W W W W A P A P P E B W P E B W W W W W A P E", ) test_sentence( "Almennt verð er krónur 9.900,- en kr. 8.000,- fyrir félagsmenn. Maður borgar 99 kr. 10 sinnum. " "USD900 fyrir Bandaríkjamenn en 700 EUR fyrir Þjóðverja. Ég hef spilað RISK 100 sinnum.", "B W W W A P P W A P P W W P E B W W A N W P E " "B A W W W A W W P E B W W W W N W P E", ) # '\u00AD': soft hyphen # '\u200B': zero-width space # '\uFEFF': zero-width non-breaking space test_sentence( "Lands\u00ADbank\u00ADinn er í 98\u200B,2 pró\u00ADsent eigu\u200B íslenska rík\uFEFFis\u00ADins.", "B W W W PC W W W P E", coalesce_percent=True, ) test_sentence( "Lands\u00ADbank\u00ADinn er í 98\u200B,2 pró\u00ADsent eigu\u200B íslenska rík\uFEFFis\u00ADins.", "B W W W N W W W W P E", coalesce_percent=False, ) test_sentence( "Málið um BSRB gekk marg-ítrekað til stjórnskipunar- og eftirlitsnefndar í 10. sinn " "skv. XVII. kafla þann 24. september 2015 nk. Ál-verið notar 60 MWst á ári.", "B W W W W W W W W O W " "W O W W DA W E B W W ME W W P E", ) test_sentence( "Ég er t.d. með tölvupóstfangið [email protected], vefföngin " "http://greynir.is og https://greynir.is, og síma 6638999. Hann gaf mér 1000 kr. Ég keypti mér 1/2 kaffi. " "Það er hægt að ná í mig í s 623 7892, eða vinnusíma, 7227979 eða eitthvað.", "B W W W W W M P W " "U W U P W W TEL P E B W W W A E B W W W N W P E " "B W W W W W W W W W TEL P W W P TEL W W P E", ) test_sentence( "Þetta voru 300 1000 kílóa pokar, og 4000 500 kílóa pokar. " "Einnig 932 800 kílóa pokar, svo og 177 4455 millilítra skammtar.", "B W W N N W W P W N N W W P E " "B W N N W W P W W N N W W P E", ) test_sentence( "Skoðaðu vörunúmerin 000-1224 eða 121-2233. Hafðu síðan samband í síma 692 2073. " "Þeir voru 313 2012 en 916 árið 2013.", "B W W SE W SE P E B W W W W W TEL P E " "B W W N Y W N Y P E", ) test_sentence( "Hann starfaði við stofnunina árin 1944-50.", "B W W W W W Y P N P E", ) test_sentence( "Landnám er talið hafa hafist um árið 874 e.Kr. en óvissa er nokkur.", "B W W W W W W Y W W W W P E", ) test_sentence( 'Hitinn í "pottinum" var orðinn 30,7 °C þegar 2.000 l voru komnir í hann.', "B W W P W P W W ME W ME W W W W P E", ) test_sentence( "Skrifað var undir friðarsamninga í nóvember 1918. Júlíus Sesar var myrtur " "þann fimmtánda mars árið 44 f.Kr. og þótti harmdauði.", "B W W W W W DR P E B W W W W " "W W DR W W W P E", ) test_sentence( "1.030 hPa lægð gengur yfir landið árið 2019 e.Kr. Jógúrtin inniheldur 80 kcal.", "B ME W W W W Y E B W W ME P E", ) test_sentence( "Maður var lagður inn á deild 33C eftir handtöku á Bárugötu 14a þann nítjánda júlí 2016.", "B W W W W W W NL W W W W NL W W DR P E", ) test_sentence( "Þessir 10Milljón vírar með 20A straum kostuðu 3000ISK og voru geymdir á Hagamel á 2hæð.", "B W N W W W ME W W A W W W W W W N W P E", ) test_sentence( "Hitinn í dag var 32°C en á morgun verður hann 33° C og svo 37 °C.", "B W W W W ME W W W W W ME W W ME P E", ) test_sentence( "Hitinn í dag var 100,3°F en á morgun verður hann 102,7 ° F og svo 99.88 °F.", "B W W W W ME W W W W W ME W W ME P E", ) test_sentence( "Ég tók stefnu 45° til suðurs og svo 70°N en eftir það 88 ° vestur.", "B W W W ME W W W W ME W W W W ME W P E", ) test_sentence( "Byrjum á 2½ dl af rjóma því ¼-½ matskeið er ekki nóg. Helmingur er ½. Svarið er 42, ekki 41⅞.", "B W W ME W W W N P N W W W W P E B W W N P E B W W N P W N P E", ) test_sentence( "Ágúst bjó á hæð númer 13. Ágúst kunni vel við Ágúst í ágúst, enda var 12. ágúst. ÞAÐ VAR 12. ÁGÚST!", "B W W W W W DR W W W W W DR P W W DR P E B W W DR P E", ) test_sentence( "Þórdís Kolbrún Reykfjörð Gylfadóttir var skipuð dómsmála-, ferðamála- og iðnaðarráðherra þann 12. mars 2019.", "B W W W W W W W W DA P E", ) test_sentence( "Þórdís Kolbrún Reykfjörð Gylfadóttir var skipuð viðskipta- dómsmála- ferðamála- og iðnaðarráðherra þann 12. mars 2019.", "B W W W W W W W W DA P E", ) test_sentence( "#MeToo-byltingin er til staðar á Íslandsmóti #1. #12stig í Eurovision en #égerekkiaðfílaþað! #ruv50.", "B HT P W W W W W W O P E B HT W W W HT P E B HT P E", ) test_sentence( "Mbl.is er fjölsóttari en www.visir.is, og Rúv.is... En greynir.is, hann er skemmtilegri.Far þú þangað, ekki á 4chan.org!", "B DM W W W DM P W DM P E B W DM P W W W P E B W W W P W W DM P E", ) test_sentence( "Sjá nánar á NRK.no eða WhiteHouse.gov. Some.how.com er fínn vefur, skárri en dailymail.co.uk, eða Extrabladet.dk.", "B W W W DM W DM P E B DM W W W P W W DM P W DM P E", ) test_sentence( "Fyrri setningin var í þgf. en sú seinni í nf. Ég stóð í ef. en hann í þf. Hvað ef.", "B W W W W W W W W W W E B W W W W W W W W E B W W P E", ) test_sentence( "Ég vildi [...] fara út. [...] Hann sá mig.", "B W W P W W P P E B W W W P E", ) test_sentence( "Ég fæddist 15.10. í Skaftárhreppi en systir mín 25.9. Hún var eldri en ég.", "B W W DR W W W W W N P E B W W W W W P E", ) test_sentence( "Jón fæddist 15.10. MCMXCVII í Skaftárhreppi.", "B W W DR W W W P E", ) test_sentence( "Ég þvoði hárið með H2SO4, og notaði efni (Ag2FeSi) við það, en það hjálpaði ekki.", "B W W W W MO P W W W P MO P W W P W W W W P E", ) test_sentence( "Ég þvoði hárið með H2SO4, og notaði efni (AgFeSi) við það, en það hjálpaði ekki.", "B W W W W MO P W W W P W P W W P W W W W P E", ) test_sentence( "Kennitala fyrirtækisins er 591213-1480, en ekki 591214-1480.", "B W W W K P W W N P N P E", ) test_sentence( "Jón, kt. 301265-5309, vann 301265-53090 kr. H2O var drukkið.", "B W P W K P W N P A E B MO W W P E", ) test_sentence( "Anna-María var í St. Mary's en prófaði aldrei að fara á Dunkin' Donuts.", "B W W W W W W W W W W W W W P E", ) test_sentence( "Þingmenn og -konur versluðu marg-ítrekað í Tösku- og hanskabúðinni.", "B W W W W W W W P E", ) test_sentence( "Tösku- og hanskabúðin, sálug, var á Lauga- eða Skothúsvegi.", "B W P W P W W W P E", ) test_sentence( "Tösku-og hanskabúðin, sálug, var á Lauga-eða Skothúsvegi.", "B W P W P W W W P E", ) test_sentence( "Friðgeir fór út kl. hálf átta en var hálf slompaður.", "B W W W T W W W W P E", ) test_sentence( "Klukkan hálf sjö fór Friðgeir út.", "B T W W W P E", ) test_sentence( "Gummi keypti sjö hundruð áttatíu og sjö kindur.", "B W W W W W W W W P E", ) test_sentence( "Sex milljón manns horfðu á trilljarð Bandaríkjadala fuðra upp.", "B W W W W W W W W W P E", ) test_sentence( "Einn, tveir, þrír, fjórir, fimm Dimmalimm.", "B W P W P W P W P W W P E", ) test_sentence( "Einn milljarður tvö hundruð þrjátíu og fjögur þúsund fimm hundruð sextíu og sjö.", "B W W W W W W W W W W W W W P E", ) test_sentence( "Níu hundruð áttatíu og sjö milljónir sex hundruð fimmtíu og fjögur þúsund þrjú hundruð tuttugu og eitt.", "B W W W W W W W W W W W W W W W W W P E", ) test_sentence( "Þrjár septilljónir og einn kvaðrilljarður billjarða.", "B W W W W W W P E", ) test_sentence( "Allir komast fyrir í fjögurra sæta bíl.", "B W W W W W W W P E", ) test_sentence( "Einn fannst í skóginum, ein í hlíðinni og eitt á túninu.", "B W W W W P W W W W W W W P E", ) test_sentence( "Ég bókaði einnar nætur ferð til Volgograd.", "B W W W W W W W P E", ) test_sentence( "Tveir af tveimur eiga tveggja sæta bíl.", "B W W W W W W W P E", ) test_sentence( "Bóndinn á tvo hunda, tvær kindur og tvö lömb.", "B W W W W P W W W W W P E", ) test_sentence( "Þrír þeirra kynntust þremur þriggja ára hestum.", "B W W W W W W W P E", ) test_sentence( "Betri eru þrjú ber í hendi en fjögur í skógi.", "B W W W W W W W W W W P E", ) test_sentence( "Þrjá karla og fjórar konur vantaði.", "B W W W W W W P E", ) test_sentence( "Þrjár teskeiðar af salti í fjögra lítra skál.", "B W W W W W W W W P E", ) test_sentence( "Þarna eru fjórir menn og um fjóra þeirra gilti að " "þeir fengu fjögurra ára dóm fyrir fjórum árum.", "B W W W W W W W W W W " "W W W W W W W W P E", ) def test_unicode() -> None: """Test composite Unicode characters, where a glyph has two code points""" # Mask away Python 2/3 difference # pylint: disable=undefined-variable ACUTE = chr(769) UMLAUT = chr(776) sent = ( "Ko" + UMLAUT + "rfuboltamaðurinn og KR-ingurinn Kristo" + ACUTE + "fer Acox " "heldur a" + ACUTE + " vit ævinty" + ACUTE + "ranna." ) tokens = list(t.tokenize(sent)) assert tokens[1].txt == "Körfuboltamaðurinn" assert tokens[3].txt == "KR-ingurinn" assert tokens[4].txt == "Kristófer" assert tokens[7].txt == "á" assert tokens[9].txt == "ævintýranna" def test_correction() -> None: SENT = [ ( """Hann sagði: "Þú ert fífl"! Ég mótmælti því.""", """Hann sagði: „Þú ert fífl“! Ég mótmælti því.""", ), ( """Hann sagði: Þú ert "fífl"! Ég mótmælti því.""", """Hann sagði: Þú ert „fífl“! Ég mótmælti því.""", ), ( """Hann sagði: Þú ert «fífl»! Ég mótmælti því.""", """Hann sagði: Þú ert „fífl“! Ég mótmælti því.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu í 3ja sinn.""", """Hann sagði: ‚Þú ert fífl‘! Farðu í 3ja sinn.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu í 1sta sinn.""", """Hann sagði: ‚Þú ert fífl‘! Farðu í 1sta sinn.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu 2svar í bað.""", """Hann sagði: ‚Þú ert fífl‘! Farðu 2svar í bað.""", ), ( """Ég keypti 4ra herbergja íbúð á verði 2ja herbergja.""", """Ég keypti 4ra herbergja íbúð á verði 2ja herbergja.""", ), ( """Hann sagði: Þú ert ´fífl´! Hringdu í 7771234.""", """Hann sagði: Þú ert ‚fífl‘! Hringdu í 7771234.""", ), ( """Hann sagði: Þú ert (´fífl´)! Ég mótmælti því.""", """Hann sagði: Þú ert (‘ fífl‘)! Ég mótmælti því.""", # !!! ), ( """Hann "gaf" mér 10,780.65 dollara.""", """Hann „gaf“ mér 10,780.65 dollara.""", ), ( """Hann "gaf" mér €10,780.65.""", """Hann „gaf“ mér €10,780.65.""", ), ( """Hann "gaf" mér €10.780,65.""", """Hann „gaf“ mér €10.780,65.""", ), ] SENT_KLUDGY_ORDINALS_MODIFY = [ ( """Hann sagði: ´Þú ert fífl´! Farðu í 3ja herbergja íbúð.""", """Hann sagði: ‚Þú ert fífl‘! Farðu í þriggja herbergja íbúð.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu í 1sta sinn.""", """Hann sagði: ‚Þú ert fífl‘! Farðu í fyrsta sinn.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu 2svar í bað.""", """Hann sagði: ‚Þú ert fífl‘! Farðu tvisvar í bað.""", ), ( """Ég keypti 4ra herbergja íbúð á verði 2ja herbergja.""", """Ég keypti fjögurra herbergja íbúð á verði tveggja herbergja.""", ), ] SENT_KLUDGY_ORDINALS_TRANSLATE = [ ( """Hann sagði: ´Þú ert fífl´! Farðu í 3ja sinn.""", """Hann sagði: ‚Þú ert fífl‘! Farðu í 3ja sinn.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu í 1sta sinn.""", """Hann sagði: ‚Þú ert fífl‘! Farðu í 1sta sinn.""", ), ( """Hann sagði: ´Þú ert fífl´! Farðu 2svar í bað.""", """Hann sagði: ‚Þú ert fífl‘! Farðu 2svar í bað.""", ), ( """Ég keypti 4ra herbergja íbúð á verði 2ja herbergja.""", """Ég keypti 4ra herbergja íbúð á verði 2ja herbergja.""", ), ] SENT_CONVERT_NUMBERS = [ ( """Hann "gaf" mér 10,780.65 dollara.""", """Hann „gaf“ mér 10.780,65 dollara.""", ), ("""Hann "gaf" mér €10,780.65.""", """Hann „gaf“ mér €10.780,65."""), ( """Hann "gaf" mér €10.780,65.""", """Hann „gaf“ mér €10.780,65.""", ), ] for sent, correct in SENT: s = t.tokenize(sent) txt = t.detokenize(s, normalize=True) assert txt == correct for sent, correct in SENT_KLUDGY_ORDINALS_MODIFY: s = t.tokenize(sent, handle_kludgy_ordinals=t.KLUDGY_ORDINALS_MODIFY) txt = t.detokenize(s, normalize=True) assert txt == correct for sent, correct in SENT_KLUDGY_ORDINALS_TRANSLATE: s = t.tokenize(sent, handle_kludgy_ordinals=t.KLUDGY_ORDINALS_TRANSLATE) txt = t.detokenize(s, normalize=True) assert txt == correct for sent, correct in SENT_CONVERT_NUMBERS: s = t.tokenize(sent, convert_numbers=True) txt = t.detokenize(s, normalize=True) assert txt == correct def test_correct_spaces() -> None: s = t.correct_spaces("Bensínstöðvar, -dælur og -brúsar eru bannaðir.") assert s == "Bensínstöðvar, -dælur og -brúsar eru bannaðir." s = t.correct_spaces("Fjármála- og efnahagsráðuneytið") assert s == "Fjármála- og efnahagsráðuneytið" s = t.correct_spaces("Iðnaðar-, ferðamála- og nýsköpunarráðuneytið") assert s == "Iðnaðar-, ferðamála- og nýsköpunarráðuneytið" s = t.correct_spaces( "Ég hef aldrei verslað í húsgagna-, byggingavöru- eða timburverslun." ) assert s == "Ég hef aldrei verslað í húsgagna-, byggingavöru- eða timburverslun." s = t.correct_spaces( "Frétt \n dagsins:Jón\t ,Friðgeir og Páll ! 100,8 / 2 = 50.4" ) assert s == "Frétt dagsins: Jón, Friðgeir og Páll! 100,8/2 = 50.4" s = t.correct_spaces( "Hitinn var\n-7,4 \t gráður en álverðið var \n $10,348.55." ) assert s == "Hitinn var -7,4 gráður en álverðið var $10,348.55." s = t.correct_spaces( "\n Breytingin var +4,10 þingmenn \t en dollarinn er nú á €1,3455 ." ) assert s == "Breytingin var +4,10 þingmenn en dollarinn er nú á €1,3455." s = t.correct_spaces("Jón- sem var formaður — mótmælti málinu.") assert s == "Jón-sem var formaður—mótmælti málinu." s = t.correct_spaces("Það á að geyma mjólkina við 20 ± 3 °C") assert s == "Það á að geyma mjólkina við 20±3° C" def test_abbrev() -> None: tokens = list(t.tokenize("Í dag las ég fréttina um IBM t.d. á Mbl.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), # We are testing that 'Í' is not an abbreviation Tok(kind=TOK.WORD, txt="Í", val=None), Tok(kind=TOK.WORD, txt="dag", val=None), Tok(kind=TOK.WORD, txt="las", val=None), Tok(kind=TOK.WORD, txt="ég", val=None), Tok(kind=TOK.WORD, txt="fréttina", val=None), Tok(kind=TOK.WORD, txt="um", val=None), Tok( kind=TOK.WORD, txt="IBM", val=[ BIN_Tuple( "International Business Machines", 0, "hk", "skst", "IBM", "-" ) ], ), Tok( kind=TOK.WORD, txt="t.d.", val=[BIN_Tuple("til dæmis", 0, "ao", "frasi", "t.d.", "-")], ), Tok(kind=TOK.WORD, txt="á", val=None), Tok( kind=TOK.WORD, txt="Mbl", val=[BIN_Tuple("Morgunblaðið", 0, "hk", "skst", "Mbl", "-")], ), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Reykjavík er stór m.v. Akureyri.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Reykjavík", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="stór", val=None), Tok( kind=TOK.WORD, txt="m.v.", val=[BIN_Tuple("miðað við", 0, "fs", "frasi", "m.v.", "-")], ), Tok(kind=TOK.WORD, txt="Akureyri", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég nefndi t.d. Guðmund.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="nefndi", val=None), Tok( kind=TOK.WORD, txt="t.d.", val=[BIN_Tuple("til dæmis", 0, "ao", "frasi", "t.d.", "-")], ), Tok(kind=TOK.WORD, txt="Guðmund", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Jón var sérfr. Guðmundur var læknir.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Jón", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok( kind=TOK.WORD, txt="sérfr.", val=[BIN_Tuple("sérfræðingur", 0, "kk", "skst", "sérfr.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Guðmundur", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok(kind=TOK.WORD, txt="læknir", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Jón var t.h. Guðmundur var t.v. á myndinni.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Jón", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok( kind=TOK.WORD, txt="t.h.", val=[BIN_Tuple("til hægri", 0, "ao", "frasi", "t.h.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Guðmundur", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok( kind=TOK.WORD, txt="t.v.", val=[BIN_Tuple("til vinstri", 0, "ao", "frasi", "t.v.", "-")], ), Tok(kind=TOK.WORD, txt="á", val=None), Tok(kind=TOK.WORD, txt="myndinni", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Bréfið var dags. 20. maí.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Bréfið", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok( kind=TOK.WORD, txt="dags.", val=[ BIN_Tuple("dagsetja", 0, "so", "skst", "dags.", "-"), BIN_Tuple("dagsettur", 0, "lo", "skst", "dags.", "-"), ], ), Tok(kind=TOK.DATEREL, txt="20. maí", val=(0, 5, 20)), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég ræddi við hv. þm. Halldóru Mogensen.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="ræddi", val=None), Tok(kind=TOK.WORD, txt="við", val=None), Tok( kind=TOK.WORD, txt="hv.", val=[ BIN_Tuple("hæstvirtur", 0, "lo", "skst", "hv.", "-"), BIN_Tuple("háttvirtur", 0, "lo", "skst", "hv.", "-"), ], ), Tok( kind=TOK.WORD, txt="þm.", val=[BIN_Tuple("þingmaður", 0, "kk", "skst", "þm.", "-")], ), Tok(kind=TOK.WORD, txt="Halldóru", val=None), Tok(kind=TOK.WORD, txt="Mogensen", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Það var snemma dags. Fuglarnir sungu.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Það", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok(kind=TOK.WORD, txt="snemma", val=None), Tok(kind=TOK.WORD, txt="dags", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Fuglarnir", val=None), Tok(kind=TOK.WORD, txt="sungu", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Nú er s. 550-1234 hjá bankanum.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Nú", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok( kind=TOK.WORD, txt="s.", val=[BIN_Tuple("símanúmer", 0, "hk", "skst", "s.", "-")], ), Tok(kind=TOK.TELNO, txt="550-1234", val=("550-1234", "354")), Tok(kind=TOK.WORD, txt="hjá", val=None), Tok(kind=TOK.WORD, txt="bankanum", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með s. 550-1234.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="s.", val=[BIN_Tuple("símanúmer", 0, "hk", "skst", "s.", "-")], ), Tok(kind=TOK.TELNO, txt="550-1234", val=("550-1234", "354")), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með s. en hin er með símanúmer.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="s.", val=[BIN_Tuple("símanúmer", 0, "hk", "skst", "s.", "-")], ), Tok(kind=TOK.WORD, txt="en", val=None), Tok(kind=TOK.WORD, txt="hin", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok(kind=TOK.WORD, txt="símanúmer", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með s. Hin er með símanúmer.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="s.", val=[BIN_Tuple("símanúmer", 0, "hk", "skst", "s.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hin", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok(kind=TOK.WORD, txt="símanúmer", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með s. Hinrik er með símanúmer.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="s.", val=[BIN_Tuple("símanúmer", 0, "hk", "skst", "s.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hinrik", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok(kind=TOK.WORD, txt="símanúmer", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með rknr. 0123-26-123456 í bankanum.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="rknr.", val=[BIN_Tuple("reikningsnúmer", 0, "hk", "skst", "rknr.", "-")], ), Tok(kind=TOK.SERIALNUMBER, txt="0123-26-123456", val=None), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="bankanum", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með rknr. 0123-26-123456.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="rknr.", val=[BIN_Tuple("reikningsnúmer", 0, "hk", "skst", "rknr.", "-")], ), Tok(kind=TOK.SERIALNUMBER, txt="0123-26-123456", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er með rknr. en hin er með reikningsnúmer.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="rknr.", val=[BIN_Tuple("reikningsnúmer", 0, "hk", "skst", "rknr.", "-")], ), Tok(kind=TOK.WORD, txt="en", val=None), Tok(kind=TOK.WORD, txt="hin", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok(kind=TOK.WORD, txt="reikningsnúmer", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Hallur tók 11 frák. en Valur 12.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hallur", val=None), Tok(kind=TOK.WORD, txt="tók", val=None), Tok(kind=TOK.NUMBER, txt="11", val=(11, None, None)), Tok( kind=TOK.WORD, txt="frák.", val=[BIN_Tuple("fráköst", 0, "hk", "skst", "frák.", "-")], ), Tok(kind=TOK.WORD, txt="en", val=None), Tok(kind=TOK.WORD, txt="Valur", val=None), Tok(kind=TOK.NUMBER, txt="12", val=(12, None, None)), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Hallur tók 11 frák. Marteinn tók 12.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hallur", val=None), Tok(kind=TOK.WORD, txt="tók", val=None), Tok(kind=TOK.NUMBER, txt="11", val=(11, None, None)), Tok( kind=TOK.WORD, txt="frák.", val=[BIN_Tuple("fráköst", 0, "hk", "skst", "frák.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Marteinn", val=None), Tok(kind=TOK.WORD, txt="tók", val=None), Tok(kind=TOK.NUMBER, txt="12", val=(12, None, None)), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Hallur tók 11 frák. Hinn tók tólf.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hallur", val=None), Tok(kind=TOK.WORD, txt="tók", val=None), Tok(kind=TOK.NUMBER, txt="11", val=(11, None, None)), Tok( kind=TOK.WORD, txt="frák.", val=[BIN_Tuple("fráköst", 0, "hk", "skst", "frák.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hinn", val=None), Tok(kind=TOK.WORD, txt="tók", val=None), Tok(kind=TOK.WORD, txt="tólf", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ath. ekki ganga um gólf.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok( kind=TOK.WORD, txt="Ath.", val=[BIN_Tuple("athuga", 0, "so", "skst", "ath.", "-")], ), Tok(kind=TOK.WORD, txt="ekki", val=None), Tok(kind=TOK.WORD, txt="ganga", val=None), Tok(kind=TOK.WORD, txt="um", val=None), Tok(kind=TOK.WORD, txt="gólf", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ath. Marteinn verður ekki við á morgun.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok( kind=TOK.WORD, txt="Ath.", val=[BIN_Tuple("athuga", 0, "so", "skst", "ath.", "-")], ), Tok(kind=TOK.WORD, txt="Marteinn", val=None), Tok(kind=TOK.WORD, txt="verður", val=None), Tok(kind=TOK.WORD, txt="ekki", val=None), Tok(kind=TOK.WORD, txt="við", val=None), Tok(kind=TOK.WORD, txt="á", val=None), Tok(kind=TOK.WORD, txt="morgun", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Jón keypti átta kýr, ath. heimildir.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Jón", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.WORD, txt="átta", val=None), Tok(kind=TOK.WORD, txt="kýr", val=None), Tok(kind=TOK.PUNCTUATION, txt=",", val=(3, ",")), Tok( kind=TOK.WORD, txt="ath.", val=[BIN_Tuple("athuga", 0, "so", "skst", "ath.", "-")], ), Tok(kind=TOK.WORD, txt="heimildir", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég er ástfangin, ps. ekki lesa dagbókina mína.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="ástfangin", val=None), Tok(kind=TOK.PUNCTUATION, txt=",", val=(3, ",")), Tok( kind=TOK.WORD, txt="ps.", val=[BIN_Tuple("eftirskrift", 0, "kvk", "skst", "ps.", "-")], ), Tok(kind=TOK.WORD, txt="ekki", val=None), Tok(kind=TOK.WORD, txt="lesa", val=None), Tok(kind=TOK.WORD, txt="dagbókina", val=None), Tok(kind=TOK.WORD, txt="mína", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Vala er með M.Sc. í málfræði.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Vala", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="M.Sc.", val=[BIN_Tuple("Master of Science", 0, "hk", "erl", "M.Sc.", "-")], ), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="málfræði", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Vala jafnaði M.Sc. Halls.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Vala", val=None), Tok(kind=TOK.WORD, txt="jafnaði", val=None), Tok( kind=TOK.WORD, txt="M.Sc.", val=[BIN_Tuple("Master of Science", 0, "hk", "erl", "M.Sc.", "-")], ), Tok(kind=TOK.WORD, txt="Halls", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Vala er með M.Sc. Hallur er með grunnskólapróf.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Vala", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="M.Sc.", val=[BIN_Tuple("Master of Science", 0, "hk", "erl", "M.Sc.", "-")], ), Tok(kind=TOK.WORD, txt="Hallur", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok(kind=TOK.WORD, txt="grunnskólapróf", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Vala er með M.Sc. Hinn er með grunnskólapróf.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Vala", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok( kind=TOK.WORD, txt="M.Sc.", val=[BIN_Tuple("Master of Science", 0, "hk", "erl", "M.Sc.", "-")], ), Tok(kind=TOK.WORD, txt="Hinn", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="með", val=None), Tok(kind=TOK.WORD, txt="grunnskólapróf", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Það er kalt í dag m.v. veðurspána.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Það", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="kalt", val=None), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="dag", val=None), Tok( kind=TOK.WORD, txt="m.v.", val=[BIN_Tuple("miðað við", 0, "fs", "frasi", "m.v.", "-")], ), Tok(kind=TOK.WORD, txt="veðurspána", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Jóna er hávaxin m.v. Martein.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Jóna", val=None), Tok(kind=TOK.WORD, txt="er", val=None), Tok(kind=TOK.WORD, txt="hávaxin", val=None), Tok( kind=TOK.WORD, txt="m.v.", val=[BIN_Tuple("miðað við", 0, "fs", "frasi", "m.v.", "-")], ), Tok(kind=TOK.WORD, txt="Martein", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Jóna þarf að velja á milli matar vs. reikninga.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Jóna", val=None), Tok(kind=TOK.WORD, txt="þarf", val=None), Tok(kind=TOK.WORD, txt="að", val=None), Tok(kind=TOK.WORD, txt="velja", val=None), Tok(kind=TOK.WORD, txt="á", val=None), Tok(kind=TOK.WORD, txt="milli", val=None), Tok(kind=TOK.WORD, txt="matar", val=None), Tok( kind=TOK.WORD, txt="vs.", val=[BIN_Tuple("gegn", 0, "fs", "skst", "vs.", "-")], ), Tok(kind=TOK.WORD, txt="reikninga", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Jóna þarf að velja á milli Íslands vs. Svíþjóðar.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Jóna", val=None), Tok(kind=TOK.WORD, txt="þarf", val=None), Tok(kind=TOK.WORD, txt="að", val=None), Tok(kind=TOK.WORD, txt="velja", val=None), Tok(kind=TOK.WORD, txt="á", val=None), Tok(kind=TOK.WORD, txt="milli", val=None), Tok(kind=TOK.WORD, txt="Íslands", val=None), Tok( kind=TOK.WORD, txt="vs.", val=[BIN_Tuple("gegn", 0, "fs", "skst", "vs.", "-")], ), Tok(kind=TOK.WORD, txt="Svíþjóðar", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég keypti 3 km. af Marteini.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.MEASUREMENT, txt="3 km.", val=("m", 3000.0)), Tok(kind=TOK.WORD, txt="af", val=None), Tok(kind=TOK.WORD, txt="Marteini", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list( t.tokenize("Ég jafnaði 3 km. Marteins.") ) # TODO can't handle cases before names in same sentence tokens = strip_originals(tokens) # assert tokens == [ # Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), # Tok(kind=TOK.WORD, txt="Ég", val=None), # Tok(kind=TOK.WORD, txt="jafnaði", val=None), # Tok(kind=TOK.MEASUREMENT, txt="3 km.", val=('m', 3000.0)), # Tok(kind=TOK.WORD, txt="Marteins", val=None), # Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), # Tok(kind=TOK.S_END, txt=None, val=None), # ] tokens = list(t.tokenize("Ég keypti 3 km. Hinn keypti átta.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.MEASUREMENT, txt="3 km", val=("m", 3000.0)), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hinn", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.WORD, txt="átta", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ég keypti 3 kcal. af Marteini.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.MEASUREMENT, txt="3 kcal.", val=("J", 12552)), Tok(kind=TOK.WORD, txt="af", val=None), Tok(kind=TOK.WORD, txt="Marteini", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list( t.tokenize("Ég jafnaði 3 kcal. Marteins.") ) # TODO can't handle cases before names in same sentence tokens = strip_originals(tokens) # assert tokens == [ # Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), # Tok(kind=TOK.WORD, txt="Ég", val=None), # Tok(kind=TOK.WORD, txt="jafnaði", val=None), # Tok(kind=TOK.MEASUREMENT, txt="3 kcal.", val=('J', 12552)), # Tok(kind=TOK.WORD, txt="Marteins", val=None), # Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), # Tok(kind=TOK.S_END, txt=None, val=None), # ] tokens = list(t.tokenize("Ég keypti 3 kcal. Hinn keypti átta.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ég", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.MEASUREMENT, txt="3 kcal", val=("J", 12552.0)), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Hinn", val=None), Tok(kind=TOK.WORD, txt="keypti", val=None), Tok(kind=TOK.WORD, txt="átta", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] # m/s og km/klst. tokens = list(t.tokenize("Úti var 18 m/s og kuldi.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Úti", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok(kind=TOK.MEASUREMENT, txt="18 m/s", val=("m/s", 18.0)), Tok(kind=TOK.WORD, txt="og", val=None), Tok(kind=TOK.WORD, txt="kuldi", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list( t.tokenize("Bíllinn keyrði á 14 km/klst. Nonni keyrði á hámarkshraða.") ) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Bíllinn", val=None), Tok(kind=TOK.WORD, txt="keyrði", val=None), Tok(kind=TOK.WORD, txt="á", val=None), Tok( kind=TOK.MEASUREMENT, txt="14 km/klst", val=("14 km/klst", 14000.0) ), # TODO wrong val but correct tokenization Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Nonni", val=None), Tok(kind=TOK.WORD, txt="keyrði", val=None), Tok(kind=TOK.WORD, txt="á", val=None), Tok(kind=TOK.WORD, txt="hámarkshraða", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Bílarnir keyrðu á 14 km/klst hraða.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Bílarnir", val=None), Tok(kind=TOK.WORD, txt="keyrðu", val=None), Tok(kind=TOK.WORD, txt="á", val=None), Tok(kind=TOK.MEASUREMENT, txt="14 km/klst", val=("m/s", 3.8888888888888893)), Tok(kind=TOK.WORD, txt="hraða", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Sjö millj. krónur fóru í lagfæringarnar.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Sjö", val=None), Tok( kind=TOK.WORD, txt="millj.", val=[ BIN_Tuple( stofn="milljónir", utg=0, ordfl="kvk", fl="skst", ordmynd="millj.", beyging="-", ), BIN_Tuple( stofn="milljarðar", utg=0, ordfl="kk", fl="skst", ordmynd="millj.", beyging="-", ), ], ), Tok(kind=TOK.WORD, txt="krónur", val=None), # Should this be amount? Tok(kind=TOK.WORD, txt="fóru", val=None), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="lagfæringarnar", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Aðgerðin kostaði níutíu þús.kr.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Aðgerðin", val=None), Tok(kind=TOK.WORD, txt="kostaði", val=None), Tok(kind=TOK.WORD, txt="níutíu", val=None), Tok( kind=TOK.WORD, txt="þús.kr.", val=[BIN_Tuple("þúsundir króna", 0, "kvk", "skst", "þús.kr.", "-")], ), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Aðgerðin kostaði 14 þús.kr.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Aðgerðin", val=None), Tok(kind=TOK.WORD, txt="kostaði", val=None), Tok(kind=TOK.AMOUNT, txt="14 þús.kr.", val=(14e3, "ISK", None, None)), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Aðgerðin þann 5. mars kostaði 14 þús.kr.")) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok( kind=TOK.WORD, txt="Aðgerðin", val=None, original="Aðgerðin", origin_spans=[0, 1, 2, 3, 4, 5, 6, 7], ), Tok( kind=TOK.WORD, txt="þann", val=None, original=" þann", origin_spans=[1, 2, 3, 4], ), Tok( kind=TOK.DATEREL, txt="5. mars", val=(0, 3, 5), original=" 5. mars", origin_spans=[1, 2, 3, 8, 9, 10, 11], ), Tok( kind=TOK.WORD, txt="kostaði", val=None, original=" kostaði", origin_spans=[1, 2, 3, 4, 5, 6, 7], ), Tok( kind=TOK.AMOUNT, txt="14 þús.kr.", val=(14000.0, "ISK", None, None), original=" 14 þús.kr.", origin_spans=[1, 2, 3, 8, 9, 10, 11, 12, 13, 14], ), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Aðgerðin þann 5.mars kostaði 14þús.kr.")) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok( kind=TOK.WORD, txt="Aðgerðin", val=None, original="Aðgerðin", origin_spans=[0, 1, 2, 3, 4, 5, 6, 7], ), Tok( kind=TOK.WORD, txt="þann", val=None, original=" þann", origin_spans=[1, 2, 3, 4], ), Tok( kind=TOK.DATEREL, txt="5. mars", val=(0, 3, 5), original=" 5.mars", origin_spans=[1, 2, 3, 3, 4, 5, 6], ), Tok( kind=TOK.WORD, txt="kostaði", val=None, original=" kostaði", origin_spans=[1, 2, 3, 4, 5, 6, 7], ), Tok( kind=TOK.AMOUNT, txt="14 þús.kr.", val=(14000.0, "ISK", None, None), original=" 14þús.kr.", origin_spans=[1, 2, 3, 3, 4, 5, 6, 7, 8, 9], ), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Átta menn áttu að fara að hátta klukkan átta.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Átta", val=None), Tok(kind=TOK.WORD, txt="menn", val=None), Tok(kind=TOK.WORD, txt="áttu", val=None), Tok(kind=TOK.WORD, txt="að", val=None), Tok(kind=TOK.WORD, txt="fara", val=None), Tok(kind=TOK.WORD, txt="að", val=None), Tok(kind=TOK.WORD, txt="hátta", val=None), Tok(kind=TOK.TIME, txt="klukkan átta", val=(8, 0, 0)), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list( t.tokenize( "Níu þúsund kvaðrilljarðar billjarða tuttugu og ein milljón og eitt." ) ) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Níu", val=None), Tok(kind=TOK.WORD, txt="þúsund", val=None), Tok(kind=TOK.WORD, txt="kvaðrilljarðar", val=None), Tok(kind=TOK.WORD, txt="billjarða", val=None), Tok(kind=TOK.WORD, txt="tuttugu", val=None), Tok(kind=TOK.WORD, txt="og", val=None), Tok(kind=TOK.WORD, txt="ein", val=None), Tok(kind=TOK.WORD, txt="milljón", val=None), Tok(kind=TOK.WORD, txt="og", val=None), Tok(kind=TOK.WORD, txt="eitt", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Oktilljón septilljónir og ein kvintilljón.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Oktilljón", val=None), Tok(kind=TOK.WORD, txt="septilljónir", val=None), Tok(kind=TOK.WORD, txt="og", val=None), Tok(kind=TOK.WORD, txt="ein", val=None), Tok(kind=TOK.WORD, txt="kvintilljón", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list( t.tokenize( "Um 14,5 milljarðar króna hafa verið greiddir í tekjufalls- og viðspyrnustyrki." ) ) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Um", val=None), Tok(kind=TOK.NUMBER, txt="14,5", val=(14.5, None, None)), Tok(kind=TOK.WORD, txt="milljarðar", val=None), Tok(kind=TOK.WORD, txt="króna", val=None), Tok(kind=TOK.WORD, txt="hafa", val=None), Tok(kind=TOK.WORD, txt="verið", val=None), Tok(kind=TOK.WORD, txt="greiddir", val=None), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="tekjufalls- og viðspyrnustyrki", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Ekki einn einasti maður var hlynntur breytingunum.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Ekki", val=None), Tok(kind=TOK.WORD, txt="einn", val=None), Tok(kind=TOK.WORD, txt="einasti", val=None), Tok(kind=TOK.WORD, txt="maður", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok(kind=TOK.WORD, txt="hlynntur", val=None), Tok(kind=TOK.WORD, txt="breytingunum", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Barnið var eins árs en gekk eitt í skólann.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Barnið", val=None), Tok(kind=TOK.WORD, txt="var", val=None), # Tok(kind=TOK.NUMBER, txt="eins", val=(1, None, None)), Tok(kind=TOK.WORD, txt="eins", val=None), # TODO Tok(kind=TOK.WORD, txt="árs", val=None), Tok(kind=TOK.WORD, txt="en", val=None), Tok(kind=TOK.WORD, txt="gekk", val=None), Tok(kind=TOK.WORD, txt="eitt", val=None), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="skólann", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Það eina sem vantaði í lautarferðina var góða skapið.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Það", val=None), Tok(kind=TOK.WORD, txt="eina", val=None), Tok(kind=TOK.WORD, txt="sem", val=None), Tok(kind=TOK.WORD, txt="vantaði", val=None), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="lautarferðina", val=None), Tok(kind=TOK.WORD, txt="var", val=None), Tok(kind=TOK.WORD, txt="góða", val=None), Tok(kind=TOK.WORD, txt="skapið", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Þriggja daga ferð ílengdist þegar þrjú börn veiktust.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Þriggja", val=None), Tok(kind=TOK.WORD, txt="daga", val=None), Tok(kind=TOK.WORD, txt="ferð", val=None), Tok(kind=TOK.WORD, txt="ílengdist", val=None), Tok(kind=TOK.WORD, txt="þegar", val=None), Tok(kind=TOK.WORD, txt="þrjú", val=None), Tok(kind=TOK.WORD, txt="börn", val=None), Tok(kind=TOK.WORD, txt="veiktust", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list( t.tokenize("Þær voru ekki einar um það að hafa lesið Þúsund og eina nótt.") ) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Þær", val=None), Tok(kind=TOK.WORD, txt="voru", val=None), Tok(kind=TOK.WORD, txt="ekki", val=None), Tok(kind=TOK.WORD, txt="einar", val=None), Tok(kind=TOK.WORD, txt="um", val=None), Tok(kind=TOK.WORD, txt="það", val=None), Tok(kind=TOK.WORD, txt="að", val=None), Tok(kind=TOK.WORD, txt="hafa", val=None), Tok(kind=TOK.WORD, txt="lesið", val=None), Tok(kind=TOK.WORD, txt="Þúsund", val=None), Tok(kind=TOK.WORD, txt="og", val=None), Tok(kind=TOK.WORD, txt="eina", val=None), Tok(kind=TOK.WORD, txt="nótt", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] tokens = list(t.tokenize("Eitt sinn, fyrir langa löngu, í fjarlægri vetrarbraut.")) tokens = strip_originals(tokens) assert tokens == [ Tok(kind=TOK.S_BEGIN, txt=None, val=(0, None)), Tok(kind=TOK.WORD, txt="Eitt", val=None), Tok(kind=TOK.WORD, txt="sinn", val=None), Tok(kind=TOK.PUNCTUATION, txt=",", val=(3, ",")), Tok(kind=TOK.WORD, txt="fyrir", val=None), Tok(kind=TOK.WORD, txt="langa", val=None), Tok(kind=TOK.WORD, txt="löngu", val=None), Tok(kind=TOK.PUNCTUATION, txt=",", val=(3, ",")), Tok(kind=TOK.WORD, txt="í", val=None), Tok(kind=TOK.WORD, txt="fjarlægri", val=None), Tok(kind=TOK.WORD, txt="vetrarbraut", val=None), Tok(kind=TOK.PUNCTUATION, txt=".", val=(3, ".")), Tok(kind=TOK.S_END, txt=None, val=None), ] def test_overlap() -> None: # Make sure that there is no overlap between the punctuation sets assert not ( set(t.definitions.LEFT_PUNCTUATION) & set(t.definitions.RIGHT_PUNCTUATION) & set(t.definitions.CENTER_PUNCTUATION) & set(t.definitions.NONE_PUNCTUATION) ) def test_split_sentences() -> None: """Test shallow tokenization""" s = ( "3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000. \n" "200.000 manns mótmæltu.\n" "Hér byrjar ný setning" ) g = t.split_into_sentences(s) sents = list(g) assert len(sents) == 4 assert sents[0] == "3. janúar sl. keypti ég 64kWst rafbíl ." assert sents[1] == "Hann kostaði €30.000 ." assert sents[2] == "200.000 manns mótmæltu ." assert sents[3] == "Hér byrjar ný setning" # Test using a generator as input into split_into_sentences() st = ( "3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000. \n", "200.000 manns mótmæltu\n", "\n", "Hér byrjar ný setning\n", ) def gen(s: Iterable[str]) -> Iterator[str]: for line in s: yield line g = t.split_into_sentences(gen(st)) sents = list(g) assert len(sents) == 4 assert sents[0] == "3. janúar sl. keypti ég 64kWst rafbíl ." assert sents[1] == "Hann kostaði €30.000 ." assert sents[2] == "200.000 manns mótmæltu" assert sents[3] == "Hér byrjar ný setning" # Test the normalize option s = ( 'Hún sagði: "Þú ert leiðinlegur"! Hann svaraði engu -- ' "en hætti við ferðina. \n" ) g = t.split_into_sentences(s, normalize=True) sents = list(g) assert len(sents) == 2 assert sents[0] == "Hún sagði : „ Þú ert leiðinlegur “ !" assert sents[1] == "Hann svaraði engu - - en hætti við ferðina ." g = t.split_into_sentences(s, normalize=False) sents = list(g) assert len(sents) == 2 assert sents[0] == 'Hún sagði : " Þú ert leiðinlegur " !' assert sents[1] == "Hann svaraði engu - - en hætti við ferðina ." g = t.split_into_sentences( "Aðalsteinn Jónsson SU á leið til hafnar í " "Reykjavík.Flutningaskipið Selfoss kom til Reykjavíkur.Rósin sigldi með " "ferðamenn í hvalaskoðun." ) sents = list(g) assert len(sents) == 3 assert sents == [ "Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík .", "Flutningaskipið Selfoss kom til Reykjavíkur .", "Rósin sigldi með ferðamenn í hvalaskoðun .", ] g = t.split_into_sentences( s for s in [ "Aðalsteinn Jónsson SU á leið til hafnar í ", "Reykjavík.Flutningaskipið Selfoss kom til Reykjavíkur.Rósin sigldi með ", "ferðamenn í hvalaskoðun.", ] ) sents = list(g) assert len(sents) == 3 assert sents == [ "Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík .", "Flutningaskipið Selfoss kom til Reykjavíkur .", "Rósin sigldi með ferðamenn í hvalaskoðun .", ] g = t.split_into_sentences( s for s in [ "Aðalsteinn Jónsson SU á leið \n til hafnar í ", "Reykjavík.\nFlutningaskipið Selfoss \nkom til Reykjavíkur.Rósin sigldi með ", "ferðamenn í\nhvalaskoðun.\n\n\n", ] ) sents = list(g) assert len(sents) == 3 assert sents == [ "Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík .", "Flutningaskipið Selfoss kom til Reykjavíkur .", "Rósin sigldi með ferðamenn í hvalaskoðun .", ] g = t.split_into_sentences( s for s in [ "Aðalsteinn Jónsson SU á leið \n til hafnar í ", "Reykjavík\n \t \nFlutningaskipið Selfoss \nkom til Reykjavíkur", "", "Rósin sigldi með ", "ferðamenn í\nhvalaskoðun\n\n\nVigur kom með fullfermi að landi", ] ) sents = list(g) assert len(sents) == 4 assert sents == [ "Aðalsteinn Jónsson SU á leið til hafnar í Reykjavík", "Flutningaskipið Selfoss kom til Reykjavíkur", "Rósin sigldi með ferðamenn í hvalaskoðun", "Vigur kom með fullfermi að landi", ] g = t.split_into_sentences("") sents = list(g) assert len(sents) == 0 g = t.split_into_sentences("Athugum [hvort [setningin sé rétt skilin]].") sents = list(g) assert len(sents) == 1 assert sents == ["Athugum [ hvort [ setningin sé rétt skilin ] ] ."] g = t.split_into_sentences("Þessi [ætti [líka að]] vera rétt skilin.") sents = list(g) assert len(sents) == 1 assert sents == ["Þessi [ ætti [ líka að ] ] vera rétt skilin ."] # g = t.split_into_sentences("Þessi á [[líka að]] vera rétt skilin.") # sents = list(g) # assert len(sents) == 3 # assert sents == [ # "Þessi á", # "[[ líka að ]]", # "vera rétt skilin ." # ] # Test onesentperline # Test whether indirect speech is split up g = t.split_into_sentences("„Er einhver þarna?“ sagði konan.") sents = list(g) assert len(sents) == 1 assert sents == ["„ Er einhver þarna ? “ sagði konan ."] g = t.split_into_sentences("„Er einhver þarna?“ Maðurinn þorði varla fram.") sents = list(g) assert len(sents) == 2 assert sents == ["„ Er einhver þarna ? “", "Maðurinn þorði varla fram ."] g = t.split_into_sentences("„Hún hló,“ sagði barnið.") sents = list(g) assert len(sents) == 1 assert sents == ["„ Hún hló , “ sagði barnið ."] # g = t.split_into_sentences("„Hvað meinarðu??“ sagði barnið.") # sents = list(g) # assert len(sents) == 1 # assert sents == ["„ Hvað meinarðu ?? “ sagði barnið ."] def test_normalization() -> None: text, norm = get_text_and_norm('Hann sagði: "Þú ert ágæt!".') assert text == 'Hann sagði : " Þú ert ágæt ! " .' assert norm == "Hann sagði : „ Þú ert ágæt ! “ ." text, norm = get_text_and_norm("Hún vinnur í fjármála-og efnahagsráðuneytinu.") assert text == "Hún vinnur í fjármála- og efnahagsráðuneytinu ." assert norm == "Hún vinnur í fjármála- og efnahagsráðuneytinu ." text, norm = get_text_and_norm("Þetta er tyrfið...") assert text == "Þetta er tyrfið ..." assert norm == "Þetta er tyrfið …" text, norm = get_text_and_norm("Þetta er gaman..") assert text == "Þetta er gaman .." assert norm == "Þetta er gaman ." text, norm = get_text_and_norm("Þetta er hvellur.....") assert text == "Þetta er hvellur ....." assert norm == "Þetta er hvellur …" text, norm = get_text_and_norm("Þetta er mergjað………") assert text == "Þetta er mergjað ………" assert norm == "Þetta er mergjað …" text, norm = get_text_and_norm("Haldið var áfram [...] eftir langt hlé.") assert text == "Haldið var áfram [...] eftir langt hlé ." assert norm == "Haldið var áfram […] eftir langt hlé ." text, norm = get_text_and_norm("Þetta er tyrfið,, en við höldum áfram.") assert text == "Þetta er tyrfið ,, en við höldum áfram ." assert norm == "Þetta er tyrfið , en við höldum áfram ." text, norm = get_text_and_norm('Hinn svokallaði ,,Galileóhestur" hvarf.') assert text == 'Hinn svokallaði ,, Galileóhestur " hvarf .' assert norm == "Hinn svokallaði „ Galileóhestur “ hvarf ." text, norm = get_text_and_norm("Mars - hin rauða pláneta - skín bjart í nótt.") assert text == "Mars - hin rauða pláneta - skín bjart í nótt ." assert norm == "Mars - hin rauða pláneta - skín bjart í nótt ." text, norm = get_text_and_norm("Mars – hin rauða pláneta – skín bjart í nótt.") assert text == "Mars – hin rauða pláneta – skín bjart í nótt ." assert norm == "Mars - hin rauða pláneta - skín bjart í nótt ." text, norm = get_text_and_norm("Mars — hin rauða pláneta — skín bjart í nótt.") assert text == "Mars — hin rauða pláneta — skín bjart í nótt ." assert norm == "Mars - hin rauða pláneta - skín bjart í nótt ." text, norm = get_text_and_norm("Hvernig gastu gert þetta???!!!!!") assert text == "Hvernig gastu gert þetta ???!!!!!" assert norm == "Hvernig gastu gert þetta ?" toklist = list(t.tokenize('Hann sagði: ,,Þú ert ágæt!!??!".')) assert t.text_from_tokens(toklist) == 'Hann sagði : ,, Þú ert ágæt !!??! " .' assert t.normalized_text_from_tokens(toklist) == "Hann sagði : „ Þú ert ágæt ! “ ." toklist = list(t.tokenize('Hann sagði: ,,Þú ert ágæt??!?".')) assert t.text_from_tokens(toklist) == 'Hann sagði : ,, Þú ert ágæt ??!? " .' assert t.normalized_text_from_tokens(toklist) == "Hann sagði : „ Þú ert ágæt ? “ ." toklist = list(t.tokenize("Jón,, farðu út.")) assert t.text_from_tokens(toklist) == "Jón ,, farðu út ." assert t.normalized_text_from_tokens(toklist) == "Jón , farðu út ." toklist = list(t.tokenize("Jón ,,farðu út.")) assert t.text_from_tokens(toklist) == "Jón ,, farðu út ." assert t.normalized_text_from_tokens(toklist) == "Jón „ farðu út ." toklist = list(t.tokenize('Hann sagði: ,,Þú ert ágæt.....".')) assert t.text_from_tokens(toklist) == 'Hann sagði : ,, Þú ert ágæt ..... " .' assert t.normalized_text_from_tokens(toklist) == "Hann sagði : „ Þú ert ágæt … “ ." toklist = list(t.tokenize('Hann sagði: ,,Þú ert ágæt…..".')) assert t.text_from_tokens(toklist) == 'Hann sagði : ,, Þú ert ágæt ….. " .' assert t.normalized_text_from_tokens(toklist) == "Hann sagði : „ Þú ert ágæt … “ ." def test_abbr_at_eos() -> None: """Test that 'Örn.' is not treated as an abbreviation here""" toklist = list( t.tokenize( "„Mér leiddist ekki,“ segir Einar Örn. Hann telur þó að " "sýningin líði fyrir það ástand sem hefur skapast " "vegna heimsfaraldursins." ) ) assert len([tok for tok in toklist if tok.kind == TOK.S_BEGIN]) == 2 assert len([tok for tok in toklist if tok.kind == TOK.S_END]) == 2 def test_time_token() -> None: toklist = list( t.tokenize("2.55pm - Síðasta tilraun setur Knights fram klukkan hálf") ) assert len(toklist) == 12 assert toklist[-2].kind == TOK.WORD assert toklist[-2].txt == "hálf" assert toklist[-3].kind == TOK.WORD assert toklist[-3].txt == "klukkan" def test_html_escapes() -> None: toklist = list( t.tokenize( "Ég&nbsp;fór &aacute; &lt;bömmer&gt; og bor&shy;ðaði köku.", replace_html_escapes=True, ) ) toklist = strip_originals(toklist) correct = [ Tok(kind=11001, txt=None, val=(0, None)), Tok(kind=6, txt="Ég", val=None), Tok(kind=6, txt="fór", val=None), Tok(kind=6, txt="á", val=None), Tok(kind=1, txt="<", val=(1, "<")), Tok(kind=6, txt="bömmer", val=None), Tok(kind=1, txt=">", val=(3, ">")), Tok(kind=6, txt="og", val=None), Tok(kind=6, txt="borðaði", val=None), Tok(kind=6, txt="köku", val=None), Tok(kind=1, txt=".", val=(3, ".")), Tok(kind=11002, txt=None, val=None), ] assert toklist == correct toklist = list( t.tokenize( # En space and Em space "Ég&#8194;fór &aacute; &lt;bömmer&gt;&#8195;og bor&shy;ðaði köku.", replace_html_escapes=True, ) ) toklist = strip_originals(toklist) assert toklist == correct toklist = list( t.tokenize( "Ég fór &uacute;t og &#97;fs&#x61;kaði mig", replace_html_escapes=True ) ) toklist = strip_originals(toklist) correct = [ Tok(kind=11001, txt=None, val=(0, None)), Tok(kind=6, txt="Ég", val=None), Tok(kind=6, txt="fór", val=None), Tok(kind=6, txt="út", val=None), Tok(kind=6, txt="og", val=None), Tok(kind=6, txt="afsakaði", val=None), Tok(kind=6, txt="mig", val=None), Tok(kind=11002, txt=None, val=None), ] assert toklist == correct def test_one_sent_per_line() -> None: toklist = list(t.tokenize("Hér er hestur\nmaður beit hund", one_sent_per_line=True)) toklist = strip_originals(toklist) correct = [ Tok(kind=11001, txt=None, val=(0, None)), Tok(kind=6, txt="Hér", val=None), Tok(kind=6, txt="er", val=None), Tok(kind=6, txt="hestur", val=None), Tok( kind=11002, txt="", val=None ), # txt is not None due to origin tracking of the newline Tok(kind=11001, txt=None, val=(0, None)), Tok(kind=6, txt="maður", val=None), Tok(kind=6, txt="beit", val=None), Tok(kind=6, txt="hund", val=None), Tok(kind=11002, txt=None, val=None), ] assert toklist == correct # Test without option toklist = list( t.tokenize("Hér er hestur\nmaður beit hund", one_sent_per_line=False) ) toklist = strip_originals(toklist) correct = [ Tok(kind=11001, txt=None, val=(0, None)), Tok(kind=6, txt="Hér", val=None), Tok(kind=6, txt="er", val=None), Tok(kind=6, txt="hestur", val=None), Tok(kind=6, txt="maður", val=None), Tok(kind=6, txt="beit", val=None), Tok(kind=6, txt="hund", val=None), Tok(kind=11002, txt=None, val=None), ] assert toklist == correct if __name__ == "__main__": test_single_tokens() test_sentences() test_correct_spaces() test_correction() test_abbrev() test_overlap() test_split_sentences() test_normalization() test_html_escapes()
102,165
38.768782
131
py
z3
z3-master/examples/python/visitor.py
# Copyright (c) Microsoft Corporation 2015 from __future__ import print_function from z3 import * def visitor(e, seen): if e in seen: return seen[e] = True yield e if is_app(e): for ch in e.children(): for e in visitor(ch, seen): yield e return if is_quantifier(e): for e in visitor(e.body(), seen): yield e return def modify(e, fn): seen = {} def visit(e): if e in seen: pass elif fn(e) is not None: seen[e] = fn(e) elif is_and(e): chs = [visit(ch) for ch in e.children()] seen[e] = And(chs) elif is_or(e): chs = [visit(ch) for ch in e.children()] seen[e] = Or(chs) elif is_app(e): chs = [visit(ch) for ch in e.children()] seen[e] = e.decl()(chs) elif is_quantifier(e): # Note: does not work for Lambda that requires a separate case body = visit(e.body()) is_forall = e.is_forall() num_pats = e.num_patterns() pats = (Pattern * num_pats)() for i in range(num_pats): pats[i] = e.pattern(i).ast num_decls = e.num_vars() sorts = (Sort * num_decls)() names = (Symbol * num_decls)() for i in range(num_decls): sorts[i] = e.var_sort(i).ast names[i] = to_symbol(e.var_name(i), e.ctx) r = QuantifierRef(Z3_mk_quantifier(e.ctx_ref(), is_forall, e.weight(), num_pats, pats, num_decls, sorts, names, body.ast), e.ctx) seen[e] = r else: seen[e] = e return seen[e] return visit(e) if __name__ == "__main__": x, y = Ints('x y') fml = x + x + y > 2 seen = {} for e in visitor(fml, seen): if is_const(e) and e.decl().kind() == Z3_OP_UNINTERPRETED: print("Variable", e) else: print(e) s = SolverFor("HORN") inv = Function('inv', IntSort(), IntSort(), BoolSort()) i, ip, j, jp = Ints('i ip j jp') s.add(ForAll([i, j], Implies(i == 0, inv(i, j)))) s.add(ForAll([i, ip, j, jp], Implies(And(inv(i, j), i < 10, ip == i + 1), inv(ip, jp)))) s.add(ForAll([i, j], Implies(And(inv(i, j), i >= 10), i == 10))) a0, a1, a2 = Ints('a0 a1 a2') b0, b1, b2 = Ints('b0 b1 b2') x = Var(0, IntSort()) y = Var(1, IntSort()) template = And(a0 + a1*x + a2*y >= 0, b0 + b1*x + b2*y >= 0) def update(e): if is_app(e) and eq(e.decl(), inv): return substitute_vars(template, (e.arg(0)), e.arg(1)) return None for f in s.assertions(): f_new = modify(f, update) print(f_new)
2,796
30.784091
141
py
z3
z3-master/examples/python/example.py
# Copyright (c) Microsoft Corporation 2015, 2016 # The Z3 Python API requires libz3.dll/.so/.dylib in the # PATH/LD_LIBRARY_PATH/DYLD_LIBRARY_PATH # environment variable and the PYTHONPATH environment variable # needs to point to the `python' directory that contains `z3/z3.py' # (which is at bin/python in our binary releases). # If you obtained example.py as part of our binary release zip files, # which you unzipped into a directory called `MYZ3', then follow these # instructions to run the example: # Running this example on Windows: # set PATH=%PATH%;MYZ3\bin # set PYTHONPATH=MYZ3\bin\python # python example.py # Running this example on Linux: # export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:MYZ3/bin # export PYTHONPATH=MYZ3/bin/python # python example.py # Running this example on macOS: # export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:MYZ3/bin # export PYTHONPATH=MYZ3/bin/python # python example.py from z3 import * x = Real('x') y = Real('y') s = Solver() s.add(x + y > 5, x > 1, y > 1) print(s.check()) print(s.model())
1,036
27.027027
70
py
z3
z3-master/examples/python/rc2.py
# RC2 algorithm # basic version with some optimizations # - process soft constraints in order of highest values first. # - extract multiple cores, not just one # - use built-in cardinality constraints, cheap core minimization. # # See also https://github.com/pysathq/pysat and papers in CP 2014, JSAT 2015. 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>)
4,917
29.7375
92
py
z3
z3-master/examples/python/union_sort.py
# Copyright Microsoft Corporation 2019 # This example illustrates the use of union types # from the Python API. It is given as an example # as response to #2215. from z3 import * u = Datatype('IntOrString') u.declare('IntV', ('int', IntSort())) u.declare('StringV', ('string', StringSort())) IntOrString = u.create() StringV = IntOrString.StringV IntV = IntOrString.IntV print(IntV(1)) print(StringV(StringVal("abc"))) print(IntV(1).sort()) print(IntV(1) == StringV(StringVal("abc"))) s = String('s') print(simplify(IntV(1) == StringV(s)))
543
24.904762
49
py
z3
z3-master/examples/python/all_interval_series.py
# Copyright Microsoft Research 2016 # The following script finds sequences of length n-1 of # integers 0,..,n-1 such that the difference of the n-1 # adjacent entries fall in the range 0,..,n-1 # This is known as the "The All-Interval Series Problem" # See http://www.csplib.org/Problems/prob007/ 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.time() while sat == s.check(): block = process_model(s, xij, n) s.add(Not(And(block))) count += 1 print(s.statistics()) print(time.time() - start) print(count) set_option(verbose=1) all_models(12)
2,389
29.253165
108
py
z3
z3-master/examples/python/mini_quip.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
25,576
31.499365
126
py
z3
z3-master/examples/python/efsmt.py
from z3 import * from z3.z3util import get_vars ''' Modified from the example in pysmt https://github.com/pysmt/pysmt/blob/97088bf3b0d64137c3099ef79a4e153b10ccfda7/examples/efsmt.py ''' def efsmt(ys, phi, maxloops = None): """Solving exists xs. forall ys. phi(x, y)""" xs = [x for x in get_vars(phi) if x not in ys] E = Solver() F = Solver() E.add(BoolVal(True)) loops = 0 while maxloops is None or loops <= maxloops: loops += 1 eres = E.check() if eres == sat: emodel = E.model() sub_phi = substitute(phi, [(x, emodel.eval(x, True)) for x in xs]) F.push() F.add(Not(sub_phi)) fres = F.check() if fres == sat: fmodel = F.model() sub_phi = substitute(phi, [(y, fmodel.eval(y, True)) for y in ys]) E.add(sub_phi) else: return fres, [(x, emodel.eval(x, True)) for x in xs] F.pop() else: return eres return unknown x, y, z = Reals("x y z") print(efsmt([y], Implies(And(y > 0, y < 10), y - 2 * x < 7))) print(efsmt([y], And(y > 3, x == 1)))
1,176
29.179487
94
py
z3
z3-master/examples/python/trafficjam.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
3,434
25.627907
92
py
z3
z3-master/examples/python/simplify_formula.py
from z3 import * def is_atom(t): if not is_bool(t): return False if not is_app(t): return False k = t.decl().kind() if k == Z3_OP_AND or k == Z3_OP_OR or k == Z3_OP_IMPLIES: return False if k == Z3_OP_EQ and t.arg(0).is_bool(): return False if k == Z3_OP_TRUE or k == Z3_OP_FALSE or k == Z3_OP_XOR or k == Z3_OP_NOT: return False return True def atoms(fml): visited = set([]) atms = set([]) def atoms_rec(t, visited, atms): if t in visited: return visited |= { t } if is_atom(t): atms |= { t } for s in t.children(): atoms_rec(s, visited, atms) atoms_rec(fml, visited, atms) return atms def atom2literal(m, a): if is_true(m.eval(a)): return a return Not(a) # Extract subset of atoms used to satisfy the negation # of a formula. # snot is a solver for Not(fml) # s is a solver for fml # m is a model for Not(fml) # evaluate each atom in fml using m and create # literals corresponding to the sign of the evaluation. # If the model evaluates atoms to false, the literal is # negated. # # def implicant(atoms, s, snot): m = snot.model() lits = [atom2literal(m, a) for a in atoms] is_sat = s.check(lits) assert is_sat == unsat core = s.unsat_core() return Or([mk_not(c) for c in core]) # # Extract a CNF representation of fml # The procedure uses two solvers # Enumerate models for Not(fml) # Use the enumerated model to identify literals # that imply Not(fml) # The CNF of fml is a conjunction of the # negation of these literals. # def to_cnf(fml): atms = atoms(fml) s = Solver() snot = Solver() snot.add(Not(fml)) s.add(fml) while sat == snot.check(): clause = implicant(atms, s, snot) yield clause snot.add(clause) a, b, c, = Bools('a b c') fml = Or(And(a, b), And(Not(a), c)) for clause in to_cnf(fml): print(clause)
1,996
22.77381
79
py
z3
z3-master/examples/python/socrates.py
############################################ # Copyright (c) Microsoft Corporation. All Rights Reserved. # # all humans are mortal # Socrates is a human # so Socrates mortal ############################################ from z3 import * Object = DeclareSort('Object') Human = Function('Human', Object, BoolSort()) Mortal = Function('Mortal', Object, BoolSort()) # a well known philosopher socrates = Const('socrates', Object) # free variables used in forall must be declared Const in python x = Const('x', Object) axioms = [ForAll([x], Implies(Human(x), Mortal(x))), Human(socrates)] s = Solver() s.add(axioms) print(s.check()) # prints sat so axioms are coherent # classical refutation s.add(Not(Mortal(socrates))) print(s.check()) # prints unsat so socrates is Mortal
793
21.685714
64
py
z3
z3-master/examples/python/mini_ic3.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 __lt__(self, other): return self.level < other.level 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, [p for p in zip(self.x0, self.xn)]) def prev(self, f): if is_seq(f): return [self.prev(f1) for f1 in f] return substitute(f, [p for p in 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
11,936
28.76808
101
py
z3
z3-master/examples/python/prooflogs.py
# This script illustrates uses of proof logs over the Python interface. from z3 import * example1 = """ (declare-sort T) (declare-fun subtype (T T) Bool) ;; subtype is reflexive (assert (forall ((x T)) (subtype x x))) ;; subtype is antisymmetric (assert (forall ((x T) (y T)) (=> (and (subtype x y) (subtype y x)) (= x y)))) ;; subtype is transitive (assert (forall ((x T) (y T) (z T)) (=> (and (subtype x y) (subtype y z)) (subtype x z)))) ;; subtype has the tree-property (assert (forall ((x T) (y T) (z T)) (=> (and (subtype x z) (subtype y z)) (or (subtype x y) (subtype y x))))) ;; now we define a simple example using the axiomatization above. (declare-const obj-type T) (declare-const int-type T) (declare-const real-type T) (declare-const complex-type T) (declare-const string-type T) ;; we have an additional axiom: every type is a subtype of obj-type (assert (forall ((x T)) (subtype x obj-type))) (assert (subtype int-type real-type)) (assert (subtype real-type complex-type)) (assert (not (subtype string-type real-type))) (declare-const root-type T) (assert (subtype obj-type root-type)) """ def monitor_plain(): print("Monitor all inferred clauses") s = Solver() s.from_string(example1) onc = OnClause(s, lambda pr, clause : print(pr, clause)) print(s.check()) def log_instance(pr, clause): if pr.decl().name() == "inst": q = pr.arg(0).arg(0) # first argument is Not(q) for ch in pr.children(): if ch.decl().name() == "bind": print("Binding") print(q) print(ch.children()) break def monitor_instances(): print("Monitor just quantifier bindings") s = Solver() s.from_string(example1) onc = OnClause(s, log_instance) print(s.check()) def monitor_with_proofs(): print("Monitor clauses annotated with detailed justifications") set_param(proof=True) s = Solver() s.from_string(example1) onc = OnClause(s, lambda pr, clause : print(pr, clause)) print(s.check()) def monitor_new_core(): print("Monitor proof objects from the new core") set_param("sat.euf", True) set_param("tactic.default_tactic", "sat") s = Solver() s.from_string(example1) onc = OnClause(s, lambda pr, clause : print(pr, clause)) print(s.check()) if __name__ == "__main__": monitor_plain() monitor_instances() monitor_new_core() # Monitoring with proofs cannot be done in the same session # monitor_with_proofs()
2,810
28.904255
71
py
z3
z3-master/examples/python/hs.py
# # Unweighted hitting set maxsat solver. # interleaved with local hill-climbing improvements # and also maxres relaxation steps to reduce number # of soft constraints. # from z3 import * import random counter = 0 def add_def(s, fml): global counter name = Bool(f"def-{counter}") counter += 1 s.add(name == fml) return name def relax_core(s, core, Fs): core = list(core) if len(core) == 0: return prefix = BoolVal(True) Fs -= { f for f in core } for i in range(len(core)-1): prefix = add_def(s, And(core[i], prefix)) Fs |= { add_def(s, Or(prefix, core[i+1])) } def restrict_cs(s, cs, Fs): cs = list(cs) if len(cs) == 0: return prefix = BoolVal(False) Fs -= { f for f in cs } for i in range(len(cs)-1): prefix = add_def(s, Or(cs[i], prefix)) Fs |= { add_def(s, And(prefix, cs[i+1])) } def count_sets_by_size(sets): sizes = {} for core in sets: sz = len(core) if sz not in sizes: sizes[sz] = 0 sizes[sz] += 1 sizes = list(sizes.items()) sizes = sorted(sizes, key = lambda p : p[0]) print(sizes) #set_param("sat.euf", True) #set_param("tactic.default_tactic","sat") #set_param("sat.cardinality.solver",False) #set_param("sat.cardinality.encoding", "circuit") #set_param(verbose=1) class Soft: def __init__(self, soft): self.formulas = set(soft) self.original_soft = soft.copy() self.offset = 0 self.init_names() def init_names(self): self.name2formula = { Bool(f"s{s}") : s for s in self.formulas } self.formula2name = { s : v for (v, s) in self.name2formula.items() } # # TODO: try to replace this by a recursive invocation of HsMaxSAT # such that the invocation is incremental with respect to adding constraints # and has resource bounded invocation. # class HsPicker: def __init__(self, soft): self.soft = soft self.opt_backoff_limit = 0 self.opt_backoff_count = 0 self.timeout_value = 6000 def pick_hs_(self, Ks, lo): hs = set() for ks in Ks: if not any(k in ks for k in hs): h = random.choice([h for h in ks]) hs = hs | { h } print("approximate hitting set", len(hs), "smallest possible size", lo) return hs, lo # # This can improve lower bound, but is expensive. # Note that Z3 does not work well for hitting set optimization. # MIP solvers contain better # tuned approaches thanks to LP lower bounds and likely other properties. # Would be nice to have a good hitting set # heuristic built into Z3.... # def pick_hs(self, Ks, lo): if len(Ks) == 0: return set(), lo if self.opt_backoff_count < self.opt_backoff_limit: self.opt_backoff_count += 1 return self.pick_hs_(Ks, lo) opt = Optimize() for k in Ks: opt.add(Or([self.soft.formula2name[f] for f in k])) for n in self.soft.formula2name.values(): obj = opt.add_soft(Not(n)) opt.set("timeout", self.timeout_value) is_sat = opt.check() lo = max(lo, opt.lower(obj).as_long()) self.opt_backoff_count = 0 if is_sat == sat: if self.opt_backoff_limit > 1: self.opt_backoff_limit -= 1 self.timeout_value += 500 mdl = opt.model() hs = [self.soft.name2formula[n] for n in self.soft.formula2name.values() if is_true(mdl.eval(n))] return set(hs), lo else: print("Timeout", self.timeout_value, "lo", lo, "limit", self.opt_backoff_limit) self.opt_backoff_limit += 1 self.timeout_value += 500 return self.pick_hs_(Ks, lo) class HsMaxSAT: def __init__(self, soft, s): self.s = s # solver object self.soft = Soft(soft) # Soft constraints self.hs = HsPicker(self.soft) # Pick a hitting set self.model = None # Current best model self.lo = 0 # Current lower bound self.hi = len(soft) # Current upper bound self.Ks = [] # Set of Cores self.Cs = [] # Set of correction sets self.small_set_size = 6 self.small_set_threshold = 1 self.num_max_res_failures = 0 self.corr_set_enabled = True self.patterns = [] def has_many_small_sets(self, sets): small_count = len([c for c in sets if len(c) <= self.small_set_size]) return self.small_set_threshold <= small_count def get_small_disjoint_sets(self, sets): hs = set() result = [] min_size = min(len(s) for s in sets) def insert(bound, sets, hs, result): for s in sets: if len(s) == bound and not any(c in hs for c in s): result += [s] hs = hs | set(s) return hs, result for sz in range(min_size, min_size + 3): hs, result = insert(sz, sets, hs, result) return result def reinit_soft(self, num_cores_relaxed): self.soft.init_names() self.soft.offset += num_cores_relaxed self.Ks = [] self.Cs = [] self.lo -= num_cores_relaxed print("New offset", self.soft.offset) def maxres(self): # # If there are sufficiently many small cores, then # we reduce the soft constraints by maxres. # if self.has_many_small_sets(self.Ks) or (not self.corr_set_enabled and not self.has_many_small_sets(self.Cs) and self.num_max_res_failures > 0): self.num_max_res_failures = 0 cores = self.get_small_disjoint_sets(self.Ks) for core in cores: self.small_set_size = max(4, min(self.small_set_size, len(core) - 2)) relax_core(self.s, core, self.soft.formulas) self.reinit_soft(len(cores)) self.corr_set_enabled = True return # # If there are sufficiently many small correction sets, then # we reduce the soft constraints by dual maxres (IJCAI 2015) # # TODO: the heuristic for when to invoking correction set restriction # needs fine-tuning. For example, the if min(Ks)*optimality_gap < min(Cs)*(max(SS)) # we might want to prioritize core relaxation to make progress with less overhead. # here: max(SS) = |Soft|-min(Cs) is the size of the maximal satisfying subset # the optimality gap is self.hi - self.offset # which is a bound on how many cores have to be relaxed before determining optimality. # if self.corr_set_enabled and self.has_many_small_sets(self.Cs): self.num_max_res_failures = 0 cs = self.get_small_disjoint_sets(self.Cs) for corr_set in cs: print("restrict cs", len(corr_set)) # self.small_set_size = max(4, min(self.small_set_size, len(corr_set) - 2)) restrict_cs(self.s, corr_set, self.soft.formulas) self.s.add(Or(corr_set)) self.reinit_soft(0) self.corr_set_enabled = False return # # Increment the failure count. If the failure count reaches a threshold # then increment the lower bounds for performing maxres or dual maxres # self.num_max_res_failures += 1 print("Small set size", self.small_set_size, "num skips", self.num_max_res_failures) if self.num_max_res_failures > 3: self.num_max_res_failures = 0 self.small_set_size += 100 def pick_hs(self): hs, self.lo = self.hs.pick_hs(self.Ks, self.lo) return hs def save_model(self): # # You can save a model here. # For example, add the string: self.model.sexpr() # to a file, or print bounds in custom format. # # print(f"Bound: {self.lo}") # for f in self.soft.original_soft: # print(f"{f} := {self.model.eval(f)}") pass def add_pattern(self, orig_cs): named = { f"{f}" : f for f in self.soft.original_soft } sorted_names = sorted(named.keys()) sorted_soft = [named[f] for f in sorted_names] bits = [1 if f not in orig_cs else 0 for f in sorted_soft] def eq_bits(b1, b2): return all(b1[i] == b2[i] for i in range(len(b1))) def num_overlaps(b1, b2): return sum(b1[i] == b2[i] for i in range(len(b1))) if not any(eq_bits(b, bits) for b in self.patterns): if len(self.patterns) > 0: print(num_overlaps(bits, self.patterns[-1]), len(bits), bits) self.patterns += [bits] counts = [sum(b[i] for b in self.patterns) for i in range(len(bits))] print(counts) # # Crude, quick core reduction attempt # def reduce_core(self, core): s = self.s if len(core) <= 4: return core s.set("timeout", 200) i = 0 num_undef = 0 orig_len = len(core) core = list(core) while i < len(core): is_sat = s.check([core[j] for j in range(len(core)) if j != i]) if is_sat == unsat: core = s.unsat_core() elif is_sat == sat: self.improve(s.model()) bound = self.hi - self.soft.offset - 1 else: num_undef += 1 if num_undef > 3: break i += 1 print("Reduce", orig_len, "->", len(core), "iterations", i, "unknown", num_undef) s.set("timeout", 100000000) return core def improve(self, new_model): mss = { f for f in self.soft.formulas if is_true(new_model.eval(f)) } cs = self.soft.formulas - mss self.Cs += [cs] orig_cs = { f for f in self.soft.original_soft if not is_true(new_model.eval(f)) } cost = len(orig_cs) if self.model is None: self.model = new_model if cost <= self.hi: self.add_pattern(orig_cs) print("improve", self.hi, cost) self.model = new_model self.save_model() assert self.model if cost < self.hi: self.hi = cost return True return False def try_rotate(self, mss): backbones = set() backbone2core = {} ps = self.soft.formulas - mss num_sat = 0 num_unsat = 0 improved = False while len(ps) > 0: p = random.choice([p for p in ps]) ps = ps - { p } is_sat = self.s.check(mss | backbones | { p }) if is_sat == sat: mdl = self.s.model() mss = mss | {p} ps = ps - {p} if self.improve(mdl): improved = True num_sat += 1 elif is_sat == unsat: backbones = backbones | { Not(p) } core = set() for c in self.s.unsat_core(): if c in backbone2core: core = core | backbone2core[c] else: core = core | { c } if len(core) < 20: self.Ks += [core] backbone2core[Not(p)] = set(core) - { p } num_unsat += 1 else: print("unknown") print("rotate-1 done, sat", num_sat, "unsat", num_unsat) if improved: self.mss_rotate(mss, backbone2core) return improved def mss_rotate(self, mss, backbone2core): counts = { c : 0 for c in mss } max_count = 0 max_val = None for core in backbone2core.values(): for c in core: assert c in mss counts[c] += 1 if max_count < counts[c]: max_count = counts[c] max_val = c print("rotate max-count", max_count, "num occurrences", len({c for c in counts if counts[c] == max_count})) print("Number of plateaus", len({ c for c in counts if counts[c] <= 1 })) for c in counts: if counts[c] > 1: print("try-rotate", counts[c]) if self.try_rotate(mss - { c }): break def local_mss(self, new_model): mss = { f for f in self.soft.formulas if is_true(new_model.eval(f)) } ######################################## # test effect of random sub-sampling # #mss = list(mss) #ms = set() #for i in range(len(mss)//2): # ms = ms | { random.choice([p for p in mss]) } #mss = ms #### ps = self.soft.formulas - mss backbones = set() qs = set() backbone2core = {} while len(ps) > 0: p = random.choice([p for p in ps]) ps = ps - { p } is_sat = self.s.check(mss | backbones | { p }) print(len(ps), is_sat) sys.stdout.flush() if is_sat == sat: mdl = self.s.model() rs = { p } # # by commenting this out, we use a more stubborn exploration # by using the random seed as opposed to current model as a guide # to what gets satisfied. # # Not sure if it really has an effect. # rs = rs | { q for q in ps if is_true(mdl.eval(q)) } # rs = rs | { q for q in qs if is_true(mdl.eval(q)) } mss = mss | rs ps = ps - rs qs = qs - rs if self.improve(mdl): self.mss_rotate(mss, backbone2core) elif is_sat == unsat: core = set() for c in self.s.unsat_core(): if c in backbone2core: core = core | backbone2core[c] else: core = core | { c } core = self.reduce_core(core) self.Ks += [core] backbone2core[Not(p)] = set(core) - { p } backbones = backbones | { Not(p) } else: qs = qs | { p } if len(qs) > 0: print("Number undetermined", len(qs)) def unsat_core(self): core = self.s.unsat_core() return self.reduce_core(core) def get_cores(self, hs): core = self.unsat_core() remaining = self.soft.formulas - hs num_cores = 0 cores = [core] if len(core) == 0: self.lo = self.hi - self.soft.offset return while True: is_sat = self.s.check(remaining) if unsat == is_sat: core = self.unsat_core() if len(core) == 0: self.lo = self.hi - self.soft.offset return cores += [core] h = random.choice([c for c in core]) remaining = remaining - { h } elif sat == is_sat and num_cores == len(cores): self.local_mss(self.s.model()) break elif sat == is_sat: self.improve(self.s.model()) # # Extend the size of the hitting set using the new cores # and update remaining using these cores. # The new hitting set contains at least one new element # from the original cores # hs = hs | { random.choice([c for c in cores[i]]) for i in range(num_cores, len(cores)) } remaining = self.soft.formulas - hs num_cores = len(cores) else: print(is_sat) break self.Ks += [set(core) for core in cores] print("total number of cores", len(self.Ks)) print("total number of correction sets", len(self.Cs)) def step(self): soft = self.soft hs = self.pick_hs() is_sat = self.s.check(soft.formulas - set(hs)) if is_sat == sat: self.improve(self.s.model()) elif is_sat == unsat: self.get_cores(hs) else: print("unknown") print("maxsat [", self.lo + soft.offset, ", ", self.hi, "]","offset", soft.offset) count_sets_by_size(self.Ks) count_sets_by_size(self.Cs) self.maxres() def run(self): while self.lo + self.soft.offset < self.hi: self.step() #set_option(verbose=1) def main(file): s = Solver() opt = Optimize() opt.from_file(file) s.add(opt.assertions()) # # We just assume this is an unweighted MaxSAT optimization problem. # Weights are ignored. # soft = [f.arg(0) for f in opt.objectives()[0].children()] hs = HsMaxSAT(soft, s) hs.run() if __name__ == '__main__': main(sys.argv[1])
17,449
34.323887
152
py
z3
z3-master/examples/python/parallel.py
from z3 import * from multiprocessing.pool import ThreadPool from copy import deepcopy pool = ThreadPool(8) x = Int('x') assert x.ctx == main_ctx() def calculate(x, n, ctx): """ Do a simple computation with a context""" assert x.ctx == ctx assert x.ctx != main_ctx() # Parallel creation of z3 object condition = And(x < 2, x > n, ctx) # Parallel solving solver = Solver(ctx=ctx) solver.add(condition) solver.check() for i in range(100): # Create new context for the computation # Note that we need to do this sequentially, as parallel access to the current context or its objects # will result in a segfault i_context = Context() x_i = deepcopy(x).translate(i_context) # Kick off parallel computation pool.apply_async(calculate, [x_i, i, i_context]) pool.close() pool.join()
849
21.972973
105
py
z3
z3-master/examples/python/proofreplay.py
# This script illustrates uses of proof replay and proof logs over the Python interface. from z3 import * example1 = """ (declare-sort T) (declare-fun subtype (T T) Bool) ;; subtype is reflexive (assert (forall ((x T)) (subtype x x))) ;; subtype is antisymmetric (assert (forall ((x T) (y T)) (=> (and (subtype x y) (subtype y x)) (= x y)))) ;; subtype is transitive (assert (forall ((x T) (y T) (z T)) (=> (and (subtype x y) (subtype y z)) (subtype x z)))) ;; subtype has the tree-property (assert (forall ((x T) (y T) (z T)) (=> (and (subtype x z) (subtype y z)) (or (subtype x y) (subtype y x))))) ;; now we define a simple example using the axiomatization above. (declare-const obj-type T) (declare-const int-type T) (declare-const real-type T) (declare-const complex-type T) (declare-const string-type T) ;; we have an additional axiom: every type is a subtype of obj-type (assert (forall ((x T)) (subtype x obj-type))) (assert (subtype int-type real-type)) (assert (subtype real-type complex-type)) (assert (not (subtype string-type real-type))) (declare-const root-type T) (assert (subtype obj-type root-type)) """ if __name__ == "__main__": print("Solve and log inferences") print("--------------------------------------------------------") # inference logging, replay, and checking is supported for # the core enabled by setting sat.euf = true. # setting the default tactic to 'sat' bypasses other tactics that could # end up using different solvers. set_param("sat.euf", True) set_param("tactic.default_tactic", "sat") # Set a log file to trace inferences set_param("sat.smt.proof", "proof_log.smt2") s = Solver() s.from_string(example1) print(s.check()) print(s.statistics()) print("Parse the logged inferences and replay them") print("--------------------------------------------------------") # Reset the log file to an invalid (empty) file name. set_param("sat.smt.proof", "") # Turn off proof checking. It is on by default when parsing proof logs. set_param("solver.proof.check", False) s = Solver() onc = OnClause(s, lambda pr, clause : print(pr, clause)) s.from_file("proof_log.smt2") print("Parse the logged inferences and check them") print("--------------------------------------------------------") s = Solver() # Now turn on proof checking. It invokes the self-validator. # The self-validator produces log lines of the form: # (proofs +tseitin 60 +alldiff 8 +euf 3 +rup 5 +inst 6 -quant 3 -inst 2) # (verified-smt # (inst (forall (vars (x T) (y T) (z T)) (or (subtype (:var 2) (:var 1)) ... # The 'proofs' line summarizes inferences that were self-validated. # The pair +tseitin 60 indicates that 60 inferences were validated as Tseitin # encodings. # The pair -inst 2 indicates that two quantifier instantiations were not self-validated # They were instead validated using a call to SMT solving. A log for an smt invocation # is exemplified in the next line. # Note that the pair +inst 6 indicates that 6 quantifier instantations were validated # using a syntactic (cheap) check. Some quantifier instantiations based on quantifier elimination # are not simple substitutions and therefore a simple syntactic check does not suffice. set_param("solver.proof.check", True) s.from_file("proof_log.smt2") print("Verify and self-validate on the fly") print("--------------------------------------------------------") set_param("sat.smt.proof.check", True) s = Solver() s.from_string(example1) print(s.check()) print(s.statistics()) print("Verify and self-validate on the fly, but don't check rup") print("--------------------------------------------------------") set_param("sat.smt.proof.check", True) set_param("sat.smt.proof.check_rup", False) s = Solver() s.from_string(example1) print(s.check()) print(s.statistics())
4,308
36.798246
101
py
z3
z3-master/examples/python/bounded model checking/bubble_sort.py
# File name: bubble_sort.py # # BUBBLESORT - Copyright (c) June, 2020 - Matteo Nicoli from z3 import Solver, Int, Array, IntSort, And, Not, If, Select, Store, sat def init(i,j) : return And(i == 0, j == 0) def invert(A0, A1, tmp, i0, i1) : return If(Select(A0, i0) > Select(A0, i0 + 1), \ And(tmp == Select(A0, i0), \ A1 == Store(A0, i0, Select(A0, i0 + 1)), \ A1 == Store(A0, i0 + 1, tmp)), \ A1 == A0) def bsort_step(A0, A1, tmp, i0, j0, i1, j1, dim) : return If( j0 < dim - 1, \ And( \ If( i0 < dim - 1, \ And(invert(A0, A1, tmp, i0, i1),i1 == i0 + 1), \ i1 == i0 + 1), \ j1 == j0 + 1), \ And(j1 == j0 + 1, A1 == A0)) def mk_tran_condition(A, i, j, tmp, dim) : condition = [] for _ in range(dim) : condition.append(bsort_step(A[0],A[1],tmp[0],i[0],j[0],i[1],j[1],dim)) A = A[1:] i = i[1:] j = j[1:] tmp = tmp[1:] return condition def check(variables, Ar, dim) : for e in range(dim) : yield variables[e] == Select(Ar,e) def mk_post_condition(values) : condition = [v1 <= v2 for v1,v2 in zip(values,values[1:])] return And(*condition) def main() : dim = int(input("size of the array: ")) i = [Int(f"i_{x}") for x in range(dim + 1)] j = [Int(f"j_{x}") for x in range(dim + 1)] A = [Array(f"A_{x}",IntSort(),IntSort()) for x in range(dim + 1)] tmp = [Int(f"tmp_{x}") for x in range(dim)] s = Solver() init_condition = init(i[0],j[0]) s.add(init_condition) tran_condition = mk_tran_condition(A, i, j, tmp, dim) s.add(And(*tran_condition)) values = [Int(f"n_{x}") for x in range(dim)] init_check_condition = check(values,A[-1],dim) s.add(And(*init_check_condition)) post_condition = mk_post_condition(values) print("Bubble sort") print("---------------------") s.push() s.add(Not(post_condition)) print("Testing the validity of the algorithm; `valid expected`:") if s.check() == sat : print(f"counterexample:\n{s.model()}") else : print("valid") print("---------------------") s.pop() s.add(post_condition) print("Getting a model...") print("Model:") if s.check() == sat : print(s.model()) if __name__ == "__main__" : main()
2,473
25.319149
78
py
z3
z3-master/examples/python/mus/marco.py
############################################ # Copyright (c) 2016 Microsoft Corporation # # Basic core and correction set enumeration. # # Author: Nikolaj Bjorner (nbjorner) ############################################ """ Enumeration of Minimal Unsatisfiable Cores and Maximal Satisfying Subsets This tutorial illustrates how to use Z3 for extracting all minimal unsatisfiable cores together with all maximal satisfying subsets. Origin The algorithm that we describe next represents the essence of the core extraction procedure by Liffiton and Malik and independently by Previti and Marques-Silva: Enumerating Infeasibility: Finding Multiple MUSes Quickly Mark H. Liffiton and Ammar Malik in Proc. 10th International Conference on Integration of Artificial Intelligence (AI) and Operations Research (OR) techniques in Constraint Programming (CPAIOR-2013), 160-175, May 2013. Partial MUS Enumeration Alessandro Previti, Joao Marques-Silva in Proc. AAAI-2013 July 2013 Z3py Features This implementation contains no tuning. It was contributed by Mark Liffiton and it is a simplification of one of the versions available from his Marco Polo Web site. It illustrates the following features of Z3's Python-based API: 1. Using assumptions to track unsatisfiable cores. 2. Using multiple solvers and passing constraints between them. 3. Calling the C-based API from Python. Not all API functions are supported over the Python wrappers. This example shows how to get a unique integer identifier of an AST, which can be used as a key in a hash-table. Idea of the Algorithm The main idea of the algorithm is to maintain two logical contexts and exchange information between them: 1. The MapSolver is used to enumerate sets of clauses that are not already supersets of an existing unsatisfiable core and not already a subset of a maximal satisfying assignment. The MapSolver uses one unique atomic predicate per soft clause, so it enumerates sets of atomic predicates. For each minimal unsatisfiable core, say, represented by predicates p1, p2, p5, the MapSolver contains the clause !p1 | !p2 | !p5. For each maximal satisfiable subset, say, represented by predicats p2, p3, p5, the MapSolver contains a clause corresponding to the disjunction of all literals not in the maximal satisfiable subset, p1 | p4 | p6. 2. The SubsetSolver contains a set of soft clauses (clauses with the unique indicator atom occurring negated). The MapSolver feeds it a set of clauses (the indicator atoms). Recall that these are not already a superset of an existing minimal unsatisfiable core, or a subset of a maximal satisfying assignment. If asserting these atoms makes the SubsetSolver context infeasible, then it finds a minimal unsatisfiable subset corresponding to these atoms. If asserting the atoms is consistent with the SubsetSolver, then it extends this set of atoms maximally to a satisfying set. """ 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: seed = csolver.seed_from_core() MUS = csolver.shrink(seed) yield ("MUS", csolver.to_c_lits(MUS)) map.block_up(MUS) main()
6,746
35.080214
117
py
z3
z3-master/examples/python/mus/mss.py
############################################ # Copyright (c) 2016 Microsoft Corporation # # MSS enumeration based on maximal resolution. # # Author: Nikolaj Bjorner (nbjorner) ############################################ """ The following is a procedure for enumerating maximal satisfying subsets. It uses maximal resolution to eliminate cores from the state space. Whenever the hard constraints are satisfiable, it finds a model that satisfies the maximal number of soft constraints. During this process it collects the set of cores that are encountered. It then reduces the set of soft constraints using max-resolution in the style of [Narodytska & Bacchus, AAAI'14]. In other words, let F1, ..., F_k be a core among the soft constraints F1,...,F_n Replace F1,.., F_k by F1 or F2, F3 or (F2 & F1), F4 or (F3 & (F2 & F1)), ..., F_k or (F_{k-1} & (...)) Optionally, add the core ~F1 or ... or ~F_k to F The current model M satisfies the new set F, F1,...,F_{n-1} if the core is minimal. Whenever we modify the soft constraints by the core reduction any assignment to the reduced set satisfies a k-1 of the original soft constraints. """ from z3 import * def main(): x, y = Reals('x y') soft_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)] hard_constraints = BoolVal(True) solver = MSSSolver(hard_constraints, soft_constraints) for lits in enumerate_sets(solver): print("%s" % lits) def enumerate_sets(solver): while True: if sat == solver.s.check(): MSS = solver.grow() yield MSS else: break class MSSSolver: s = Solver() varcache = {} idcache = {} def __init__(self, hard, soft): self.n = len(soft) self.soft = soft self.s.add(hard) self.soft_vars = set([self.c_var(i) for i in range(self.n)]) self.orig_soft_vars = set([self.c_var(i) for i in range(self.n)]) self.s.add([(self.c_var(i) == soft[i]) for i in range(self.n)]) def c_var(self, i): if i not in self.varcache: v = Bool(str(self.soft[abs(i)])) self.idcache[v] = abs(i) if i >= 0: self.varcache[i] = v else: self.varcache[i] = Not(v) return self.varcache[i] # Retrieve the latest model # Add formulas that are true in the model to # the current mss def update_unknown(self): self.model = self.s.model() new_unknown = set([]) for x in self.unknown: if is_true(self.model[x]): self.mss.append(x) else: new_unknown.add(x) self.unknown = new_unknown # Create a name, propositional atom, # for formula 'fml' and return the name. def add_def(self, fml): name = Bool("%s" % fml) self.s.add(name == fml) return name # replace Fs := f0, f1, f2, .. by # Or(f1, f0), Or(f2, And(f1, f0)), Or(f3, And(f2, And(f1, f0))), ... def relax_core(self, Fs): assert(Fs <= self.soft_vars) prefix = BoolVal(True) self.soft_vars -= Fs Fs = [ f for f in Fs ] for i in range(len(Fs)-1): prefix = self.add_def(And(Fs[i], prefix)) self.soft_vars.add(self.add_def(Or(prefix, Fs[i+1]))) # Resolve literals from the core that # are 'explained', e.g., implied by # other literals. def resolve_core(self, core): new_core = set([]) for x in core: if x in self.mcs_explain: new_core |= self.mcs_explain[x] else: new_core.add(x) return new_core # Given a current satisfiable state # Extract an MSS, and ensure that currently # encountered cores are avoided in next iterations # by weakening the set of literals that are # examined in next iterations. # Strengthen the solver state by enforcing that # an element from the MCS is encountered. def grow(self): self.mss = [] self.mcs = [] self.nmcs = [] self.mcs_explain = {} self.unknown = self.soft_vars self.update_unknown() cores = [] while len(self.unknown) > 0: x = self.unknown.pop() is_sat = self.s.check(self.mss + [x] + self.nmcs) if is_sat == sat: self.mss.append(x) self.update_unknown() elif is_sat == unsat: core = self.s.unsat_core() core = self.resolve_core(core) self.mcs_explain[Not(x)] = {y for y in core if not eq(x,y)} self.mcs.append(x) self.nmcs.append(Not(x)) cores += [core] else: print("solver returned %s" % is_sat) exit() mss = [x for x in self.orig_soft_vars if is_true(self.model[x])] mcs = [x for x in self.orig_soft_vars if not is_true(self.model[x])] self.s.add(Or(mcs)) core_literals = set([]) cores.sort(key=lambda element: len(element)) for core in cores: if len(core & core_literals) == 0: self.relax_core(core) core_literals |= core return mss main()
5,260
31.079268
122
py
z3
z3-master/examples/python/hamiltonian/hamiltonian.py
############################################ # Copyright (c) Microsoft Corporation. All Rights Reserved. # # Check if the given graph has a Hamiltonian cycle. # # Author: Ganesh Gopalakrishnan [email protected] ############################################ from z3 import * def gencon(gr): """ Input a graph as an adjacency list, e.g. {0:[1,2], 1:[2], 2:[1,0]}. Produces solver to check if the given graph has a Hamiltonian cycle. Query the solver using s.check() and if sat, then s.model() spells out the cycle. Two example graphs from http://en.wikipedia.org/wiki/Hamiltonian_path are tested. ======================================================= Explanation: Generate a list of Int vars. Constrain the first Int var ("Node 0") to be 0. Pick a node i, and attempt to number all nodes reachable from i to have a number one higher (mod L) than assigned to node i (use an Or constraint). ======================================================= """ L = len(gr) cv = [Int('cv%s'%i) for i in range(L)] s = Solver() s.add(cv[0]==0) for i in range(L): s.add(Or([cv[j]==(cv[i]+1)%L for j in gr[i]])) return s def examples(): # Example Graphs: The Dodecahedral graph from http://en.wikipedia.org/wiki/Hamiltonian_path grdodec = { 0: [1, 4, 5], 1: [0, 7, 2], 2: [1, 9, 3], 3: [2, 11, 4], 4: [3, 13, 0], 5: [0, 14, 6], 6: [5, 16, 7], 7: [6, 8, 1], 8: [7, 17, 9], 9: [8, 10, 2], 10: [9, 18, 11], 11: [10, 3, 12], 12: [11, 19, 13], 13: [12, 14, 4], 14: [13, 15, 5], 15: [14, 16, 19], 16: [6, 17, 15], 17: [16, 8, 18], 18: [10, 19, 17], 19: [18, 12, 15] } import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint(grdodec) sdodec=gencon(grdodec) print(sdodec.check()) print(sdodec.model()) # ======================================================= # See http://en.wikipedia.org/wiki/Hamiltonian_path for the Herschel graph # being the smallest possible polyhedral graph that does not have a Hamiltonian # cycle. # grherschel = { 0: [1, 9, 10, 7], 1: [0, 8, 2], 2: [1, 9, 3], 3: [2, 8, 4], 4: [3, 9, 10, 5], 5: [4, 8, 6], 6: [5, 10, 7], 7: [6, 8, 0], 8: [1, 3, 5, 7], 9: [2, 0, 4], 10: [6, 4, 0] } pp.pprint(grherschel) sherschel=gencon(grherschel) print(sherschel.check()) # ======================================================= if __name__ == "__main__": examples()
2,941
32.05618
95
py
z3
z3-master/examples/python/complex/complex.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Complex numbers in Z3 # See http://research.microsoft.com/en-us/um/people/leonardo/blog/2013/01/26/complex.html # # Author: Leonardo de Moura (leonardo) ############################################ from __future__ import print_function import sys if sys.version_info.major >= 3: from functools import reduce from z3 import * def _to_complex(a): if isinstance(a, ComplexExpr): return a else: return ComplexExpr(a, RealVal(0)) def _is_zero(a): return (isinstance(a, int) and a == 0) or (is_rational_value(a) and a.numerator_as_long() == 0) class ComplexExpr: def __init__(self, r, i): self.r = r self.i = i def __add__(self, other): other = _to_complex(other) return ComplexExpr(self.r + other.r, self.i + other.i) def __radd__(self, other): other = _to_complex(other) return ComplexExpr(other.r + self.r, other.i + self.i) def __sub__(self, other): other = _to_complex(other) return ComplexExpr(self.r - other.r, self.i - other.i) def __rsub__(self, other): other = _to_complex(other) return ComplexExpr(other.r - self.r, other.i - self.i) def __mul__(self, other): other = _to_complex(other) return ComplexExpr(self.r*other.r - self.i*other.i, self.r*other.i + self.i*other.r) def __rmul__(self, other): other = _to_complex(other) return ComplexExpr(other.r*self.r - other.i*self.i, other.i*self.r + other.r*self.i) def __pow__(self, k): if k == 0: return ComplexExpr(1, 0) if k == 1: return self if k < 0: return (self ** (-k)).inv() return reduce(lambda x, y: x * y, [self for _ in range(k)], ComplexExpr(1, 0)) def inv(self): den = self.r*self.r + self.i*self.i return ComplexExpr(self.r/den, -self.i/den) def __div__(self, other): inv_other = _to_complex(other).inv() return self.__mul__(inv_other) if sys.version_info.major >= 3: # In python 3 the meaning of the '/' operator # was changed. def __truediv__(self, other): return self.__div__(other) def __rdiv__(self, other): other = _to_complex(other) return self.inv().__mul__(other) def __eq__(self, other): other = _to_complex(other) return And(self.r == other.r, self.i == other.i) def __neq__(self, other): return Not(self.__eq__(other)) def simplify(self): return ComplexExpr(simplify(self.r), simplify(self.i)) def repr_i(self): if is_rational_value(self.i): return "%s*I" % self.i else: return "(%s)*I" % str(self.i) def __repr__(self): if _is_zero(self.i): return str(self.r) elif _is_zero(self.r): return self.repr_i() else: return "%s + %s" % (self.r, self.repr_i()) def Complex(a): return ComplexExpr(Real('%s.r' % a), Real('%s.i' % a)) I = ComplexExpr(RealVal(0), RealVal(1)) def evaluate_cexpr(m, e): return ComplexExpr(m[e.r], m[e.i]) x = Complex("x") s = Tactic('qfnra-nlsat').solver() s.add(x*x == -2) print(s) print(s.check()) m = s.model() print('x = %s' % evaluate_cexpr(m, x)) print((evaluate_cexpr(m,x)*evaluate_cexpr(m,x)).simplify()) s.add(x.i != -1) print(s) print(s.check()) print(s.model()) s.add(x.i != 1) print(s.check()) # print(s.model()) print(((3 + I) ** 2)/(5 - I)) print(((3 + I) ** -3)/(5 - I))
3,596
27.101563
99
py
z3
z3-master/src/api/python/setup.py
import os import sys import shutil import platform import subprocess import multiprocessing import re import glob from setuptools import setup from distutils.util import get_platform from distutils.errors import LibError from distutils.command.build import build as _build from distutils.command.sdist import sdist as _sdist from distutils.command.clean import clean as _clean from setuptools.command.develop import develop as _develop from setuptools.command.bdist_egg import bdist_egg as _bdist_egg build_env = dict(os.environ) build_env['PYTHON'] = sys.executable build_env['CXXFLAGS'] = build_env.get('CXXFLAGS', '') + " -std=c++11" # determine where we're building and where sources are ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) SRC_DIR_LOCAL = os.path.join(ROOT_DIR, 'core') SRC_DIR_REPO = os.path.join(ROOT_DIR, '..', '..', '..') SRC_DIR = SRC_DIR_LOCAL if os.path.exists(SRC_DIR_LOCAL) else SRC_DIR_REPO # determine where binaries are RELEASE_DIR = os.environ.get('PACKAGE_FROM_RELEASE', None) if RELEASE_DIR is None: BUILD_DIR = os.path.join(SRC_DIR, 'build') # implicit in configure script HEADER_DIRS = [os.path.join(SRC_DIR, 'src', 'api'), os.path.join(SRC_DIR, 'src', 'api', 'c++')] RELEASE_METADATA = None BUILD_PLATFORM = sys.platform else: if not os.path.isdir(RELEASE_DIR): raise Exception("RELEASE_DIR (%s) is not a directory!" % RELEASE_DIR) BUILD_DIR = os.path.join(RELEASE_DIR, 'bin') HEADER_DIRS = [os.path.join(RELEASE_DIR, 'include')] RELEASE_METADATA = os.path.basename(RELEASE_DIR).split('-') if RELEASE_METADATA[0] != 'z3' or len(RELEASE_METADATA) not in (4, 5): raise Exception("RELEASE_DIR (%s) must be in the format z3-version-arch-os[-osversion] so we can extract metadata from it. Sorry!" % RELEASE_DIR) RELEASE_METADATA.pop(0) BUILD_PLATFORM = RELEASE_METADATA[2] # determine where destinations are LIBS_DIR = os.path.join(ROOT_DIR, 'z3', 'lib') HEADERS_DIR = os.path.join(ROOT_DIR, 'z3', 'include') BINS_DIR = os.path.join(ROOT_DIR, 'bin') # determine platform-specific filenames if BUILD_PLATFORM in ('darwin', 'osx'): LIBRARY_FILE = "libz3.dylib" EXECUTABLE_FILE = "z3" elif BUILD_PLATFORM in ('win32', 'cygwin', 'win'): LIBRARY_FILE = "libz3.dll" EXECUTABLE_FILE = "z3.exe" else: LIBRARY_FILE = "libz3.so" EXECUTABLE_FILE = "z3" def rmtree(tree): if os.path.exists(tree): shutil.rmtree(tree, ignore_errors=False) def _clean_bins(): """ Clean up the binary files and headers that are installed along with the bindings """ rmtree(LIBS_DIR) rmtree(BINS_DIR) rmtree(HEADERS_DIR) def _clean_native_build(): """ Clean the "build" directory in the z3 native root """ rmtree(BUILD_DIR) def _z3_version(): post = os.getenv('Z3_VERSION_SUFFIX', '') if RELEASE_DIR is None: fn = os.path.join(SRC_DIR, 'scripts', 'mk_project.py') if os.path.exists(fn): with open(fn) as f: for line in f: n = re.match(r".*set_version\((.*), (.*), (.*), (.*)\).*", line) if not n is None: return n.group(1) + '.' + n.group(2) + '.' + n.group(3) + '.' + n.group(4) + post return "?.?.?.?" else: version = RELEASE_METADATA[0] if version.count('.') == 2: version += '.0' return version + post def _configure_z3(): # bail out early if we don't need to do this - it forces a rebuild every time otherwise if os.path.exists(BUILD_DIR): return else: os.mkdir(BUILD_DIR) # Config options cmake_options = { # Config Options 'Z3_SINGLE_THREADED' : False, 'Z3_BUILD_PYTHON_BINDINGS' : True, # Build Options 'CMAKE_BUILD_TYPE' : 'Release', 'Z3_BUILD_EXECUTABLE' : True, 'Z3_BUILD_LIBZ3_SHARED' : True, 'Z3_LINK_TIME_OPTIMIZATION' : True, 'WARNINGS_AS_ERRORS' : 'SERIOUS_ONLY', # Disable Unwanted Options 'Z3_USE_LIB_GMP' : False, # Is default false in python build 'Z3_INCLUDE_GIT_HASH' : False, # Can be changed if we bundle the .git as well 'Z3_INCLUDE_GIT_DESCRIBE' : False, 'Z3_SAVE_CLANG_OPTIMIZATION_RECORDS' : False, 'Z3_ENABLE_TRACING_FOR_NON_DEBUG' : False, 'Z3_ENABLE_EXAMPLE_TARGETS' : False, 'Z3_ENABLE_CFI' : False, 'Z3_BUILD_DOCUMENTATION' : False, 'Z3_BUILD_TEST_EXECUTABLES' : False, 'Z3_BUILD_DOTNET_BINDINGS' : False, 'Z3_BUILD_JAVA_BINDINGS' : False } # Convert cmake options to CLI arguments for key, val in cmake_options.items(): if type(val) is bool: cmake_options[key] = str(val).upper() # Allow command-line arguments to add and override Z3_ options for i in range(len(sys.argv) - 1): key = sys.argv[i] if key.startswith("Z3_"): val = sys.argv[i + 1].upper() if val == "TRUE" or val == "FALSE": cmake_options[key] = val cmake_args = [ '-D' + key + '=' + value for key,value in cmake_options.items() ] args = [ 'cmake', *cmake_args, SRC_DIR ] if subprocess.call(args, env=build_env, cwd=BUILD_DIR) != 0: raise LibError("Unable to configure Z3.") def _build_z3(): if sys.platform == 'win32': if subprocess.call(['nmake'], env=build_env, cwd=BUILD_DIR) != 0: raise LibError("Unable to build Z3.") else: # linux and macOS if subprocess.call(['make', '-j', str(multiprocessing.cpu_count())], env=build_env, cwd=BUILD_DIR) != 0: raise LibError("Unable to build Z3.") def _copy_bins(): """ Copy the library and header files into their final destinations """ # STEP 1: If we're performing a build from a copied source tree, # copy the generated python files into the package _clean_bins() py_z3_build_dir = os.path.join(BUILD_DIR, 'python', 'z3') root_z3_dir = os.path.join(ROOT_DIR, 'z3') shutil.copy(os.path.join(py_z3_build_dir, 'z3core.py'), root_z3_dir) shutil.copy(os.path.join(py_z3_build_dir, 'z3consts.py'), root_z3_dir) # STEP 2: Copy the shared library, the executable and the headers os.mkdir(LIBS_DIR) os.mkdir(BINS_DIR) os.mkdir(HEADERS_DIR) shutil.copy(os.path.join(BUILD_DIR, LIBRARY_FILE), LIBS_DIR) shutil.copy(os.path.join(BUILD_DIR, EXECUTABLE_FILE), BINS_DIR) path1 = glob.glob(os.path.join(BUILD_DIR, "msvcp*")) path2 = glob.glob(os.path.join(BUILD_DIR, "vcomp*")) path3 = glob.glob(os.path.join(BUILD_DIR, "vcrun*")) for filepath in path1 + path2 + path3: shutil.copy(filepath, LIBS_DIR) for header_dir in HEADER_DIRS: for fname in os.listdir(header_dir): if not fname.endswith('.h'): continue shutil.copy(os.path.join(header_dir, fname), os.path.join(HEADERS_DIR, fname)) # This hack lets z3 installed libs link on M1 macs; it is a hack, not a proper fix # @TODO: Linked issue: https://github.com/Z3Prover/z3/issues/5926 major_minor = '.'.join(_z3_version().split('.')[:2]) link_name = None if BUILD_PLATFORM in ('win32', 'cygwin', 'win'): pass # TODO: When windows VMs work on M1, fill this in elif BUILD_PLATFORM in ('darwin', 'osx'): split = LIBRARY_FILE.split('.') link_name = split[0] + '.' + major_minor + '.' + split[1] else: link_name = LIBRARY_FILE + '.' + major_minor if link_name: os.symlink(LIBRARY_FILE, os.path.join(LIBS_DIR, link_name), True) def _copy_sources(): """ Prepare for a source distribution by assembling a minimal set of source files needed for building """ shutil.rmtree(SRC_DIR_LOCAL, ignore_errors=True) os.mkdir(SRC_DIR_LOCAL) shutil.copy(os.path.join(SRC_DIR_REPO, 'LICENSE.txt'), SRC_DIR_LOCAL) shutil.copy(os.path.join(SRC_DIR_REPO, 'z3.pc.cmake.in'), SRC_DIR_LOCAL) shutil.copy(os.path.join(SRC_DIR_REPO, 'CMakeLists.txt'), SRC_DIR_LOCAL) shutil.copytree(os.path.join(SRC_DIR_REPO, 'cmake'), os.path.join(SRC_DIR_LOCAL, 'cmake')) shutil.copytree(os.path.join(SRC_DIR_REPO, 'scripts'), os.path.join(SRC_DIR_LOCAL, 'scripts')) # Copy in src, but avoid recursion def ignore_python_setup_files(src, _): if os.path.normpath(src).endswith('api/python'): return ['core', 'dist', 'MANIFEST', 'MANIFEST.in', 'setup.py', 'z3_solver.egg-info'] return [] shutil.copytree(os.path.join(SRC_DIR_REPO, 'src'), os.path.join(SRC_DIR_LOCAL, 'src'), ignore=ignore_python_setup_files) class build(_build): def run(self): if RELEASE_DIR is None: self.execute(_configure_z3, (), msg="Configuring Z3") self.execute(_build_z3, (), msg="Building Z3") self.execute(_copy_bins, (), msg="Copying binaries") _build.run(self) class develop(_develop): def run(self): self.execute(_configure_z3, (), msg="Configuring Z3") self.execute(_build_z3, (), msg="Building Z3") self.execute(_copy_bins, (), msg="Copying binaries") _develop.run(self) class bdist_egg(_bdist_egg): def run(self): self.run_command('build') _bdist_egg.run(self) class sdist(_sdist): def run(self): self.execute(_clean_bins, (), msg="Cleaning binary files and headers") self.execute(_copy_sources, (), msg="Copying source files") _sdist.run(self) class clean(_clean): def run(self): self.execute(_clean_bins, (), msg="Cleaning binary files and headers") self.execute(_clean_native_build, (), msg="Cleaning native build") _clean.run(self) # the build directory needs to exist #try: os.makedirs(os.path.join(ROOT_DIR, 'build')) #except OSError: pass # platform.freedesktop_os_release was added in 3.10 os_id = '' if hasattr(platform, 'freedesktop_os_release'): try: osr = platform.freedesktop_os_release() print(osr) os_id = osr['ID'] except OSError: pass if 'bdist_wheel' in sys.argv and '--plat-name' not in sys.argv: if RELEASE_DIR is None: name = get_platform() if 'linux' in name: # linux_* platform tags are disallowed because the python ecosystem is fubar # linux builds should be built in the centos 5 vm for maximum compatibility # see https://github.com/pypa/manylinux # see also https://github.com/angr/angr-dev/blob/master/admin/bdist.py plat_name = 'manylinux2014_' + platform.machine() elif 'mingw' in name: if platform.architecture()[0] == '64bit': plat_name = 'win_amd64' else: plat_name ='win32' else: # https://www.python.org/dev/peps/pep-0425/ plat_name = name.replace('.', '_').replace('-', '_') else: # extract the architecture of the release from the directory name arch = RELEASE_METADATA[1] distos = RELEASE_METADATA[2] if distos in ('debian', 'ubuntu'): raise Exception( "Linux binary distributions must be built on centos to conform to PEP 513 or alpine if targeting musl" ) elif distos == 'glibc': if arch == 'x64': plat_name = 'manylinux2014_x86_64' else: plat_name = 'manylinux2014_i686' elif distos == 'linux' and os_id == 'alpine': if arch == 'x64': plat_name = 'musllinux_1_1_x86_64' else: plat_name = 'musllinux_1_1_i686' elif distos == 'win': if arch == 'x64': plat_name = 'win_amd64' else: plat_name = 'win32' elif distos == 'osx': osver = RELEASE_METADATA[3] if osver.count('.') > 1: osver = '.'.join(osver.split('.')[:2]) if arch == 'x64': plat_name ='macosx_%s_x86_64' % osver.replace('.', '_') elif arch == 'arm64': plat_name ='macosx_%s_arm64' % osver.replace('.', '_') else: raise Exception(f"idk how os {distos} {osver} works. what goes here?") else: raise Exception(f"idk how to translate between this z3 release os {distos} and the python naming scheme") idx = sys.argv.index('bdist_wheel') + 1 sys.argv.insert(idx, '--plat-name') sys.argv.insert(idx + 1, plat_name) sys.argv.insert(idx + 2, '--universal') # supports py2+py3. if --plat-name is not specified this will also mean that the package can be installed on any machine regardless of architecture, so watch out! setup( name='z3-solver', version=_z3_version(), description='an efficient SMT solver library', long_description='Z3 is a theorem prover from Microsoft Research with support for bitvectors, booleans, arrays, floating point numbers, strings, and other data types.\n\nFor documentation, please read http://z3prover.github.io/api/html/z3.html\n\nIn the event of technical difficulties related to configuration, compilation, or installation, please submit issues to https://github.com/z3prover/z3.git', author="The Z3 Theorem Prover Project", maintainer="Audrey Dutcher and Nikolaj Bjorner", maintainer_email="[email protected]", url='https://github.com/Z3Prover/z3', license='MIT License', keywords=['z3', 'smt', 'sat', 'prover', 'theorem'], packages=['z3'], include_package_data=True, package_data={ 'z3': [os.path.join('lib', '*'), os.path.join('include', '*.h'), os.path.join('include', 'c++', '*.h')] }, data_files=[('bin',[os.path.join('bin',EXECUTABLE_FILE)])], cmdclass={'build': build, 'develop': develop, 'sdist': sdist, 'bdist_egg': bdist_egg, 'clean': clean}, )
13,960
39.002865
406
py
z3
z3-master/src/api/python/z3test.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface # # Author: Leonardo de Moura (leonardo) ############################################ import z3, doctest, sys if len(sys.argv) < 2 or sys.argv[1] == 'z3': r = doctest.testmod(z3.z3) elif sys.argv[1] == 'z3num': r = doctest.testmod(z3.z3num) else: print('Usage: z3test.py (z3 | z3num)') sys.exit(1) if r.failed != 0: sys.exit(1)
464
21.142857
44
py
z3
z3-master/src/api/python/z3/z3rcf.py
############################################ # Copyright (c) 2013 Microsoft Corporation # # Z3 Python interface for Z3 Real Closed Fields # that may contain # - computable transcendentals # - infinitesimals # - algebraic extensions # # Author: Leonardo de Moura (leonardo) ############################################ from .z3 import * from .z3core import * from .z3printer import * 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))
5,039
28.822485
84
py
z3
z3-master/src/api/python/z3/z3poly.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface for Z3 polynomials # # Author: Leonardo de Moura (leonardo) ############################################ from .z3 import * def subresultants(p, q, x): """ Return the non-constant subresultants of 'p' and 'q' with respect to the "variable" 'x'. 'p', 'q' and 'x' are Z3 expressions where 'p' and 'q' are arithmetic terms. Note that, any subterm that cannot be viewed as a polynomial is assumed to be a variable. Example: f(a) is a considered to be a variable b in the polynomial f(a)*f(a) + 2*f(a) + 1 >>> x, y = Reals('x y') >>> subresultants(2*x + y, 3*x - 2*y + 2, x) [-7*y + 4] >>> r = subresultants(3*y*x**2 + y**3 + 1, 2*x**3 + y + 3, x) >>> r[0] 4*y**9 + 12*y**6 + 27*y**5 + 162*y**4 + 255*y**3 + 4 >>> r[1] -6*y**4 + -6*y """ return AstVector(Z3_polynomial_subresultants(p.ctx_ref(), p.as_ast(), q.as_ast(), x.as_ast()), p.ctx) if __name__ == "__main__": import doctest if doctest.testmod().failed: exit(1)
1,113
28.315789
105
py
z3
z3-master/src/api/python/z3/z3types.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface # # Author: Leonardo de Moura (leonardo) ############################################ 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 SimplifierObj(ctypes.c_void_p): def __init__(self, simplifier): self._as_parameter_ = simplifier 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 SolverCallbackObj(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 ParserContextObj(ctypes.c_void_p): def __init__(self, pc): self._as_parameter_ = pc 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
4,883
18.152941
46
py
z3
z3-master/src/api/python/z3/z3util.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface # # Authors: Leonardo de Moura (leonardo) # ThanhVu (Vu) Nguyen <[email protected]> ############################################ """ Usage: import common_z3 as CM_Z3 """ import ctypes 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=None): """ >>> 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 rs is None: rs = [] 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: raise TypeError("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 is 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 is 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 satisfying 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(val, bool) for val in L) L = [val for val in L if is_expr(val)] if L: if len(L) == 1: return L[0] if op == Z3_OP_OR: return Or(L) if op == Z3_OP_AND: return And(L) 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]) def Iff(f): return 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 examples 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
11,387
21.640159
97
py
z3
z3-master/src/api/python/z3/z3.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface # # Author: Leonardo de Moura (leonardo) ############################################ """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 silico analysis), and geometrical problems. Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable. Small example: >>> x = Int('x') >>> y = Int('y') >>> s = Solver() >>> s.add(x > 0) >>> s.add(x < 2) >>> s.add(y == x + 1) >>> s.check() sat >>> m = s.model() >>> m[x] 1 >>> m[y] 2 Z3 exceptions: >>> try: ... x = BitVec('x', 32) ... y = Bool('y') ... # the expression x + y is type incorrect ... n = x + y ... except Z3Exception as ex: ... print("failed: %s" % ex) failed: sort mismatch """ 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 if sys.version_info.major >= 3: from typing import Iterable Z3_DEBUG = __debug__ def z3_debug(): global Z3_DEBUG return Z3_DEBUG if sys.version_info.major < 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() 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 TypeError: # 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, AstVector, tuple)): return [arg for arg in args] else: return args except Exception: return args def _to_param_value(val): if isinstance(val, bool): return "true" if val else "false" 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.owner = True 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): if Z3_del_context is not None and self.owner: 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()) def param_descrs(self): """Return the global parameter description set.""" return ParamDescrsRef(Z3_get_global_param_descrs(self.ref()), self) # 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 and Z3_dec_ref 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) elif k == Z3_CHAR_SORT: return CharSortRef(s, ctx) elif k == Z3_TYPE_VAR: return TypeVarRef(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) class TypeVarRef(SortRef): """Type variable reference""" def subsort(self, other): return True def cast(self, val): return val def DeclareTypeVar(name, ctx=None): """Create a new type variable named `name`. If `ctx=None`, then the new sort is declared in the global Z3Py context. """ ctx = _get_ctx(ctx) return TypeVarRef(Z3_mk_type_variable(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 """ 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) _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 can be simplified if they are applied to ground arguments. >>> 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)) 120 >>> 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 from_string(self, s): pass def serialize(self): s = Solver() f = Function('F', self.sort(), BoolSort(self.ctx)) s.add(f(self)) return s.sexpr() def deserialize(st): """inverse function to the serialize method on ExprRef. It is made available to make it easier for users to serialize expressions back and forth between strings. Solvers can be serialized using the 'sexpr()' method. """ s = Solver() s.from_string(st) if len(s.assertions()) != 1: raise Z3Exception("single assertion expected") fml = s.assertions()[0] if fml.num_args() != 1: raise Z3Exception("dummy function 'F' expected") return fml.arg(0) 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_CHAR_SORT: return CharRef(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) if isinstance(a, str) and isinstance(b, SeqRef): a = StringVal(a, b.ctx) if isinstance(b, str) and isinstance(a, SeqRef): b = StringVal(b, a.ctx) if isinstance(a, float) and isinstance(b, ArithRef): a = RealVal(a, b.ctx) if isinstance(b, float) and isinstance(a, ArithRef): b = RealVal(b, a.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(func, sequence, initial): result = initial for element in sequence: result = func(result, element) return result 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. A free variable with index n is bound when it occurs within the scope of n+1 quantified declarations. >>> 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): msg = "True, False or Z3 Boolean expression expected. Received %s of type %s" _z3_assert(is_expr(val), msg % (val, type(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 isinstance(other, int) and other == 1: return If(self, 1, 0) if isinstance(other, int) and other == 0: return IntVal(0, self.ctx) if isinstance(other, BoolRef): other = If(other, 1, 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: return BoolRef(Z3_mk_true(ctx.ref()), ctx) else: return BoolRef(Z3_mk_false(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 = None args = _get_args(args) ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx)) if z3_debug(): _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] elif len(args) == 1 and isinstance(args[0], AstVector): ctx = args[0].ctx args = [a for a in args[0]] else: ctx = None args = _get_args(args) ctx = _get_ctx(_ctx_from_ast_arg_list(args, ctx)) if z3_debug(): _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") return _array_select(self, arg) 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 is_bool(self): return False 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(): msg = "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" _z3_assert(False, msg % 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()) def as_binary_string(self): """Return a Z3 integer numeral as a Python binary string. >>> v = IntVal(10) >>> v.as_binary_string() '1010' """ return Z3_get_numeral_binary_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 poly(self): return AstVector(Z3_algebraic_get_poly(self.ctx_ref(), self.as_ast()), self.ctx) def index(self): return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast()) 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 isinstance(a, str): return StringVal(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" else: return str(val) 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, ctx=ctx)) 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 """ ctx = _get_ctx(ctx) return [Int("%s__%s" % (prefix, i), ctx) 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 """ ctx = _get_ctx(ctx) return [Real("%s__%s" % (prefix, i), ctx) 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 as_binary_string(self): return Z3_get_numeral_binary_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. Extract is overloaded to also work on sequence extraction. The functions SubString and SubSeq are redirected to Extract. For this case, the arguments are reinterpreted as: high - is a sequence (string) low - is an offset a - is the length to be extracted >>> 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 domain_n(self, i): """Return the domain of the array sort `self`. """ return _to_sort_ref(Z3_get_array_sort_domain_n(self.ctx_ref(), self.ast, i), 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 domain_n(self, i): """Shorthand for self.sort().domain_n(i)`.""" return self.sort().domain_n(i) 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)' """ return _array_select(self, arg) def default(self): return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx) def _array_select(ar, arg): if isinstance(arg, tuple): args = [ar.sort().domain_n(i).cast(arg[i]) for i in range(len(arg))] _args, sz = _to_ast_array(args) return _to_expr_ref(Z3_mk_select_n(ar.ctx_ref(), ar.as_ast(), sz, _args), ar.ctx) arg = ar.sort().domain().cast(arg) return _to_expr_ref(Z3_mk_select(ar.ctx_ref(), ar.as_ast(), arg.as_ast()), ar.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), ), ctx=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, *sorts): """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(sorts) ctx = s.ctx return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx) def Update(a, *args): """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") args = _get_args(args) ctx = a.ctx if len(args) <= 1: raise Z3Exception("array update requires index and value arguments") if len(args) == 2: i = args[0] v = args[1] i = a.sort().domain().cast(i) v = a.sort().range().cast(v) return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx) v = a.sort().range().cast(args[-1]) idxs = [a.sort().domain_n(i).cast(args[i]) for i in range(len(args)-1)] _args, sz = _to_ast_array(idxs) return _to_expr_ref(Z3_mk_store_n(ctx.ref(), a.as_ast(), sz, _args, 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, *args): """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, args) def Select(a, *args): """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 """ args = _get_args(args) if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a[args] 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) or b.is_lambda()), "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). """ if not isinstance(acc, tuple): return False if len(acc) != 2: return False return 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 and Z3_del_constructor 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 and Z3_del_constructor_list 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), ctx=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 DatatypeSort(name, ctx = None): """Create a reference to a sort that was declared, or will be declared, as a recursive datatype""" ctx = _get_ctx(ctx) return DatatypeSortRef(Z3_mk_datatype_sort(ctx.ref(), to_symbol(name, ctx)), 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]), "Enumeration 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 and Z3_params_dec_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 and Z3_param_descrs_dec_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 __del__(self): if self.goal is not None and self.ctx.ref() is not None and Z3_goal_dec_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, include_names=True): """Return a textual representation of the goal in DIMACS format.""" return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal, include_names) 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 __del__(self): if self.vector is not None and self.ctx.ref() is not None and Z3_ast_vector_dec_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): result = [] for ii in range(*i.indices(self.__len__())): result.append(_to_ast_ref( Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx, )) return result 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()), ctx=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 and Z3_ast_map_dec_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 and Z3_func_entry_dec_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 __del__(self): if self.f is not None and self.ctx.ref() is not None and Z3_func_interp_dec_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 and Z3_model_dec_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 """ num_consts = int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) num_funcs = int(Z3_model_get_num_funcs(self.ctx.ref(), self.model)) return num_consts + num_funcs 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): fi = self.get_interp(get_as_array_func(r)) if fi is None: return fi e = fi.else_value() if e is None: return fi if fi.arity() != 1: return fi srt = decl.range() dom = srt.domain() e = K(dom, e) i = 0 sz = fi.num_entries() n = fi.arity() while i < sz: fe = fi.entry(i) e = Store(e, fe.arg_value(0), fe.value()) i += 1 return e 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!1, A!val!0] """ 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 update_value(self, x, value): """Update the interpretation of a constant""" if is_expr(x): x = x.decl() if is_func_decl(x) and x.arity() != 0 and isinstance(value, FuncInterp): fi1 = value.f fi2 = Z3_add_func_interp(x.ctx_ref(), self.model, x.ast, value.else_value().ast); fi2 = FuncInterp(fi2, x.ctx) for i in range(value.num_entries()): e = value.entry(i) n = Z3_func_entry_get_num_args(x.ctx_ref(), e.entry) v = AstVector() for j in range(n): v.push(e.arg_value(j)) val = Z3_func_entry_get_value(x.ctx_ref(), e.entry) Z3_func_interp_add_entry(x.ctx_ref(), fi2.f, v.vector, val) return if not is_func_decl(x) or x.arity() != 0: raise Z3Exception("Expecting 0-ary function or constant expression") value = _py2expr(value) Z3_add_const_interp(x.ctx_ref(), self.model, x.ast, value.ast) 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 ModelRef(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 and Z3_stats_dec_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("smtlib2_log", logFile) def __del__(self): if self.solver is not None and self.ctx.ref() is not None and Z3_solver_dec_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() 0 >>> s.push() >>> s.num_scopes() 1 >>> s.push() >>> s.num_scopes() 2 >>> s.pop() >>> s.num_scopes() 1 """ 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 """ s = BoolSort(self.ctx) assumptions = _get_args(assumptions) num = len(assumptions) _assumptions = (Ast * num)() for i in range(num): _assumptions[i] = s.cast(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 interrupt(self): """Interrupt the execution of the solver object. Remarks: This ensures that the interrupt applies only to the given solver object and it applies only if it is running. """ Z3_solver_interrupt(self.ctx.ref(), 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 root(self, t): t = _py2expr(t, self.ctx) """Retrieve congruence closure root of the term t relative to the current search state The function primarily works for SimpleSolver. Terms and variables that are eliminated during pre-processing are not visible to the congruence closure. """ return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx) def next(self, t): t = _py2expr(t, self.ctx) """Retrieve congruence closure sibling of the term t relative to the current search state The function primarily works for SimpleSolver. Terms and variables that are eliminated during pre-processing are not visible to the congruence closure. """ return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx) 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 and Z3_fixedpoint_dec_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) _on_models = {} def _global_on_model(ctx): (fn, mdl) = _on_models[ctx] fn(mdl) _on_model_eh = on_model_eh_type(_global_on_model) 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()) self._on_models_id = None 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 and Z3_optimize_dec_ref is not None: Z3_optimize_dec_ref(self.ctx.ref(), self.optimize) if self._on_models_id is not None: del _on_models[self._on_models_id] 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) def asoft(a): v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id) return OptimizeObjective(self, v, False) if sys.version_info.major >= 3 and isinstance(arg, Iterable): return [asoft(a) for a in arg] return asoft(arg) def maximize(self, arg): """Add objective function to maximize.""" return OptimizeObjective( self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), is_max=True, ) def minimize(self, arg): """Add objective function to minimize.""" return OptimizeObjective( self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), is_max=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) def set_on_model(self, on_model): """Register a callback that is invoked with every incremental improvement to objective values. The callback takes a model as argument. The life-time of the model is limited to the callback so the model has to be (deep) copied if it is to be used after the callback """ id = len(_on_models) + 41 mdl = Model(self.ctx) _on_models[id] = (on_model, mdl) self._on_models_id = id Z3_optimize_register_model_eh( self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh, ) ######################################### # # 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 and Z3_apply_result_dec_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))]) ######################################### # # Simplifiers # ######################################### class Simplifier: """Simplifiers act as pre-processing utilities for solvers. Build a custom simplifier and add it to a solver""" def __init__(self, simplifier, ctx=None): self.ctx = _get_ctx(ctx) self.simplifier = None if isinstance(simplifier, SimplifierObj): self.simplifier = simplifier elif isinstance(simplifier, list): simps = [Simplifier(s, ctx) for s in simplifier] self.simplifier = simps[0].simplifier for i in range(1, len(simps)): self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier) Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier) return else: if z3_debug(): _z3_assert(isinstance(simplifier, str), "simplifier name expected") try: self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier)) except Z3Exception: raise Z3Exception("unknown simplifier '%s'" % simplifier) Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier) def __deepcopy__(self, memo={}): return Simplifier(self.simplifier, self.ctx) def __del__(self): if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None: Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier) def using_params(self, *args, **keys): """Return a simplifier that uses the given configuration options""" p = args2params(args, keys, self.ctx) return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx) def add(self, solver): """Return a solver that applies the simplification pre-processing specified by the simplifier""" return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx) def help(self): """Display a string containing a description of the available options for the `self` simplifier.""" print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier)) def param_descrs(self): """Return the parameter description set.""" return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx) ######################################### # # 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 and Z3_tactic_dec_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, 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 and Z3_probe_dec_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, 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]) for p in m]), "Z3 invalid substitution, expression pairs expected.") _z3_assert( all([p[0].sort().eq(p[1].sort()) for p in m]), 'Z3 invalid substitution, mismatching "from" and "to" sorts.') 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 substitute_funs(t, *m): """Apply substitution m on t, m is a list of pairs of a function and expression (from, to) Every occurrence in to of the function from is replaced with the expression to. The expression to can have free variables, that refer to the arguments of from. For examples, see """ 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_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, funcion pairs expected.") num = len(m) _from = (FuncDecl * num)() _to = (Ast * num)() for i in range(num): _from[i] = m[i][0].as_func_decl() _to[i] = m[i][1].as_ast() return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _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 Abs(arg): """Create the absolute value of an arithmetic expression""" return If(arg > 0, arg, -arg) 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, args 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, args = _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, args = _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 equality 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, args = _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] """ show = keywords.pop("show", False) s = Solver() s.set(**keywords) s.add(*args) if show: 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. """ show = keywords.pop("show", False) if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if show: 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 show: print("Solution:") print(s.model()) def prove(claim, show=False, **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 show: 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` that renders HTML output.""" show = keywords.pop("show", False) s = Solver() s.set(**keywords) s.add(*args) if show: 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 show: print("<b>Solution:</b>") print(s.model()) def _solve_using_html(s, *args, **keywords): """Version of function `solve_using` that renders HTML.""" show = keywords.pop("show", False) if z3_debug(): _z3_assert(isinstance(s, Solver), "Solver object expected") s.set(**keywords) s.add(*args) if show: 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 show: print("<b>Solution:</b>") print(s.model()) def _prove_html(claim, show=False, **keywords): """Version of function `prove` that renders HTML.""" if z3_debug(): _z3_assert(is_bool(claim), "Z3 Boolean expression expected") s = Solver() s.set(**keywords) s.add(Not(claim)) if show: 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 class ParserContext: def __init__(self, ctx= None): self.ctx = _get_ctx(ctx) self.pctx = Z3_mk_parser_context(self.ctx.ref()) Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx) def __del__(self): if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None: Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx) self.pctx = None def add_sort(self, sort): Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast()) def add_decl(self, decl): Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast()) def from_string(self, s): return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx) 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_NEAREST_TIES_TO_EVEN _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) _ROUNDING_MODES = frozenset({ Z3_OP_FPA_RM_TOWARD_ZERO, Z3_OP_FPA_RM_TOWARD_NEGATIVE, Z3_OP_FPA_RM_TOWARD_POSITIVE, Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN, Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY }) 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 in _ROUNDING_MODES, "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] is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")") if is_repr or _is_int(a) or isinstance(a, (float, 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): num = (ctypes.c_int)() nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num)) if nsign is False: raise Z3Exception("error retrieving the sign of a numeral.") return num.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) 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) x + y >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ fpAdd(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) 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) 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) 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) class CharSortRef(SortRef): """Character sort.""" 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 CharSort(ctx=None): """Create a character sort >>> ch = CharSort() >>> print(ch) Char """ ctx = _get_ctx(ctx) return CharSortRef(Z3_mk_char_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 _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __lt__(self, other): return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def __ge__(self, other): return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def __gt__(self, other): return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx) def _coerce_char(ch, ctx=None): if isinstance(ch, str): ctx = _get_ctx(ctx) ch = CharVal(ch, ctx) if not is_expr(ch): raise Z3Exception("Character expression expected") return ch class CharRef(ExprRef): """Character expression.""" def __le__(self, other): other = _coerce_char(other, self.ctx) return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx) def to_int(self): return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx) def to_bv(self): return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx) def is_digit(self): return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx) def CharVal(ch, ctx=None): ctx = _get_ctx(ctx) if isinstance(ch, str): ch = ord(ch) if not isinstance(ch, int): raise Z3Exception("character value should be an ordinal") return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx) def CharFromBv(ch, ctx=None): if not is_expr(ch): raise Z3Expression("Bit-vector expression needed") return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx) def CharToBv(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.to_bv() def CharToInt(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.to_int() def CharIsDigit(ch, ctx=None): ch = _coerce_char(ch, ctx) return ch.is_digit() 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""" s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s) ctx = _get_ctx(ctx) return SeqRef(Z3_mk_string(ctx.ref(), 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 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 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 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, offset=None): """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 """ if offset is None: offset = IntVal(0) 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 StrToCode(s): """Convert a unit length string to integer code""" if not is_expr(s): s = _py2expr(s) return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx) def StrFromCode(c): """Convert code to a string""" if not is_expr(c): c = _py2expr(c) return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.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 """ if z3_debug(): _z3_assert(is_expr(re), "expression expected") 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 """ if z3_debug(): _z3_assert(is_expr(re), "expression expected") 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 """ if z3_debug(): _z3_assert(is_expr(re), "expression expected") 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 """ if z3_debug(): _z3_assert(is_expr(re), "expression expected") 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) if z3_debug(): _z3_assert(is_expr(lo), "expression expected") _z3_assert(is_expr(hi), "expression expected") return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx) def Diff(a, b, ctx=None): """Create the difference regular expression """ if z3_debug(): _z3_assert(is_expr(a), "expression expected") _z3_assert(is_expr(b), "expression expected") return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx) def AllChar(regex_sort, ctx=None): """Create a regular expression that accepts all single character strings """ return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.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) def to_Ast(ptr,): ast = Ast(ptr) super(ctypes.c_void_p, ast).__init__(ptr) return ast def to_ContextObj(ptr,): ctx = ContextObj(ptr) super(ctypes.c_void_p, ctx).__init__(ptr) return ctx def to_AstVectorObj(ptr,): v = AstVectorObj(ptr) super(ctypes.c_void_p, v).__init__(ptr) return v # NB. my-hacky-class only works for a single instance of OnClause # it should be replaced with a proper correlation between OnClause # and object references that can be passed over the FFI. # for UserPropagator we use a global dictionary, which isn't great code. _my_hacky_class = None def on_clause_eh(ctx, p, clause): onc = _my_hacky_class p = _to_expr_ref(to_Ast(p), onc.ctx) clause = AstVector(to_AstVectorObj(clause), onc.ctx) onc.on_clause(p, clause) _on_clause_eh = Z3_on_clause_eh(on_clause_eh) class OnClause: def __init__(self, s, on_clause): self.s = s self.ctx = s.ctx self.on_clause = on_clause self.idx = 22 global _my_hacky_class _my_hacky_class = self Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh) class PropClosures: def __init__(self): self.bases = {} self.lock = None def set_threaded(self): if self.lock is None: import threading self.lock = threading.Lock() def get(self, ctx): if self.lock: with self.lock: r = self.bases[ctx] else: r = self.bases[ctx] return r def set(self, ctx, r): if self.lock: with self.lock: self.bases[ctx] = r else: self.bases[ctx] = r def insert(self, r): if self.lock: with self.lock: id = len(self.bases) + 3 self.bases[id] = r else: id = len(self.bases) + 3 self.bases[id] = r return id _prop_closures = None def ensure_prop_closures(): global _prop_closures if _prop_closures is None: _prop_closures = PropClosures() def user_prop_push(ctx, cb): prop = _prop_closures.get(ctx) prop.cb = cb prop.push() def user_prop_pop(ctx, cb, num_scopes): prop = _prop_closures.get(ctx) prop.cb = cb prop.pop(num_scopes) def user_prop_fresh(ctx, _new_ctx): _prop_closures.set_threaded() prop = _prop_closures.get(ctx) nctx = Context() Z3_del_context(nctx.ctx) new_ctx = to_ContextObj(_new_ctx) nctx.ctx = new_ctx nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler) nctx.owner = False new_prop = prop.fresh(nctx) _prop_closures.set(new_prop.id, new_prop) return new_prop.id def user_prop_fixed(ctx, cb, id, value): prop = _prop_closures.get(ctx) prop.cb = cb id = _to_expr_ref(to_Ast(id), prop.ctx()) value = _to_expr_ref(to_Ast(value), prop.ctx()) prop.fixed(id, value) prop.cb = None def user_prop_created(ctx, cb, id): prop = _prop_closures.get(ctx) prop.cb = cb id = _to_expr_ref(to_Ast(id), prop.ctx()) prop.created(id) prop.cb = None def user_prop_final(ctx, cb): prop = _prop_closures.get(ctx) prop.cb = cb prop.final() prop.cb = None def user_prop_eq(ctx, cb, x, y): prop = _prop_closures.get(ctx) prop.cb = cb x = _to_expr_ref(to_Ast(x), prop.ctx()) y = _to_expr_ref(to_Ast(y), prop.ctx()) prop.eq(x, y) prop.cb = None def user_prop_diseq(ctx, cb, x, y): prop = _prop_closures.get(ctx) prop.cb = cb x = _to_expr_ref(to_Ast(x), prop.ctx()) y = _to_expr_ref(to_Ast(y), prop.ctx()) prop.diseq(x, y) prop.cb = None def user_prop_decide(ctx, cb, t, idx, phase): prop = _prop_closures.get(ctx) prop.cb = cb t = _to_expr_ref(to_Ast(t_ref), prop.ctx()) prop.decide(t, idx, phase) prop.cb = None _user_prop_push = Z3_push_eh(user_prop_push) _user_prop_pop = Z3_pop_eh(user_prop_pop) _user_prop_fresh = Z3_fresh_eh(user_prop_fresh) _user_prop_fixed = Z3_fixed_eh(user_prop_fixed) _user_prop_created = Z3_created_eh(user_prop_created) _user_prop_final = Z3_final_eh(user_prop_final) _user_prop_eq = Z3_eq_eh(user_prop_eq) _user_prop_diseq = Z3_eq_eh(user_prop_diseq) _user_prop_decide = Z3_decide_eh(user_prop_decide) def PropagateFunction(name, *sig): """Create a function that gets tracked by user propagator. Every term headed by this function symbol is tracked. If a term is fixed and the fixed callback is registered a callback is invoked that the term headed by this function is fixed. """ 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_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx) class UserPropagateBase: # # Either solver is set or ctx is set. # Propagators that are created throuh callbacks # to "fresh" inherit the context of that is supplied # as argument to the callback. # This context should not be deleted. It is owned by the solver. # def __init__(self, s, ctx=None): assert s is None or ctx is None ensure_prop_closures() self.solver = s self._ctx = None self.fresh_ctx = None self.cb = None self.id = _prop_closures.insert(self) self.fixed = None self.final = None self.eq = None self.diseq = None self.created = None if ctx: self.fresh_ctx = ctx if s: Z3_solver_propagate_init(self.ctx_ref(), s.solver, ctypes.c_void_p(self.id), _user_prop_push, _user_prop_pop, _user_prop_fresh) def __del__(self): if self._ctx: self._ctx.ctx = None def ctx(self): if self.fresh_ctx: return self.fresh_ctx else: return self.solver.ctx def ctx_ref(self): return self.ctx().ref() def add_fixed(self, fixed): assert not self.fixed assert not self._ctx if self.solver: Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed) self.fixed = fixed def add_created(self, created): assert not self.created assert not self._ctx if self.solver: Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created) self.created = created def add_final(self, final): assert not self.final assert not self._ctx if self.solver: Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final) self.final = final def add_eq(self, eq): assert not self.eq assert not self._ctx if self.solver: Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq) self.eq = eq def add_diseq(self, diseq): assert not self.diseq assert not self._ctx if self.solver: Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq) self.diseq = diseq def add_decide(self, decide): assert not self.decide assert not self._ctx if self.solver: Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide) self.decide = decide def push(self): raise Z3Exception("push needs to be overwritten") def pop(self, num_scopes): raise Z3Exception("pop needs to be overwritten") def fresh(self, new_ctx): raise Z3Exception("fresh needs to be overwritten") def add(self, e): assert not self._ctx if self.solver: Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast) else: Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast) # # Tell the solver to perform the next split on a given term # If the term is a bit-vector the index idx specifies the index of the Boolean variable being # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument. # def next_split(self, t, idx, phase): return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase) # # Propagation can only be invoked as during a fixed or final callback. # def propagate(self, e, ids, eqs=[]): _ids, num_fixed = _to_ast_array(ids) num_eqs = len(eqs) _lhs, _num_lhs = _to_ast_array([x for x, y in eqs]) _rhs, _num_rhs = _to_ast_array([y for x, y in eqs]) return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p( self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast) def conflict(self, deps = [], eqs = []): self.propagate(BoolVal(False, self.ctx()), deps, eqs)
337,613
27.772286
151
py
z3
z3-master/src/api/python/z3/z3printer.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface # # Author: Leonardo de Moura (leonardo) ############################################ import sys import io # We want to import submodule z3 here, but there's no way # to do that that works correctly on both Python 2 and 3. if sys.version_info.major < 3: # In Python 2: an implicit-relative import of submodule z3. # In Python 3: an undesirable import of global package z3. import z3 else: # In Python 2: an illegal circular import. # In Python 3: an explicit-relative import of submodule z3. from . import 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 ] _ASSOC_OPS = frozenset({ Z3_OP_BOR, Z3_OP_BXOR, Z3_OP_BAND, Z3_OP_ADD, Z3_OP_BADD, Z3_OP_MUL, Z3_OP_BMUL, }) def _is_assoc(k): return k in _ASSOC_OPS 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 if sys.version_info.major < 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 is 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 is 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 is not 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()), )) elif isinstance(s, z3.CharSortRef): return to_format("Char") 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) elif k == Z3_OP_CHAR_CONST: return self.pp_char(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): high = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 0) low = 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(high), to_format(low), arg]) def pp_loop(self, a, d, xs): low = 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: high = Z3_get_decl_int_parameter(a.ctx_ref(), a.decl().ast, 1) return seq1("Loop", [arg, to_format(low), to_format(high)]) return seq1("Loop", [arg, to_format(low)]) def pp_set(self, id, a): return seq1(id, [self.pp_sort(a.sort())]) def pp_char(self, a): n = a.params()[0] return to_format(str(n)) 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 is 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 is not None: _z3_assert(isinstance(v, type(val)), "Invalid pretty print option value") setattr(_PP, k, v) return True val = getattr(_Formatter, k, None) if val is not None: _z3_assert(isinstance(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()
45,224
28.871202
116
py
z3
z3-master/src/api/python/z3/z3num.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Z3 Python interface for Z3 numerals # # Author: Leonardo de Moura (leonardo) ############################################ 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.major >= 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]
16,090
26.743103
110
py
z3
z3-master/src/api/python/z3/__init__.py
from .z3 import * from . import z3num from . import z3poly from . import z3printer from . import z3rcf from . import z3types from . import z3util # generated files from . import z3core from . import z3consts
210
15.230769
23
py
z3
z3-master/scripts/mk_gparams_register_modules_cpp.py
# -- /usr/bin/env python """ Determines the available global parameters from a list of header files and generates a ``gparams_register_modules.cpp`` file in the destination directory that defines a function ``void gparams_register_modules()``. """ import mk_genfile_common import argparse import logging import os import sys def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("destination_dir", help="destination directory") parser.add_argument("header_files", nargs="+", help="One or more header files to parse") pargs = parser.parse_args(args) if not mk_genfile_common.check_dir_exists(pargs.destination_dir): return 1 if not mk_genfile_common.check_files_exist(pargs.header_files): return 1 h_files_full_path = [] for header_file in pargs.header_files: h_files_full_path.append(os.path.abspath(header_file)) output = mk_genfile_common.mk_gparams_register_modules_internal( h_files_full_path, pargs.destination_dir ) logging.info('Generated "{}"'.format(output)) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
1,236
29.170732
78
py
z3
z3-master/scripts/mk_copyright.py
# Copyright (c) 2015 Microsoft Corporation import os import re cr = re.compile("Copyright") aut = re.compile("Automatically generated") cr_notice = """ /*++ Copyright (c) 2015 Microsoft Corporation --*/ """ def has_cr(file): ins = open(file) lines = 0 line = ins.readline() while line and lines < 20: m = cr.search(line) if m: ins.close() return True m = aut.search(line) if m: ins.close() return True line = ins.readline() ins.close() return False def add_cr(file): tmp = "%s.tmp" % file ins = open(file) ous = open(tmp,'w') ous.write(cr_notice) line = ins.readline() while line: ous.write(line) line = ins.readline() ins.close() ous.close() os.system("move %s %s" % (tmp, file)) def add_missing_cr(dir): for root, dirs, files in os.walk(dir): for f in files: if f.endswith('.cpp') or f.endswith('.h') or f.endswith('.c') or f.endswith('.cs'): path = "%s\\%s" % (root, f) if not has_cr(path): print("Missing CR for %s" % path) add_cr(path) add_missing_cr('src') add_missing_cr('examples')
1,259
20.724138
95
py
z3
z3-master/scripts/pyg2hpp.py
# - /usr/bin/env python """ Reads a pyg file and emits the corresponding C++ header file into the specified destination directory. """ import mk_genfile_common import argparse import logging import os import sys def main(args): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("pyg_file", help="pyg file") parser.add_argument("destination_dir", help="destination directory") pargs = parser.parse_args(args) if not os.path.exists(pargs.pyg_file): logging.error('"{}" does not exist'.format(pargs.pyg_file)) return 1 if not mk_genfile_common.check_dir_exists(pargs.destination_dir): return 1 pyg_full_path = os.path.abspath(pargs.pyg_file) destination_dir_full_path = os.path.abspath(pargs.destination_dir) logging.info('Using {}'.format(pyg_full_path)) output = mk_genfile_common.mk_hpp_from_pyg(pyg_full_path, destination_dir_full_path) logging.info('Generated "{}"'.format(output)) return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
1,100
28.756757
88
py
z3
z3-master/scripts/mk_genfile_common.py
# This file contains code that is common to # both the Python build system and the CMake # build system. # # The code here generally is involved in # generating files needed by Z3 at build time. # # You should **not** import ``mk_util`` here # to avoid having this code depend on the # of the Python build system. import io import os import pprint import logging import re import sys # Logger for this module _logger = logging.getLogger(__name__) ############################################################################### # Utility functions ############################################################################### def check_dir_exists(output_dir): """ Returns ``True`` if ``output_dir`` exists, otherwise returns ``False``. """ if not os.path.isdir(output_dir): _logger.error('"{}" is not an existing directory'.format(output_dir)) return False return True def check_files_exist(files): assert isinstance(files, list) for f in files: if not os.path.exists(f): _logger.error('"{}" does not exist'.format(f)) return False return True def sorted_headers_by_component(l): """ Take a list of header files and sort them by the path after ``src/``. E.g. for ``src/ast/fpa/fpa2bv_converter.h`` the sorting key is ``ast/fpa/fpa2bv_converter.h``. The sort is done this way because for the CMake build there are two directories for every component (e.g. ``<src_dir>/src/ast/fpa`` and ``<build_dir>/src/ast/fpa``). We don't want to sort based on different ``<src_dir>`` and ``<build_dir>`` prefixes so that we can match the Python build system's behaviour. """ assert isinstance(l, list) def get_key(path): _logger.debug("get_key({})".format(path)) path_components = [] stripped_path = path assert 'src' in stripped_path.split(os.path.sep) or 'src' in stripped_path.split('/') # Keep stripping off directory components until we hit ``src`` while os.path.basename(stripped_path) != 'src': path_components.append(os.path.basename(stripped_path)) stripped_path = os.path.dirname(stripped_path) assert len(path_components) > 0 path_components.reverse() # For consistency across platforms use ``/`` rather than ``os.sep``. # This is a sorting key so it doesn't need to a platform suitable # path r = '/'.join(path_components) _logger.debug("return key:'{}'".format(r)) return r sorted_headers = sorted(l, key=get_key) _logger.debug('sorted headers:{}'.format(pprint.pformat(sorted_headers))) return sorted_headers ############################################################################### # Functions for generating constant declarations for language bindings ############################################################################### def mk_z3consts_py_internal(api_files, output_dir): """ Generate ``z3consts.py`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") z3consts = open(os.path.join(output_dir, 'z3', 'z3consts.py'), 'w') z3consts_output_path = z3consts.name z3consts.write('# Automatically generated file\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] z3consts.write('# enum %s\n' % name) # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write('%s = %s\n' % (k, v)) z3consts.write('\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.close() return z3consts_output_path def mk_z3consts_dotnet_internal(api_files, output_dir): """ Generate ``Enumerations.cs`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] z3consts = open(os.path.join(output_dir, 'Enumerations.cs'), 'w') z3consts_output_path = z3consts.name z3consts.write('// Automatically generated file\n\n') z3consts.write('using System;\n\n' '#pragma warning disable 1591\n\n' 'namespace Microsoft.Z3\n' '{\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: z3consts.write(' /// <summary>%s</summary>\n' % name) z3consts.write(' public enum %s {\n' % name) z3consts.write # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write(' %s = %s,\n' % (k, v)) z3consts.write(' }\n\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.write('}\n'); z3consts.close() return z3consts_output_path def mk_z3consts_java_internal(api_files, package_name, output_dir): """ Generate "com.microsoft.z3.enumerations" package from the list of API header files in ``api_files`` and write the package directory into the ``output_dir`` directory Returns a list of the generated java source files. """ blank_pat = re.compile("^ *$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] gendir = os.path.join(output_dir, "enumerations") if not os.path.exists(gendir): os.mkdir(gendir) generated_enumeration_files = [] for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: efile = open('%s.java' % os.path.join(gendir, name), 'w') generated_enumeration_files.append(efile.name) efile.write('/**\n * Automatically generated file\n **/\n\n') efile.write('package %s.enumerations;\n\n' % package_name) efile.write('import java.util.HashMap;\n') efile.write('import java.util.Map;\n') efile.write('\n') efile.write('/**\n') efile.write(' * %s\n' % name) efile.write(' **/\n') efile.write('public enum %s {\n' % name) efile.write first = True # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): if first: first = False else: efile.write(',\n') efile.write(' %s (%s)' % (k, v)) efile.write(";\n") efile.write('\n private final int intValue;\n\n') efile.write(' %s(int v) {\n' % name) efile.write(' this.intValue = v;\n') efile.write(' }\n\n') efile.write(' // Cannot initialize map in constructor, so need to do it lazily.\n') efile.write(' // Easiest thread-safe way is the initialization-on-demand holder pattern.\n') efile.write(' private static class %s_MappingHolder {\n' % name) efile.write(' private static final Map<Integer, %s> intMapping = new HashMap<>();\n' % name) efile.write(' static {\n') efile.write(' for (%s k : %s.values())\n' % (name, name)) efile.write(' intMapping.put(k.toInt(), k);\n') efile.write(' }\n') efile.write(' }\n\n') efile.write(' public static final %s fromInt(int v) {\n' % name) efile.write(' %s k = %s_MappingHolder.intMapping.get(v);\n' % (name, name)) efile.write(' if (k != null) return k;\n') efile.write(' throw new IllegalArgumentException("Illegal value " + v + " for %s");\n' % name) efile.write(' }\n\n') efile.write(' public final int toInt() { return this.intValue; }\n') # efile.write(';\n %s(int v) {}\n' % name) efile.write('}\n\n') efile.close() mode = SEARCHING else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() return generated_enumeration_files # Extract enumeration types from z3_api.h, and add ML definitions def mk_z3consts_ml_internal(api_files, output_dir): """ Generate ``z3enums.ml`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") DeprecatedEnums = [ 'Z3_search_failure' ] if not os.path.exists(output_dir): os.mkdir(output_dir) efile = open('%s.ml' % os.path.join(output_dir, "z3enums"), 'w') z3consts_output_path = efile.name efile.write('(* Automatically generated file *)\n\n') efile.write('(** The enumeration types of Z3. *)\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] if name not in DeprecatedEnums: sorted_decls = sorted(decls.items(), key=lambda pair: pair[1]) efile.write('(** %s *)\n' % name[3:]) efile.write('type %s =\n' % name[3:]) # strip Z3_ for k, i in sorted_decls: efile.write(' | %s \n' % k[3:]) # strip Z3_ efile.write('\n') efile.write('(** Convert %s to int*)\n' % name[3:]) efile.write('let int_of_%s x : int =\n' % (name[3:])) # strip Z3_ efile.write(' match x with\n') for k, i in sorted_decls: efile.write(' | %s -> %d\n' % (k[3:], i)) efile.write('\n') efile.write('(** Convert int to %s*)\n' % name[3:]) efile.write('let %s_of_int x : %s =\n' % (name[3:],name[3:])) # strip Z3_ efile.write(' match x with\n') for k, i in sorted_decls: efile.write(' | %d -> %s\n' % (i, k[3:])) # use Z3.Exception? efile.write(' | _ -> raise (Failure "undefined enum value")\n\n') mode = SEARCHING else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() efile.close() return z3consts_output_path # efile = open('%s.mli' % os.path.join(gendir, "z3enums"), 'w') # efile.write('(* Automatically generated file *)\n\n') # efile.write('(** The enumeration types of Z3. *)\n\n') # for api_file in api_files: # api_file_c = ml.find_file(api_file, ml.name) # api_file = os.path.join(api_file_c.src_dir, api_file) # api = open(api_file, 'r') # SEARCHING = 0 # FOUND_ENUM = 1 # IN_ENUM = 2 # mode = SEARCHING # decls = {} # idx = 0 # linenum = 1 # for line in api: # m1 = blank_pat.match(line) # m2 = comment_pat.match(line) # if m1 or m2: # # skip blank lines and comments # linenum = linenum + 1 # elif mode == SEARCHING: # m = typedef_pat.match(line) # if m: # mode = FOUND_ENUM # m = typedef2_pat.match(line) # if m: # mode = IN_ENUM # decls = {} # idx = 0 # elif mode == FOUND_ENUM: # m = openbrace_pat.match(line) # if m: # mode = IN_ENUM # decls = {} # idx = 0 # else: # assert False, "Invalid %s, line: %s" % (api_file, linenum) # else: # assert mode == IN_ENUM # words = re.split('[^\-a-zA-Z0-9_]+', line) # m = closebrace_pat.match(line) # if m: # name = words[1] # if name not in DeprecatedEnums: # efile.write('(** %s *)\n' % name[3:]) # efile.write('type %s =\n' % name[3:]) # strip Z3_ # for k, i in sorted(decls.items(), key=lambda pair: pair[1]): # efile.write(' | %s \n' % k[3:]) # strip Z3_ # efile.write('\n') # efile.write('(** Convert %s to int*)\n' % name[3:]) # efile.write('val int_of_%s : %s -> int\n' % (name[3:], name[3:])) # strip Z3_ # efile.write('(** Convert int to %s*)\n' % name[3:]) # efile.write('val %s_of_int : int -> %s\n' % (name[3:],name[3:])) # strip Z3_ # efile.write('\n') # mode = SEARCHING # else: # if words[2] != '': # if len(words[2]) > 1 and words[2][1] == 'x': # idx = int(words[2], 16) # else: # idx = int(words[2]) # decls[words[1]] = idx # idx = idx + 1 # linenum = linenum + 1 # api.close() # efile.close() # if VERBOSE: # print ('Generated "%s/z3enums.mli"' % ('%s' % gendir)) ############################################################################### # Functions for generating a "module definition file" for MSVC ############################################################################### def mk_def_file_internal(defname, dll_name, export_header_files): """ Writes to a module definition file to a file named ``defname``. ``dll_name`` is the name of the dll (without the ``.dll`` suffix). ``export_header_file`` is a list of header files to scan for symbols to include in the module definition file. """ assert isinstance(export_header_files, list) pat1 = re.compile(".*Z3_API.*") fout = open(defname, 'w') fout.write('LIBRARY "%s"\nEXPORTS\n' % dll_name) num = 1 for export_header_file in export_header_files: api = open(export_header_file, 'r') for line in api: m = pat1.match(line) if m: words = re.split(r'\W+', line) i = 0 for w in words: if w == 'Z3_API': f = words[i+1] fout.write('\t%s @%s\n' % (f, num)) i = i + 1 num = num + 1 api.close() fout.close() ############################################################################### # Functions for generating ``gparams_register_modules.cpp`` ############################################################################### def path_after_src(h_file): h_file = h_file.replace("\\","/") idx = h_file.rfind("src/") if idx == -1: return h_file return h_file[idx + 4:] def mk_gparams_register_modules_internal(h_files_full_path, path): """ Generate a ``gparams_register_modules.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedure ``` void gparams_register_modules() ``` This procedure is invoked by gparams::init() """ assert isinstance(h_files_full_path, list) assert check_dir_exists(path) cmds = [] mod_cmds = [] mod_descrs = [] fullname = os.path.join(path, 'gparams_register_modules.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') fout.write('#include "util/gparams.h"\n') reg_pat = re.compile(r'[ \t]*REG_PARAMS\(\'([^\']*)\'\)') reg_mod_pat = re.compile(r'[ \t]*REG_MODULE_PARAMS\(\'([^\']*)\', *\'([^\']*)\'\)') reg_mod_descr_pat = re.compile(r'[ \t]*REG_MODULE_DESCRIPTION\(\'([^\']*)\', *\'([^\']*)\'\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: m = reg_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) cmds.append((m.group(1))) m = reg_mod_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) mod_cmds.append((m.group(1), m.group(2))) m = reg_mod_descr_pat.match(line) if m: mod_descrs.append((m.group(1), m.group(2))) fout.write('void gparams_register_modules() {\n') for code in cmds: fout.write('{ param_descrs d; %s(d); gparams::register_global(d); }\n' % code) for (mod, code) in mod_cmds: fout.write('{ auto f = []() { auto* d = alloc(param_descrs); %s(*d); return d; }; gparams::register_module("%s", f); }\n' % (code, mod)) for (mod, descr) in mod_descrs: fout.write('gparams::register_module_descr("%s", "%s");\n' % (mod, descr)) fout.write('}\n') fout.close() return fullname ############################################################################### # Functions/data structures for generating ``install_tactics.cpp`` ############################################################################### def mk_install_tactic_cpp_internal(h_files_full_path, path): """ Generate a ``install_tactics.cpp`` file in the directory ``path``. Returns the path the generated file. This file implements the procedure ``` void install_tactics(tactic_manager & ctx) ``` It installs all tactics declared in the given header files ``h_files_full_path`` The procedure looks for ``ADD_TACTIC`` and ``ADD_PROBE``commands in the ``.h`` and ``.hpp`` files of these components. """ ADD_TACTIC_DATA = [] ADD_SIMPLIFIER_DATA = [] ADD_PROBE_DATA = [] def ADD_TACTIC(name, descr, cmd): ADD_TACTIC_DATA.append((name, descr, cmd)) def ADD_PROBE(name, descr, cmd): ADD_PROBE_DATA.append((name, descr, cmd)) def ADD_SIMPLIFIER(name, descr, cmd): ADD_SIMPLIFIER_DATA.append((name, descr, cmd)) eval_globals = { 'ADD_TACTIC': ADD_TACTIC, 'ADD_PROBE': ADD_PROBE, 'ADD_SIMPLIFIER': ADD_SIMPLIFIER } assert isinstance(h_files_full_path, list) assert check_dir_exists(path) fullname = os.path.join(path, 'install_tactic.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') fout.write('#include "tactic/tactic.h"\n') fout.write('#include "cmd_context/tactic_cmds.h"\n') fout.write('#include "cmd_context/simplifier_cmds.h"\n') fout.write('#include "cmd_context/cmd_context.h"\n') tactic_pat = re.compile(r'[ \t]*ADD_TACTIC\(.*\)') probe_pat = re.compile(r'[ \t]*ADD_PROBE\(.*\)') simplifier_pat = re.compile(r'[ \t]*ADD_SIMPLIFIER\(.*\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False try: with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: if tactic_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_TACTIC command at '{}'\n{}".format( fullname, line)) raise e if probe_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_PROBE command at '{}'\n{}".format( fullname, line)) raise e if simplifier_pat.match(line): if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) try: eval(line.strip('\n '), eval_globals, None) except Exception as e: _logger.error("Failed processing ADD_SIMPLIFIER command at '{}'\n{}".format( fullname, line)) raise e except Exception as e: _logger.error("Failed to read file {}\n".format(h_file)) raise e # First pass will just generate the tactic factories fout.write('#define ADD_TACTIC_CMD(NAME, DESCR, CODE) ctx.insert(alloc(tactic_cmd, symbol(NAME), DESCR, [](ast_manager &m, const params_ref &p) { return CODE; }))\n') fout.write('#define ADD_PROBE(NAME, DESCR, PROBE) ctx.insert(alloc(probe_info, symbol(NAME), DESCR, PROBE))\n') fout.write('#define ADD_SIMPLIFIER_CMD(NAME, DESCR, CODE) ctx.insert(alloc(simplifier_cmd, symbol(NAME), DESCR, [](auto& m, auto& p, auto &s) -> dependent_expr_simplifier* { return CODE; }))\n') fout.write('void install_tactics(tactic_manager & ctx) {\n') for data in ADD_TACTIC_DATA: fout.write(' ADD_TACTIC_CMD("%s", "%s", %s);\n' % data) for data in ADD_PROBE_DATA: fout.write(' ADD_PROBE("%s", "%s", %s);\n' % data) for data in ADD_SIMPLIFIER_DATA: fout.write(' ADD_SIMPLIFIER_CMD("%s", "%s", %s);\n' % data) fout.write('}\n') fout.close() return fullname ############################################################################### # Functions for generating ``mem_initializer.cpp`` ############################################################################### def mk_mem_initializer_cpp_internal(h_files_full_path, path): """ Generate a ``mem_initializer.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedures ``` void mem_initialize() void mem_finalize() ``` These procedures are invoked by the Z3 memory_manager """ assert isinstance(h_files_full_path, list) assert check_dir_exists(path) initializer_cmds = [] finalizer_cmds = [] fullname = os.path.join(path, 'mem_initializer.cpp') fout = open(fullname, 'w') fout.write('// Automatically generated file.\n') initializer_pat = re.compile(r'[ \t]*ADD_INITIALIZER\(\'([^\']*)\'\)') # ADD_INITIALIZER with priority initializer_prio_pat = re.compile(r'[ \t]*ADD_INITIALIZER\(\'([^\']*)\',[ \t]*(-?[0-9]*)\)') finalizer_pat = re.compile(r'[ \t]*ADD_FINALIZER\(\'([^\']*)\'\)') for h_file in sorted_headers_by_component(h_files_full_path): added_include = False with io.open(h_file, encoding='utf-8', mode='r') as fin: for line in fin: m = initializer_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) initializer_cmds.append((m.group(1), 0)) m = initializer_prio_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) initializer_cmds.append((m.group(1), int(m.group(2)))) m = finalizer_pat.match(line) if m: if not added_include: added_include = True fout.write('#include "%s"\n' % path_after_src(h_file)) finalizer_cmds.append(m.group(1)) initializer_cmds.sort(key=lambda tup: tup[1]) fout.write('void mem_initialize() {\n') for (cmd, prio) in initializer_cmds: fout.write(cmd) fout.write('\n') fout.write('}\n') fout.write('void mem_finalize() {\n') for cmd in finalizer_cmds: fout.write(cmd) fout.write('\n') fout.write('}\n') fout.close() return fullname ############################################################################### # Functions for generating ``database.h`` ############################################################################### def mk_pat_db_internal(inputFilePath, outputFilePath): """ Generate ``g_pattern_database[]`` declaration header file. """ with open(inputFilePath, 'r') as fin: with open(outputFilePath, 'w') as fout: fout.write('static char const g_pattern_database[] =\n') for line in fin: fout.write('"%s\\n"\n' % line.strip('\n')) fout.write(';\n') ############################################################################### # Functions and data structures for generating ``*_params.hpp`` files from # ``*.pyg`` files ############################################################################### UINT = 0 BOOL = 1 DOUBLE = 2 STRING = 3 SYMBOL = 4 UINT_MAX = 4294967295 TYPE2CPK = { UINT : 'CPK_UINT', BOOL : 'CPK_BOOL', DOUBLE : 'CPK_DOUBLE', STRING : 'CPK_STRING', SYMBOL : 'CPK_SYMBOL' } TYPE2CTYPE = { UINT : 'unsigned', BOOL : 'bool', DOUBLE : 'double', STRING : 'char const *', SYMBOL : 'symbol' } TYPE2GETTER = { UINT : 'get_uint', BOOL : 'get_bool', DOUBLE : 'get_double', STRING : 'get_str', SYMBOL : 'get_sym' } def pyg_default(p): if p[1] == BOOL: if p[2]: return "true" else: return "false" return p[2] def pyg_default_as_c_literal(p): if p[1] == BOOL: if p[2]: return "true" else: return "false" elif p[1] == STRING: return '"%s"' % p[2] elif p[1] == SYMBOL: return 'symbol("%s")' % p[2] elif p[1] == UINT: return '%su' % p[2] else: return p[2] def to_c_method(s): return s.replace('.', '_') def max_memory_param(): return ('max_memory', UINT, UINT_MAX, 'maximum amount of memory in megabytes') def max_steps_param(): return ('max_steps', UINT, UINT_MAX, 'maximum number of steps') def mk_hpp_from_pyg(pyg_file, output_dir): """ Generates the corresponding header file for the input pyg file at the path ``pyg_file``. The file is emitted into the directory ``output_dir``. Returns the path to the generated file """ CURRENT_PYG_HPP_DEST_DIR = output_dir # Note OUTPUT_HPP_FILE cannot be a string as we need a mutable variable # for the nested function to modify OUTPUT_HPP_FILE = [ ] # The function below has been nested so that it can use closure to capture # the above variables that aren't global but instead local to this # function. This avoids use of global state which makes this function safer. def def_module_params(module_name, export, params, class_name=None, description=None): dirname = CURRENT_PYG_HPP_DEST_DIR assert(os.path.exists(dirname)) if class_name is None: class_name = '%s_params' % module_name hpp = os.path.join(dirname, '%s.hpp' % class_name) out = open(hpp, 'w') out.write('// Automatically generated file\n') out.write('#pragma once\n') out.write('#include "util/params.h"\n') if export: out.write('#include "util/gparams.h"\n') out.write('struct %s {\n' % class_name) out.write(' params_ref const & p;\n') if export: out.write(' params_ref g;\n') out.write(' %s(params_ref const & _p = params_ref::get_empty()):\n' % class_name) out.write(' p(_p)') if export: out.write(', g(gparams::get_module("%s"))' % module_name) out.write(' {}\n') out.write(' static void collect_param_descrs(param_descrs & d) {\n') for param in params: out.write(' d.insert("%s", %s, "%s", "%s","%s");\n' % (param[0], TYPE2CPK[param[1]], param[3], pyg_default(param), module_name)) out.write(' }\n') if export: out.write(' /*\n') out.write(" REG_MODULE_PARAMS('%s', '%s::collect_param_descrs')\n" % (module_name, class_name)) if description is not None: out.write(" REG_MODULE_DESCRIPTION('%s', '%s')\n" % (module_name, description)) out.write(' */\n') # Generated accessors for param in params: if export: out.write(' %s %s() const { return p.%s("%s", g, %s); }\n' % (TYPE2CTYPE[param[1]], to_c_method(param[0]), TYPE2GETTER[param[1]], param[0], pyg_default_as_c_literal(param))) else: out.write(' %s %s() const { return p.%s("%s", %s); }\n' % (TYPE2CTYPE[param[1]], to_c_method(param[0]), TYPE2GETTER[param[1]], param[0], pyg_default_as_c_literal(param))) out.write('};\n') out.close() OUTPUT_HPP_FILE.append(hpp) # Globals to use when executing the ``.pyg`` file. pyg_globals = { 'UINT' : UINT, 'BOOL' : BOOL, 'DOUBLE' : DOUBLE, 'STRING' : STRING, 'SYMBOL' : SYMBOL, 'UINT_MAX' : UINT_MAX, 'max_memory_param' : max_memory_param, 'max_steps_param' : max_steps_param, # Note that once this function is entered that function # executes with respect to the globals of this module and # not the globals defined here 'def_module_params' : def_module_params, } with open(pyg_file, 'r') as fh: eval(fh.read() + "\n", pyg_globals, None) assert len(OUTPUT_HPP_FILE) == 1 return OUTPUT_HPP_FILE[0]
39,190
39.654564
198
py
z3
z3-master/scripts/mk_exception.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Author: Leonardo de Moura (leonardo) ############################################ class MKException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
320
23.692308
44
py
z3
z3-master/scripts/mk_win_dist.py
############################################ # Copyright (c) 2012 Microsoft Corporation # # Scripts for automatically generating # Window distribution zip files. # # Author: Leonardo de Moura (leonardo) ############################################ import os import glob import re import getopt import sys import shutil import subprocess import zipfile from mk_exception import * from mk_project import * import mk_util BUILD_DIR='build-dist' BUILD_X64_DIR=os.path.join('build-dist', 'x64') BUILD_X86_DIR=os.path.join('build-dist', 'x86') VERBOSE=True DIST_DIR='dist' FORCE_MK=False ASSEMBLY_VERSION=None DOTNET_CORE_ENABLED=True DOTNET_KEY_FILE=None JAVA_ENABLED=True ZIP_BUILD_OUTPUTS=False GIT_HASH=False PYTHON_ENABLED=True X86ONLY=False X64ONLY=False MAKEJOBS=getenv("MAKEJOBS", "24") def set_verbose(flag): global VERBOSE VERBOSE = flag def is_verbose(): return VERBOSE def mk_dir(d): if not os.path.exists(d): os.makedirs(d) def set_build_dir(path): global BUILD_DIR, BUILD_X86_DIR, BUILD_X64_DIR BUILD_DIR = mk_util.norm_path(path) BUILD_X86_DIR = os.path.join(path, 'x86') BUILD_X64_DIR = os.path.join(path, 'x64') mk_dir(BUILD_X86_DIR) mk_dir(BUILD_X64_DIR) def display_help(): print("mk_win_dist.py: Z3 Windows distribution generator\n") print("This script generates the zip files containing executables, dlls, header files for Windows.") print("It must be executed from the Z3 root directory.") print("\nOptions:") print(" -h, --help display this message.") print(" -s, --silent do not print verbose messages.") print(" -b <sudir>, --build=<subdir> subdirectory where x86 and x64 Z3 versions will be built (default: build-dist).") print(" -f, --force force script to regenerate Makefiles.") print(" --assembly-version assembly version for dll") print(" --nodotnet do not include .NET bindings in the binary distribution files.") print(" --dotnet-key=<file> strongname sign the .NET assembly with the private key in <file>.") print(" --nojava do not include Java bindings in the binary distribution files.") print(" --nopython do not include Python bindings in the binary distribution files.") print(" --zip package build outputs in zip file.") print(" --githash include git hash in the Zip file.") print(" --x86-only x86 dist only.") print(" --x64-only x64 dist only.") exit(0) # Parse configuration option for mk_make script def parse_options(): global FORCE_MK, JAVA_ENABLED, ZIP_BUILD_OUTPUTS, GIT_HASH, DOTNET_CORE_ENABLED, DOTNET_KEY_FILE, ASSEMBLY_VERSION, PYTHON_ENABLED, X86ONLY, X64ONLY path = BUILD_DIR options, remainder = getopt.gnu_getopt(sys.argv[1:], 'b:hsf', ['build=', 'help', 'silent', 'force', 'nojava', 'nodotnet', 'dotnet-key=', 'assembly-version=', 'zip', 'githash', 'nopython', 'x86-only', 'x64-only' ]) for opt, arg in options: if opt in ('-b', '--build'): if arg == 'src': raise MKException('The src directory should not be used to host the Makefile') path = arg elif opt in ('-s', '--silent'): set_verbose(False) elif opt in ('-h', '--help'): display_help() elif opt in ('-f', '--force'): FORCE_MK = True elif opt == '--nodotnet': DOTNET_CORE_ENABLED = False elif opt == '--assembly-version': ASSEMBLY_VERSION = arg elif opt == '--nopython': PYTHON_ENABLED = False elif opt == '--dotnet-key': DOTNET_KEY_FILE = arg elif opt == '--nojava': JAVA_ENABLED = False elif opt == '--zip': ZIP_BUILD_OUTPUTS = True elif opt == '--githash': GIT_HASH = True elif opt == '--x86-only' and not X64ONLY: X86ONLY = True elif opt == '--x64-only' and not X86ONLY: X64ONLY = True else: raise MKException("Invalid command line option '%s'" % opt) set_build_dir(path) # Check whether build directory already exists or not def check_build_dir(path): return os.path.exists(path) and os.path.exists(os.path.join(path, 'Makefile')) # Create a build directory using mk_make.py def mk_build_dir(path, x64): if not check_build_dir(path) or FORCE_MK: parallel = '--parallel=' + MAKEJOBS opts = ["python", os.path.join('scripts', 'mk_make.py'), parallel, "-b", path] if DOTNET_CORE_ENABLED: opts.append('--dotnet') if DOTNET_KEY_FILE is not None: opts.append('--dotnet-key=' + DOTNET_KEY_FILE) if ASSEMBLY_VERSION is not None: opts.append('--assembly-version=' + ASSEMBLY_VERSION) if JAVA_ENABLED: opts.append('--java') if x64: opts.append('-x') if GIT_HASH: opts.append('--githash=%s' % mk_util.git_hash()) opts.append('--git-describe') if PYTHON_ENABLED: opts.append('--python') opts.append('--guardcf') if subprocess.call(opts) != 0: raise MKException("Failed to generate build directory at '%s'" % path) # Create build directories def mk_build_dirs(): mk_build_dir(BUILD_X86_DIR, False) mk_build_dir(BUILD_X64_DIR, True) # Check if on Visual Studio command prompt def check_vc_cmd_prompt(): try: DEVNULL = open(os.devnull, 'wb') subprocess.call(['cl'], stdout=DEVNULL, stderr=DEVNULL) except: raise MKException("You must execute the mk_win_dist.py script on a Visual Studio Command Prompt") def exec_cmds(cmds): cmd_file = 'z3_tmp.cmd' f = open(cmd_file, 'w') for cmd in cmds: f.write(cmd) f.write('\n') f.close() res = 0 try: res = subprocess.call(cmd_file, shell=True) except: res = 1 try: os.erase(cmd_file) except: pass return res # Compile Z3 (if x64 == True, then it builds it in x64 mode). def mk_z3(x64): cmds = [] if x64: cmds.append('call "%VCINSTALLDIR%Auxiliary\\build\\vcvarsall.bat" amd64') cmds.append('cd %s' % BUILD_X64_DIR) else: cmds.append('call "%VCINSTALLDIR%Auxiliary\\build\\vcvarsall.bat" x86') cmds.append('cd %s' % BUILD_X86_DIR) cmds.append('nmake') if exec_cmds(cmds) != 0: raise MKException("Failed to make z3, x64: %s" % x64) def mk_z3s(): mk_z3(False) mk_z3(True) def get_z3_name(x64): major, minor, build, revision = get_version() print("Assembly version:", major, minor, build, revision) if x64: platform = "x64" else: platform = "x86" if GIT_HASH: return 'z3-%s.%s.%s.%s-%s-win' % (major, minor, build, mk_util.git_hash(), platform) else: return 'z3-%s.%s.%s-%s-win' % (major, minor, build, platform) def mk_dist_dir(x64): if x64: platform = "x64" build_path = BUILD_X64_DIR else: platform = "x86" build_path = BUILD_X86_DIR dist_path = os.path.join(DIST_DIR, get_z3_name(x64)) mk_dir(dist_path) mk_win_dist(build_path, dist_path) if is_verbose(): print(f"Generated {platform} distribution folder at '{dist_path}'") def mk_dist_dirs(): mk_dist_dir(False) mk_dist_dir(True) def get_dist_path(x64): return get_z3_name(x64) def mk_zip(x64): dist_path = get_dist_path(x64) old = os.getcwd() try: os.chdir(DIST_DIR) zfname = '%s.zip' % dist_path zipout = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(dist_path): for f in files: zipout.write(os.path.join(root, f)) if is_verbose(): print("Generated '%s'" % zfname) except: pass os.chdir(old) # Create a zip file for each platform def mk_zips(): mk_zip(False) mk_zip(True) VS_RUNTIME_PATS = [re.compile('vcomp.*\.dll'), re.compile('msvcp.*\.dll'), re.compile('msvcr.*\.dll'), re.compile('vcrun.*\.dll')] # Copy Visual Studio Runtime libraries def cp_vs_runtime(x64): if x64: platform = "x64" else: platform = "x86" vcdir = os.environ['VCINSTALLDIR'] path = '%sredist' % vcdir vs_runtime_files = [] print("Walking %s" % path) # Everything changes with every release of VS # Prior versions of VS had DLLs under "redist\x64" # There are now several variants of redistributables # The naming convention defies my understanding so # we use a "check_root" filter to find some hopefully suitable # redistributable. def check_root(root): return platform in root and ("CRT" in root or "MP" in root) and "onecore" not in root and "debug" not in root for root, dirs, files in os.walk(path): for filename in files: if fnmatch(filename, '*.dll') and check_root(root): print("Checking %s %s" % (root, filename)) for pat in VS_RUNTIME_PATS: if pat.match(filename): fname = os.path.join(root, filename) if not os.path.isdir(fname): vs_runtime_files.append(fname) if not vs_runtime_files: raise MKException("Did not find any runtime files to include") bin_dist_path = os.path.join(DIST_DIR, get_dist_path(x64), 'bin') for f in vs_runtime_files: shutil.copy(f, bin_dist_path) if is_verbose(): print("Copied '%s' to '%s'" % (f, bin_dist_path)) def cp_vs_runtimes(): cp_vs_runtime(True) cp_vs_runtime(False) def cp_license(x64): shutil.copy("LICENSE.txt", os.path.join(DIST_DIR, get_dist_path(x64))) def cp_licenses(): cp_license(True) cp_license(False) def init_flags(): global DOTNET_KEY_FILE, JAVA_ENABLED, PYTHON_ENABLED, ASSEMBLY_VERSION mk_util.DOTNET_CORE_ENABLED = True mk_util.DOTNET_KEY_FILE = DOTNET_KEY_FILE mk_util.ASSEMBLY_VERSION = ASSEMBLY_VERSION mk_util.JAVA_ENABLED = JAVA_ENABLED mk_util.PYTHON_ENABLED = PYTHON_ENABLED mk_util.ALWAYS_DYNAMIC_BASE = True # Entry point def main(): if os.name != 'nt': raise MKException("This script is for Windows only") parse_options() check_vc_cmd_prompt() init_flags() if X86ONLY: mk_build_dir(BUILD_X86_DIR, False) mk_z3(False) init_project_def() mk_dist_dir(False) cp_license(False) cp_vs_runtime(False) if ZIP_BUILD_OUTPUTS: mk_zip(False) elif X64ONLY: mk_build_dir(BUILD_X64_DIR, True) mk_z3(True) init_project_def() mk_dist_dir(True) cp_license(True) cp_vs_runtime(True) if ZIP_BUILD_OUTPUTS: mk_zip(True) else: mk_build_dirs() mk_z3s() init_project_def() mk_dist_dirs() cp_licenses() cp_vs_runtimes() if ZIP_BUILD_OUTPUTS: mk_zips() main()
12,186
33.041899
152
py