Questions about using Z3Py online to solve problems in Transport Phenomena - z3

Certain problem in transport Phenomena is solved using the following code:
T_max, T_0, S, R, k, I, k_e, L, R, E, a = Reals('T_max T_0 S R k I k_e L R E a')
k = a*k_e*T_0
I = k_e*E/L
S = (I**2)/k_e
eq = T_0 + S* R**2/(4*k)
print eq
equations = [
T_max == eq,
]
print "Temperature equations:"
print equations
problem = [
R == 2, L == 5000,
T_0 == 20 + 273,
T_max == 30 + 273, k_e == 1,
a == 2.23*10**(-8), E > 0
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
using this code online we obtain
This output gives the correct answer but there are two issues in the code: a) the expresion named "eq" is not fully simplified and then it is necessary to give an arbitrary value for k_e . My question is: How to simplify the expression "eq" in such way that k_e be eliminated from "eq"?
Other example: To determine the radius of a tube
Code:
def inte(n,a,b):
return (b**(n+1))/(n+1)-(a**(n+1))/(n+1)
P_0, P_1, L, R, mu, q, C = Reals('P_0 P_1 L R mu q C')
k = (P_0 - P_1)/(2*mu*L)
equations = [0 == -k*inte(1,0,R) +C,
q == 2*3.1416*(-(k/2)*inte(3,0,R) + C*inte(1,0,R))]
print "Fluid equations:"
print equations
problem = [
L == 50.02/100, mu == (4.03*10**(-5)),
P_0 == 4.829*10**5, P_1==0,
q == 2.997*10**(-3), R >0
]
print "Problem:"
print problem
print "Solution:"
solve(equations + problem)
Output:
Fluid equations:
[-((P_0 - P_1)/(2·mu·L))·(R2/2 - 0) + C = 0, q =
3927/625·
(-(((P_0 - P_1)/(2·mu·L))/2)·(R4/4 - 0) + C·(R2/2 - 0))]
Problem:
[L = 2501/5000, mu = 403/10000000, P_0 = 482900, P_1 = 0, q = 2997/1000000, R > 0]
Solution:
[R = 0.0007512843?,
q = 2997/1000000,
P_1 = 0,
P_0 = 482900,
mu = 403/10000000,
L = 2501/5000,
C = 3380.3149444289?]

Related

Precision and recall missunderstanding

In pycocotools in cocoeval.py sctipt there is COCOeval class and in this class there is accumulate function for calculating Precision and Recall. Does anyone know what is this npig variable? Is this negative-positive or?
Because I saw this formula for recall: Recall = (True Positive)/(True Positive + False Negative)
Can I just use this precision and recall variable inside dictionary self.eval to get precision and recall of my model which I'm testing, and plot a precision-recall curve?
And the variable scores is this F1 score?
Because I'm not very well understand this T,R,K,A,M what is happening with this.
How can I print precision and recall in terminal?
def accumulate(self, p = None):
'''
Accumulate per image evaluation results and store the result in self.eval
:param p: input params for evaluation
:return: None
'''
print('Accumulating evaluation results...')
tic = time.time()
if not self.evalImgs:
print('Please run evaluate() first')
# allows input customized parameters
if p is None:
p = self.params
p.catIds = p.catIds if p.useCats == 1 else [-1]
T = len(p.iouThrs)
R = len(p.recThrs)
K = len(p.catIds) if p.useCats else 1
A = len(p.areaRng)
M = len(p.maxDets)
precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories
recall = -np.ones((T,K,A,M))
scores = -np.ones((T,R,K,A,M))
# create dictionary for future indexing
_pe = self._paramsEval
catIds = _pe.catIds if _pe.useCats else [-1]
setK = set(catIds)
setA = set(map(tuple, _pe.areaRng))
setM = set(_pe.maxDets)
setI = set(_pe.imgIds)
# get inds to evaluate
k_list = [n for n, k in enumerate(p.catIds) if k in setK]
m_list = [m for n, m in enumerate(p.maxDets) if m in setM]
a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA]
i_list = [n for n, i in enumerate(p.imgIds) if i in setI]
I0 = len(_pe.imgIds)
A0 = len(_pe.areaRng)
# retrieve E at each category, area range, and max number of detections
for k, k0 in enumerate(k_list):
Nk = k0*A0*I0
for a, a0 in enumerate(a_list):
Na = a0*I0
for m, maxDet in enumerate(m_list):
E = [self.evalImgs[Nk + Na + i] for i in i_list]
E = [e for e in E if not e is None]
if len(E) == 0:
continue
dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E])
# different sorting method generates slightly different results.
# mergesort is used to be consistent as Matlab implementation.
inds = np.argsort(-dtScores, kind='mergesort')
dtScoresSorted = dtScores[inds]
dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds]
dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds]
gtIg = np.concatenate([e['gtIgnore'] for e in E])
npig = np.count_nonzero(gtIg==0 )
if npig == 0:
continue
tps = np.logical_and( dtm, np.logical_not(dtIg) )
fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) )
tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)
fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)
for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)):
tp = np.array(tp)
fp = np.array(fp)
nd = len(tp)
rc = tp / npig
pr = tp / (fp+tp+np.spacing(1))
q = np.zeros((R,))
ss = np.zeros((R,))
if nd:
recall[t,k,a,m] = rc[-1]
else:
recall[t,k,a,m] = 0
# numpy is slow without cython optimization for accessing elements
# use python array gets significant speed improvement
pr = pr.tolist(); q = q.tolist()
for i in range(nd-1, 0, -1):
if pr[i] > pr[i-1]:
pr[i-1] = pr[i]
inds = np.searchsorted(rc, p.recThrs, side='left')
try:
for ri, pi in enumerate(inds):
q[ri] = pr[pi]
ss[ri] = dtScoresSorted[pi]
except:
pass
precision[t,:,k,a,m] = np.array(q)
scores[t,:,k,a,m] = np.array(ss)
self.eval = {
'params': p,
'counts': [T, R, K, A, M],
'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'precision': precision,
'recall': recall,
'scores': scores,
}
toc = time.time()
print('DONE (t={:0.2f}s).'.format( toc-tic))

I am trying to give the heuristics using random function. Can anyone please correct me

def getNeighbors(v, adjacency_list):
return adjacency_list[v]
import random
def h(n):
H = {
'A': 14,
'B': 12,
'C': 11,
'D': 6,
'E': 4,
'F': 11,
'Z':random.randint(0,22),
Error message shows in this line saying invalid syntax.
h('Z')=='Z',
}
return H[n]
def A_star(start_node, stop_node,adjacency_list):
open_list = set([start_node])
closed_list = set([])
g = {}
g[start_node] = 0
parents = {}
parents[start_node] = start_node
while len(open_list) > 0:
n = None
for v in open_list:
if n == None or g[v] + h(v) < g[n] + h(n):
n = v;
if n == None:
print('Path does not exist!')
return None
if n == stop_node:
reconst_path = []
while parents[n] != n:
reconst_path.append(n)
n = parents[n]
reconst_path.append(start_node)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path))
return reconst_path
for (m, weight) in getNeighbors(n,adjacency_list):
if m not in open_list and m not in closed_list:
open_list.add(m)
parents[m] = n
g[m] = g[n] + weight
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
open_list.remove(n)
closed_list.add(n)
print('Path does not exist!')
return None
adjacency_list = {
'A': [('B', 4), ('C', 3)],
'B': [('E', 12),('F',5)],
'C': [('D', 7),('E',10)],
'D': [('E',2)],
'E': [('Z',5)],
'F': [('Z',16)]
}
A_star('A', 'Z',adjacency_list)
I would like to know if there is anything wrong with my code. Here I am trying to implement the A star algorithm while giving heuristics randomly, Are there any mistakes that I have done. I know there might be a very silly one. If you find anything please correct me.

How to solve nqueen problem with Z3 solver

I write a formula to solve nqueen problem. It finds one of the solution but I want find all solution how I generalize to all solution for this formula:
from z3 import *
import time
def queens(n,all=0):
start = time.time()
sol = Solver()
# q = [Int("q_%s" % (i)) for i in range(n) ] # n=100: ???s
# q = IntVector("q", n) # this is much faster # n=100: 28.1s
q = Array("q", IntSort(), BitVecSort(8)) # n=100: ??s
# Domains
sol.add([And(q[i]>=0, q[i] <= n-1) for i in range(n)])
# Constraints
for i in range(n):
for j in range(i):
sol.add(q[i] != q[j], q[i]+i != q[j]+j, q[i]-i != q[j]-j)
if sol.check() == sat:
mod = sol.model()
ss = [mod.evaluate(q[i]) for i in range(n)]
print(ss)
# Show all solutions
if all==1:
num_solutions = 0
while sol.check() == sat:
m = sol.model()
ss = [mod.evaluate(q[i]) for i in range(n)]
sol.add( Or([q[i] != ss[i] for i in range(n)]) )
print("q=",ss)
num_solutions = num_solutions + 1
print("num_solutions:", num_solutions)
else:
print("failed to solve")
end = time.time()
value = end - start
print("Time: ", value)
for n in [8,10,12,20,50,100,200]:
print("Testing ", n)
queens(n,0)
For N=4 I try to show 2 solution
For N=8 I try to show all 92 solution
You got most of it correct, though there are issues with how you coded the find-all-solutions part. There's a solution for N-queens that comes with the z3 tutorial here: https://ericpony.github.io/z3py-tutorial/guide-examples.htm
You can turn it into an "find-all-solutions" versions like this:
from z3 import *
def queens(n):
Q = [Int('Q_%i' % (i + 1)) for i in range(n)]
val_c = [And(1 <= Q[i], Q[i] <= n) for i in range(n)]
col_c = [Distinct(Q)]
diag_c = [If(i == j, True, And(Q[i] - Q[j] != i - j, Q[i] - Q[j] != j - i)) for i in range(n) for j in range(i)]
sol = Solver()
sol.add(val_c + col_c + diag_c)
num_solutions = 0
while sol.check() == sat:
mod = sol.model()
ss = [mod.evaluate(Q[i]) for i in range(n)]
print(ss)
num_solutions += 1
sol.add(Or([Q[i] != ss[i] for i in range(n)]))
print("num_solutions:", num_solutions)
queens(4)
queens(8)
This'll print 2 solutions for N=4 and 92 for N=8.

differential evolution global minimum problem

Im trying to get the global minimum of a non linear function with linear constraints. I share you the code:
rho = 1.0
g = 9.8
C = 1.0 #roughness coefficient
J = rho*g/(float(1e6)) #constant of function
capacity = [0.3875, 0.607, 0.374] #Supply data
demand = [0.768, 0.315, 0.38,] #Demand data
m= len(capacity)
n = len(demand)
x0 = np.array(m*n*[0.01]) #Initial point for algorithm
# In[59]:
#READ L AND d FROM ARCGIS !!!
L = (314376.57, 277097.9663, 253756.9869 ,265786.5632, 316712.6028, 232857.1468, 112063.9914, 135762.94, 131152.8206)
h= (75, 75, 75, 75, 75, 75, 1320,75,75)
K = np.zeros(m*n)
N=np.zeros(m*n)
# In[60]:
#Each path has its own L,d, therefore, own constant
# In[61]:
#np.seterr(all='ignore')
def diameter(x):
d = 1.484
if x >= 0.276:
d = 1.484
elif x >= 0.212:
d = 1.299
elif x >= 0.148:
d = 1.086
elif x >= 0.0975:
d = 0.881
elif x >= 0.079:
d = 0.793
elif x >= 0.062:
d = 0.705
elif x >= 0.049:
d = 0.626
elif x >= 0.038:
d = 0.555
elif x >= 0.030:
d = 0.494
elif x >= 0.024:
d = 0.441
elif x >= 0.0198:
d = 0.397
elif x >= 0.01565:
d = 0.353
elif x >= 0.0123:
d = 0.313
elif x >= 0.0097:
d = 0.278
elif x >= 0.0077:
d = 0.247
elif x >= 0.0061:
d = 0.22
elif x >= 0.0049:
d = 0.198
elif x >= 0.00389:
d = 0.176
elif x >= 0.0032:
d = 0.159
elif x >= 0.0025:
d = 0.141
elif x >= 0:
d = 0.123
return d
#Definition of Objetive function
def objective(x):
sum_obj = 0.0
for i in range(len(L)):
K = 10.674*L[i]/(C**1.852*diameter(x[i])**4.871)
N[i] = K*x[i]**2.852*J+x[i]*J*h[i]
sum_obj = sum_obj + N[i]
return sum_obj
print(str(objective(x0)))
#Definition of the constraints
GB=[]
for i in range(m):
GB.append(n*i*[0]+n*[1]+(m-1-i)*n*[0])
P=[]
for i in range(n):
P.append(m*(i*[0]+[1]+(n-1-i)*[0]))
DU=np.array(GB+P)
lb = np.array(m*[0] + demand) # Supply
ub = np.array(capacity + n*[np.inf]) # Demand
# In[62]:
b = (0, 1)
bnds = []
for i in range(m*n):
bnds.append(b)
cons = LinearConstraint(DU,lb,ub)
solution = differential_evolution(objective,x0,cons,bnds)
x = solution.x
# show initial objective
print('Initial SSE Objective: ' + str(objective(x0)))
# show final objective
print('Final SSE Objective: ' + str(objective(x)))
# print solution
print('Solution Supply to Demand:')
print('Q = ' + str(((np.around(x,6)).reshape(10,18))))
I dont know why, but when I run appear the following:
"if strategy in self._binomial:
TypeError: unhashable type: 'list'
Anyone have gotten the same mistake ? Its my first time trying to solve optimization problem, so I need a little bit of help. Any advice is welcome !!
Thanks a lot !
You're not calling differential_evolution correctly. For your example you should call it as:
differential_evolution(objective, bnds, contraints=(cons,))
(I'm not sure if there are additional problems)

How to compute with Quaternion numbers in Z3?

In Complex numbers in Z3 Leonardo de Moura was able to introduce and to compute with complex numbers in Z3.
Using the code proposed by Leonardo I am introducing and computing with quaternion numbers in Z3 according with the code presented here . Using this "quaternion " code I am solving the following problem:
x = Quaternion("x")
s = Tactic('qfnra-nlsat').solver()
s.add(x*x + 30 == 0, x.i3 > 0, x.i2 >0, x.i1 > 0)
print(s.check())
m = s.model()
print m
and the corresponding output is:
sat
[x.r = 0, x.i1 = 1, x.i2 = 1, x.i3 = 5.2915026221?]
This result was verified using Maple.
Other example:
x = Quaternion("x")
y = Quaternion("y")
z = Quaternion("z")
s = Tactic('qfnra-nlsat').solver()
s.add(x*y + 30 + x + y*z == 0, x - y + z == 10)
print(s.check())
m = s.model()
print m
and the output is:
sat
[y.r = 1/8,
z.r = 2601/64,
y.i1 = 1/2,
z.i1 = 45/8,
y.i2 = -1/2,
z.i2 = -45/8,
y.i3 = -1/2,
z.i3 = -45/8,
x.i3 = 41/8,
x.i2 = 41/8,
x.i1 = -41/8,
x.r = -1953/64]
Other example:
Proving that
x * y != y * x
Code:
x = Quaternion("x")
y = Quaternion("y")
a1, b1, c1, d1 = Reals('a1 b1 c1 d1')
a2, b2, c2, d2 = Reals('a2 b2 c2 d2')
x.r = a1
x.i1 = b1
x.i2 = c1
x.i3 = d1
y.r = a2
y.i1 = b2
y.i2 = c2
y.i3 = d2
print simplify((x * y - y * x).r)
print simplify((x * y - y * x).i1)
print simplify((x * y - y * x).i2)
print simplify((x * y - y * x).i3)
Output:
0
2·c2·d1 + -2·c1·d2
-2·b2·d1 + 2·b1·d2
2·b2·c1 + -2·b1·c2
Other example : Proving that the quaternions
A = (1+ I)/sqrt(2),
B =(1 + J)/sqrt(2),
C = (1 + K)/sqrt(2)
generate a representation of the Braid Group, it is to say, we have that
ABA = BAB, ACA = CAC, BCB = CBC.
Code:
A = Quaternion('A')
B = Quaternion('B')
C = Quaternion('C')
A.r = 1/Sqrt(2)
A.i1 = 1/Sqrt(2)
A.i2 = 0
A.i3 = 0
B.r = 1/Sqrt(2)
B.i1 = 0
B.i2 = 1/Sqrt(2)
B.i3 = 0
C.r = 1/Sqrt(2)
C.i1 = 0
C.i2 = 0
C.i3 = 1/Sqrt(2)
print simplify((A*B*A-B*A*B).r)
print simplify((A*B*A-B*A*B).i1)
print simplify((A*B*A-B*A*B).i2)
print simplify((A*B*A-B*A*B).i3)
print "Proved : ABA = BAB:"
print simplify((A*C*A-C*A*C).r)
print simplify((A*C*A-C*A*C).i1)
print simplify((A*C*A-C*A*C).i2)
print simplify((A*C*A-C*A*C).i3)
print "Proved : ACA = CAC:"
print simplify((B*C*B-C*B*C).r)
print simplify((B*C*B-C*B*C).i1)
print simplify((B*C*B-C*B*C).i2)
print simplify((B*C*B-C*B*C).i3)
print "Proved : BCB = CBC:"
Output:
0
0
0
0
Proved : ABA = BAB.
0
0
0
0
Proved : ACA = CAC.
0
0
0
0
Proved : BCB = CBC.
Other example: Proving that
x / x = 1
for all invertible quaternion:
Code:
x = Quaternion("x")
a, a1, a2, a3 = Reals('a a1 a2 a3')
x.r = a
x.i1 = a1
x.i2 = a2
x.i3 = a3
s = Solver()
s.add(Or(a != 0, a1 != 0, a2 != 0, a3 != 0), Not((x/x).r == 1))
print s.check()
s1 = Solver()
s1.add(Or(a != 0, a1 != 0, a2 != 0, a3 != 0), Not((x/x).i1 == 0))
print s1.check()
s2 = Solver()
s2.add(Or(a != 0, a1 != 0, a2 != 0, a3 != 0), Not((x/x).i2 == 0))
print s2.check()
s3 = Solver()
s3.add(Or(a != 0, a1 != 0, a2 != 0, a3 != 0), Not((x/x).i3 == 0))
print s3.check()
Output:
unsat
unsat
unsat
unsat
Please let me know what do you think about the "quaternion" code and how the "quaternion" code can be improved. Many thanks.

Resources