Prolog - Summing numbers - numbers

I am new in prolog. I have found breadth first search program in the internet which is search for routes between cities. I want to extend the program to store and calculate distances. But I can't figure out how to do it.
The original code:
move(loc(omaha), loc(chicago)).
move(loc(omaha), loc(denver)).
move(loc(chicago), loc(denver)).
move(loc(chicago), loc(los_angeles)).
move(loc(chicago), loc(omaha)).
move(loc(denver), loc(los_angeles)).
move(loc(denver), loc(omaha)).
move(loc(los_angeles), loc(chicago)).
move(loc(los_angeles), loc(denver)).
bfs(State, Goal, Path) :-
bfs_help([[State]], Goal, RevPath), reverse(RevPath, Path).
bfs_help([[Goal|Path]|_], Goal, [Goal|Path]).
bfs_help([Path|RestPaths], Goal, SolnPath) :-
extend(Path, NewPaths),
append(RestPaths, NewPaths, TotalPaths),
bfs_help(TotalPaths, Goal, SolnPath).
extend([State|Path], NewPaths) :-
bagof([NextState,State|Path],
(move(State, NextState), not(member(NextState, [State|Path]))),
NewPaths), !.
extend(_, []).
Output:
1 ?- bfs(loc(omaha), loc(chicago), X).
X = [loc(omaha), loc(chicago)] ;
X = [loc(omaha), loc(denver), loc(los_angeles), loc(chicago)] ;
false.
I have tried this:
bfs(A,B,Path,D) :-
bfs(A,B,Path),
path_distance(Path,D).
path_distance([_], 0).
path_distance([A,B|Cs], S1) :-
move(A,B,D),
path_distance(Cs,S2),
S1 is S2+D.
bfs(A,B, Path) :-
bfs_help([[A]], B, RevPath), reverse(RevPath, Path).
bfs_help([[Goal|Path]|_], Goal, [Goal|Path]).
bfs_help([Path|RestPaths], Goal, SolnPath) :-
extend(Path, NewPaths),
append(RestPaths, NewPaths, TotalPaths),
bfs_help(TotalPaths, Goal, SolnPath).
extend([State|Path], NewPaths) :-
bagof([NextState,State|Path],
(move(State, NextState,_), not(member(NextState, [State|Path]))),
NewPaths), !.
extend(_, []).
Output:
5 ?- bfs(loc(omaha), loc(chicago), X,D).
false.
What i want:
1 ?- bfs(loc(omaha), loc(chicago), X, D).
X = [loc(omaha), loc(chicago)] ;
D = 1
X = [loc(omaha), loc(denver), loc(los_angeles), loc(chicago)] ;
D = 6
false.
Please anyone help me to solve this problem!
Sorry for my english.

It seems cheapest to define a relation path_distance/2. That is not the most elegant way,
but it should serve your purpose:
bfs(A,B,Path,D) :-
bfs(A,B,Path),
path_distance(Path,D).
path_distance([_], 0).
path_distance([A,B|Cs], S1) :-
move(A,B,D),
path_distance([B|Cs],S2),
S1 is S2+D.
You might also reconsider bfs/3 a bit. The query
?- bfs(A,B, Path).
Gives rather odd results.
Both move/2 and move/3 are now used. Thus:
move(A,B) :-
move(A,B,_).
move(loc(omaha), loc(chicago),1).
move(loc(omaha), loc(denver),2).
move(loc(chicago), loc(denver),1).
move(loc(chicago), loc(los_angeles),2).
move(loc(chicago), loc(omaha),1).
move(loc(denver), loc(los_angeles),2).
move(loc(denver), loc(omaha),1).
move(loc(los_angeles), loc(chicago),2).
move(loc(los_angeles), loc(denver),3).

Related

Lsode throwing INTDY-- T (=R1) ILLEGAL and invalid input detected

I have my function:
function [result] = my_func(x,y)
result = y^2*(1-3*x)-3*y;
endfunction
Also, my vector with Ts, my function address and my initial variable x_0
load file_with_ts
# Add my limits as I also want to calculate those
# (all values in file_with_ts are within those limits.)
t_points = [-1, file_with_ts, 2]
myfunc = str2func("my_func")
x_0 = 0.9142
I am trying to execute the following line:
lsode_d1 = lsode(myfunc, x_0, t_points)
And expecting a result, but getting the following error:
INTDY-- T (=R1) ILLEGAL
In above message, R1 = 0.7987082301475D+00
T NOT IN INTERVAL TCUR - HU (= R1) TO TCUR (=R2)
In above, R1 = 0.8091168896311D+00 R2 = 0.8280400838323D+00
LSODE-- TROUBLE FROM INTDY. ITASK = I1, TOUT = R1
In above message, I1 = 1
In above message, R1 = 0.7987082301475D+00
error: lsode: invalid input detected (see printed message)
error: called from
main at line 20 column 10
Also, the variable sizes are:
x_0 -> 1x1
t_points -> 1x153
myfunc -> 1x1
I tried transposing the t_points vector
using #my_func instead of the str2func function
I tried adding multiple variables as the starting point (instead of x_0 I entered [x_0; x_1])
Tried changing my function header from my_func(x, y) to my_func(y, x)
Read the documentation and confirmed that my_func allows x to be a vector and returns a vector (whenever x is a vector).
EDIT: T points is the following 1x153 matrix (with -1 and 2 added to the beggining and the end respectively):
-4.9451e-01
-4.9139e-01
-4.7649e-01
-4.8026e-01
-4.6177e-01
-4.5412e-01
-4.4789e-01
-4.2746e-01
-4.1859e-01
-4.0983e-01
-4.0667e-01
-3.8436e-01
-3.7825e-01
-3.7150e-01
-3.5989e-01
-3.5131e-01
-3.4875e-01
-3.3143e-01
-3.2416e-01
-3.1490e-01
-3.0578e-01
-2.9267e-01
-2.9001e-01
-2.6518e-01
-2.5740e-01
-2.5010e-01
-2.4017e-01
-2.3399e-01
-2.1491e-01
-2.1067e-01
-2.0357e-01
-1.8324e-01
-1.8112e-01
-1.7295e-01
-1.6147e-01
-1.5424e-01
-1.4560e-01
-1.1737e-01
-1.1172e-01
-1.0846e-01
-1.0629e-01
-9.4327e-02
-8.0883e-02
-6.6043e-02
-6.6660e-02
-6.1649e-02
-4.7245e-02
-2.8332e-02
-1.8043e-02
-7.7416e-03
-6.5142e-04
1.0918e-02
1.7619e-02
3.4310e-02
3.3192e-02
5.2275e-02
5.5756e-02
6.8326e-02
8.2764e-02
9.5195e-02
9.4412e-02
1.1630e-01
1.2330e-01
1.2966e-01
1.3902e-01
1.4891e-01
1.5848e-01
1.7012e-01
1.8026e-01
1.9413e-01
2.0763e-01
2.1233e-01
2.1895e-01
2.3313e-01
2.4092e-01
2.4485e-01
2.6475e-01
2.7154e-01
2.8068e-01
2.9258e-01
3.0131e-01
3.0529e-01
3.1919e-01
3.2927e-01
3.3734e-01
3.5841e-01
3.5562e-01
3.6758e-01
3.7644e-01
3.8413e-01
3.9904e-01
4.0863e-01
4.2765e-01
4.2875e-01
4.3468e-01
4.5802e-01
4.6617e-01
4.6885e-01
4.7247e-01
4.8778e-01
4.9922e-01
5.1138e-01
5.1869e-01
5.3222e-01
5.4196e-01
5.4375e-01
5.5526e-01
5.6629e-01
5.7746e-01
5.8840e-01
6.0006e-01
5.9485e-01
6.1771e-01
6.3621e-01
6.3467e-01
6.5467e-01
6.6175e-01
6.6985e-01
6.8091e-01
6.8217e-01
6.9958e-01
7.1802e-01
7.2049e-01
7.3021e-01
7.3633e-01
7.4985e-01
7.6116e-01
7.7213e-01
7.7814e-01
7.8882e-01
8.1012e-01
7.9871e-01
8.3115e-01
8.3169e-01
8.4500e-01
8.4168e-01
8.5705e-01
8.6861e-01
8.8211e-01
8.8165e-01
9.0236e-01
9.0394e-01
9.2033e-01
9.3326e-01
9.4164e-01
9.5541e-01
9.6503e-01
9.6675e-01
9.8129e-01
9.8528e-01
9.9339e-01
Credits to Lutz Lehmann and PierU.
The problem lied in the array t_points not being a monotonous array. Adding a sort(t_points) before doing any calculations fixed the error.

How is risc-v neg instruction imeplemented?

How is the neg pseudo instruction implemented with only one sub?
I don't understand, as neg is R[rd] = -R[rs1]. But if I have sub, it is R[rs1] - something.
The "something" in this case is the zero register. but you're not subtracting that from the register, you're subtracting the register from that.
The:
neg rd, rs
pseudo-instruction is meant to put the negation of rs into rd. The
sub rd, zero, rs
instruction subtracts rs from zero, placing the result into rd.
rd := -rs ; example: -(42) -> -42
rd := 0 - rs ; 0 - 42 -> -42
Since -x is the same as 0 - x, they are equivalent.
If you want a more comprehensive list of pseudo instructions and what they map to, here an image which details some, including the specific one you asked about:

Verified software toolchain: if-then-else proof

I'm learning using the Verified Software Toolchain (VST). I get stuck at proving a simple "if-then-else" block.
Here is the .c file:
int iftest(int a){
int r=0;
if(a==2){
r=0;
else{
r=0;
}
return r;
}
I write a specification about the iftest() as follow:
Definition if_spec :=`
DECLARE _iftest`
WITH a0:int
PRE [_a OF tint]
PROP ()
LOCAL (`(eq (Vint a0)) (eval_id _a))
SEP ()
POST [tint]
PROP ()
LOCAL ((`(eq (Vint (Int.repr 0))) retval))
SEP ().`
the proof steps are:
Lemma body_iftest : semax_body Vprog Gtot f_iftest if_spec.Proof.
start_function.
name a _a.
name r _r.
forward. (*r=0*)
simplify_typed_comparison.
forward. (*if(E)*). go_lower. subst. normalize.
it generates a hypothesis:Post := EX x : ?214, ?215 x : environ -> mpred and the "then" clause can't go on by "go_lower" and "normalize".
In the current version of VST there is a forward_if PRED tactic. Here is how you can use it to solve your goal:
Require Import floyd.proofauto.
Require Import iftest.
Local Open Scope logic.
Local Open Scope Z.
Definition if_spec :=
DECLARE _iftest
WITH a0:int
PRE [_a OF tint]
PROP ()
LOCAL (`(eq (Vint a0)) (eval_id _a))
SEP ()
POST [tint]
PROP ()
LOCAL ((`(eq (Vint (Int.repr 0))) retval))
SEP ().
Definition Vprog : varspecs := nil.
Definition Gtot : funspecs := if_spec :: nil.
Lemma body_iftest : semax_body Vprog Gtot f_iftest if_spec.
Proof.
start_function.
name a _a.
name r _r.
forward.
forward_if (PROP ()
LOCAL (`(eq (Vint (Int.repr 0))) (eval_id _r)) SEP()).
+ forward.
entailer.
+ forward.
entailer.
+ forward.
Qed.
P.S. #bazza is right about a missing } before else. I assume it is fixed.
Potentially a non-helpful answer, but I can't help noticing that your .c code has 3 {'s and only 2 }'s, suggesting that it doesn't compile. Could the error message you're receiving have something to do with that?

"LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd" when importing from Matlab files

After importing this data file from Matlab with scipy.io.loadmat, things appeared to work fine until we tried to calculate the conditioning number of one of the matrixes within.
Here's the minimum amount of code that reproduces for us:
import scipy
import numpy
stuff = scipy.io.loadmat("dati-esercizio1.mat")
numpy.linalg.cond(stuff["A"])
Here's the extended stacktrace courtesy of iPython:
In [3]: numpy.linalg.cond(A)
---------------------------------------------------------------------------
LapackError Traceback (most recent call last)
/snip/<ipython-input-3-15d9ef00a605> in <module>()
----> 1 numpy.linalg.cond(A)
/snip/python2.7/site-packages/numpy/linalg/linalg.py in cond(x, p)
1409 x = asarray(x) # in case we have a matrix
1410 if p is None:
-> 1411 s = svd(x,compute_uv=False)
1412 return s[0]/s[-1]
1413 else:
/snip/python2.7/site-packages/numpy/linalg/linalg.py in svd(a, full_matrices, compute_uv)
1313 work = zeros((lwork,), t)
1314 results = lapack_routine(option, m, n, a, m, s, u, m, vt, nvt,
-> 1315 work, -1, iwork, 0)
1316 lwork = int(work[0])
1317 work = zeros((lwork,), t)
LapackError: Parameter a has non-native byte order in lapack_lite.dgesdd
All obvious ideas (like flattening and reshaping the matrix or recreating the matrix from scratch reassigning it element by element) failed. How can I want to massage the data, then, in order to make it more agreeable with numpy?
It's a bug, fixed some time ago: https://github.com/numpy/numpy/pull/235
Workaround:
np.linalg.cond(stuff['A'].newbyteorder('='))
This works for me:
In [33]: stuff = loadmat('dati-esercizio1.mat')
In [34]: a = stuff['A']
In [35]: try: np.linalg.cond(a)
....: except: print "Fail!"
Fail!
In [36]: b = np.array(a, dtype='>d')
In [37]: np.linalg.cond(b)
Out[37]: 62493201976.673141
In [38]: np.all(a == b) # Verify they hold the same data.
Out[38]: True
Apparently it's something wrong with the byte order (endianness?) of each number in the resulting ndarray and not just with the ndarray object itself.
Something like this but more elegant should do the trick:
n, m = A.shape()
B = numpy.empty_like(A)
for i in xrange(n):
for j in xrange(m):
B[i,j] = float(A[i,j])
del A
B = A
print numpy.linalg.cond(A) # 62493210091.354507
(For some reason an in-place replacement still gives that error - so there's something wrong with the byte order of the whole object, too.)

Math not working as expected

I can't figure out how to use a variable as a math expression. The following code won't return the expected solution but doesnt throw any errors, instead it will just output the contents of the Q variable again in A.
Q = 7+5=
StringReplace, Q, Q, =,, 1
A := Q
Using %Q% or Q = %Q% doesn't work. And running MsgBox, %A% after it will just return "7+5".
Please help as I'm pretty new to AutoHotKey :)
Check this out:
http://www.autohotkey.com/community/viewtopic.php?t=17058
This should do it though:
Q = 7+5=
StringReplace, Q, Q, =,, 1
StringReplace, Q, Q, +,%A_SPACE%, 1
stringleft, first, Q, 1
stringright, last, Q, 1
x := first + last
MsgBox, %first%, %last%, %x%