Prolog program error 1010

Program error 1010 prolog Error and warning messages from programming systems like SWI Prolog tell you that there is (or may be) a problem, but they can be a little cryptic in terms of telling you what the problem is. The following table is intended to demystify the messages. Message Likely cause(s) ERROR: Out […]

Program error 1010 prolog

Error and warning messages from programming systems like SWI Prolog tell you that there is (or may be) a problem, but they can be a little cryptic in terms of telling you what the problem is. The following table is intended to demystify the messages.

ERROR: predname/1: Arguments are not sufficiently instantiated

ERROR: predname/1: Type error: `character’ expected, found `abc’

Message Likely cause(s)
ERROR: Out of local stack Usually infinite recursion. Look at your recursive rules and ensure that there is some provision to stop the recursion from going on for ever.
Means that in the program file test.pl , at line 1 (that’s the :1 ), you have used a variable name that not used anywhere else in that rule (or fact). Can mean a spelling mistake, as in this case — Cihld should presumably be Child . However, it could just be that you really only wanted to use the variable once, as with Someone , in
happy(Person) :- loves(Someone, Person).
In this case, you can get rid of the warning message by putting an underscore in front of the singleton variable:
happy(Person) :- loves(_Someone, Person).
means that rich was previously defined, and you have now loaded a new definition of it via a consult operation. This will have cleared out the previous definition of rich .
This means that you have tried to redefine a system predicate. It is usually a very bad idea to redefine a system predicate, as it means that any other code that calls the system predicate may end up using your definition, which might be entirely inappropriate. It is usually better to think of another name for your predicate: perhaps make_assertion instead of assert in the example above.
If you absolutely have to use the name reserved for the system predicate for some very good reason, you can do this by inserting the directive e.g. before the point where you begin to redefine the system predicate.
This is telling you something like the following: you tried to use a directive like :- [‘nlp-basis.pro’]. to load some extra code into Prolog, but there was no such file available. This could happen either because, although the file exists, it’s in another directory, or because you mis-spelled the filename. In this case, the file is one that is often used in COMP9414 nlp assignments, and it is spelled nlpbasis.pro not nlp-basis.pro — i.e. no hyphen. Solution — fix the spelling of the filename in your code. The :6: at the end of the first and third lines of the messages is telling you that the problem was detected at line 6 of your code file. The extra «Warning» message is about the same problem.
This says that, from the point of view of the Prolog system, your code stopped abruptly at line 12, without completing the rule or fact that it was half-way through. This might be exactly what has happened, or it might be that some syntax error in your code has caused Prolog to get confused about what you are trying to do.
This says that, from the point of view of the Prolog system, your code stopped abruptly at line 92, partway through a clause. This is similar to the previous message, but Prolog had passed the start of a clause when the problem occurred.
Likely to occur with other messages, e.g. singleton variable warnings. Probably means you have a punctuation error in a rule, something like this: There should be a comma, not a full stop, at the end of the first line.
You have called a predicate, predname , probably a predefined one, and you supplied an argument that was a variable that is yet bound, where it doesn’t make sense to supply an unbound variable. For example, tab(N) (which prints N spaces) doesn’t make sense if N is not bound to a non-negative whole number. The argument must be bound at the time the goal is evaluated — it is not good enough to supply a value via a later goal. The /1 refers to the number of arguments that predname takes, in this case 1, but will vary according to the number of arguments you provide to the particular predicate. Like the preceding example errors, this one is likely to come, in practice, with a filename:linenum:position to tell you where in your program the problem is located.
Some Prolog built-in predicates insist on a particular type of argument — maybe integer, or string, for example. In this case, the predicate predname was expecting a single character, but you provided the string ‘abc’ . Like preceding example errors, this one is likely to come, in practice, with a filename:linenum:position to tell you where in your program the problem is located.

I plan to add to the table as I encounter more such messages. Suggestions welcome, please send a cut-and-paste of the message, the dialogue with SWI Prolog that generated it, and the Prolog code as an attachment. This is not a free debugging service, but I’ll try to include such examples in this list.

Bill Wilson’s contact info
Last updated:
UNSW’s CRICOS Provider No. is 00098G

Источник

Работа с файлами на Visual/Turbo Prolog

Чтобы работать с файлами в Turbo и Visual Prolog нужно сначала объявить тип файла в разделе domains, например:
file = students_file; teachers_file
В данном случае нами объявлены два идентификатора:

  1. students_file — идентификатор файла, содержащего записи о студентах;
  2. teachers_file — идентификатор файла, содержащего записи о преподавателях;

Типы файлов могут использоваться, например для задания различных имен бинарным и текстовым файлам или файлам, отличающимся логически (как в нашем случае — файл с данными студентов и файл с данными преподавателей). Это нужно, т.к. ваша программа может одновременно открывать несколько файлов, обращаться к ним вы можете через идентификаторы.

Для работы с файлом, нужно его открыть помощью одной одной из функций. При открытии физический файл на диске связывается с одним из идентификаторов, объявленных вами в разделе domains . Доступны следующие функции открытия файла:

    openread(Id, Path) — открывает файл для чтения, если файл не получится открыть — вы получите ошибку:

PROGRAM ERROR. Module:C:WINDOWSTEMPGOAL$000.PRO Pos:445
Message:7002 File not found

Чтобы избежать ошибки при отсутствии файла в функции openread , нужно проверить наличие соответствующего файла на диске с помощью функции existfile(Path) .

Итак, мы открыли файл, но чтобы записывать или считывать с него данные нужно задать его в качестве текущего устройства ввода/вывода, сделать это можно с помощью функций writedevice(Id) и readdevice(Id) . После их вызова все запросы на ввод/вывод (например вызовы функций readInt , write , nl ) будут переадресованы соответствующему файлу. Если после работы с файлом нам потребуется вывести сообщения на экран или запросить ввод с клавиатуры — нужно переключить этими же функциями ввод/вывод на соответствующие устройства — stdin , stdout , stderr .

После работы с файлом его нужно закрывать функцией closefile(Id) .

В качестве примера, напишем программу, считывающую список целых чисел с файла:

Функция file_numbers_to_list использует метод накапливающего параметра — результат накапливает во втором аргументе (буфере). Считывание продолжается до тех пор, пока в файле содержатся данные — когда будет достигнут конец файла eof(File) завершится успешно и функция вернет накопленный результат. Если файл содержит что-то кроме целых чисел, функция readint вернет fail и функция выведет сообщение об ошибке.
Важно что функции ввода в visual prolog считывают данные с клавиатуры или текстового файла до символа перевода строки или конца файла, поэтому если вы запишите числа в файле через пробел — они завершатся неудачей. Исходный файл для этой программы должен содержать по одному числу на каждой строке. Если числа в файле содержатся в ином порядке или вам требуется обработать отдельные слова файла — можете считать строки целиком с помощью функции readln , преобразовать их в списки символов, затем — в список слов, после чего слова можно будет преобразовать в числа.

Источник

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
constants
      fmax=100
                
     domains
     
 
      
      int = integer
      lint = int*
      coord = c(int,int)   
      p = poz(char,coord)   
      lpoz = p*
      prob = coord*       
      lp = prob*          
 
     
     
      
      est = e(int,int)     
      tr=l(prob,est);      
         t(prob,est,tlist) 
                           
      tlist=tr*           
      son = s(prob,int)    
      lson = son*          
   
     
     predicates
     
    
       start1(prob)                
       start2(prob)               
       start3(prob)              
       nondeterm show_sol(lp)              
       show_poz(prob)             
       nondeterm change(coord,coord,prob,prob) 
       dist(coord,coord,int )    
       dist1(int,int,int )        
       nondeterm tot_dist(prob,prob,int)    
       points(coord,coord,int )  
       nondeterm sort(prob,int)             
       nondeterm sort1(prob,coord,int)      
                                 
       nondeterm member1(p,lpoz)
       nondeterm member1(int,lint)
     
    
       nondeterm solve(prob,lp)            
       nondeterm expo(lp,tr,int,tr,int,lp)  
       nondeterm optf(tlist,int)            
       nondeterm f(tr,int)                  
       nondeterm h(prob,int)               
       nondeterm sons(int,lson,tlist)      
       nondeterm prolong(lp,tr,int,tr,int,int,lp) 
       nondeterm continue(prob,lp,son)     
       end(prob)                 
       nondeterm go(prob,prob,int)          
       into(tr,tlist,tlist)      
       member(prob,lp)
       min(int,int,int)
 
     
     
     goal  
          start1(A),
          solve(A,S),
          show_sol(S),nl.  
     
     clauses
     
   
      
      solve(A,S):-
          expo([],l(A,e(0,0)),fmax,_,1,S).
          
      expo(Way,l(X,_),_,_,1,[X|Way]):-
          end(X).
      
      expo(Way,l(X,e(F,G)),Limit,D1,Yes,Sol):-
          F<=Limit,
          findall(Y,continue(X,Way,Y),Lsons),!,
          sons(G,Lsons,DD),
          optf(DD,F1),
          expo(Way,t(X,e(F1,G),DD),Limit,D1,Yes,Sol).
      
      expo(Way,l(X,e(F,G)),Limit,D1,Yes,Sol):-
          F<=Limit,    
          Yes= -1.
      
      expo(Way,t(X,e(F,G),[D|DD]),Limit,Dr1,Yes,Sol):-
          F<=Limit,    
          optf(DD,OF),
          min(Limit,OF,Limit1),
          expo([X|Way],D,Limit1,D1,Yes1,Sol),
          prolong(Way,t(X,e(F,G),[D1|DD]),Limit,Dr1,Yes1,Yes,Sol).
      
      expo(_,t(_,_,[]),_,_,-1,_):-!. 
      
      expo(_,D,Limit,D,0,_):-    
          f(D,F),  
          F>Limit. 
     
      continue(X,Way,s(Y,C)):-
          go(X,Y,C),
          not(member(Y,Way)).    
      
      prolong(_,_,_,_,1,1,Sol).
      
      prolong(Way,t(X,e(F,G),[D1|DD]),Limit,Dr1,Yes1,Yes,Sol):-
          Yes1=0, into(D1,DD,DD1),
          optf(DD1,F1),
          expo(Way,t(X,e(F1,G),DD1),Limit,Dr1,Yes,Sol).
      
      prolong(Way,t(X,e(F,G),[D1|DD]),Limit,Dr1,Yes1,Yes,Sol):-
          Yes1= -1, DD1=DD,
          optf(DD1,F1),
          expo(Way,t(X,e(F1,G),DD1),Limit,Dr1,Yes,Sol).  
      
      sons(_,[],[]).
      sons(G0,[ s(X,C)|TX ],DD):-
          G=G0+C,
          h(X,H),
          F=G+H,
          sons(G0,TX,DD1),
          into(l(X,e(F,G)),DD1,DD).
      
        
      into(D,DD,[D|DD]):-
          f(D,F), optf(DD,F1),
          F<=F1,!.
      into(D,[D1|DD],[D1|DD1]):-
          into(D,DD,DD1).
      
      f( l(_,e(F,_)),F).
      f( t(_,e(F,_),_),F).
      
      optf([D|_],F):-
          f(D,F).
      optf([],fmax).
          
      min(X,Y,X):-
          X<=Y,!.
      min(X,Y,Y).        
     
      member(H,[H|_]):-!.
      member(H,[_|T]):-
          member(H,T).
   
     go( [Hole|T],[Fsh|T1],1 ):-
        change(Hole, Fsh, T, T1).
     
     
     change(H,F,[F|T],[H|T]):-
        dist( H,F,1).    
     
      
     change(H,F,[F1|T],[F1|T1]):-
        change(H,F,T,T1).
     
     
     
      start1( [c(2,2),c(2,3),c(1,2),c(3,3),c(2,1),c(3,2),c(3,1),c (1,1),c(1,3)] ).
      start2( [c(2,1), c(1,2), c(1,3), c(3,3), c(3,2), c(3,1),
              c(2,2), c(1,1), c(2,3)] ).
      start3( [c(2,2), c(2,3), c(1,3), c(3,1), c(1,2), c(2,1),
              c(3,3), c(1,1), c(3,2)] ).
      end(    [c(2,2), c(1,3), c(2,3), c(3,3), c(3,2), c(3,1),
              c(2,1), c(1,1), c(1,2)] ).
     
      
      points( c(2,2),_,1):-!.      
      points( c(1,3),c(2,3),0):-!.  
      points( c(2,3),c(3,3),0):-!.  
      points( c(3,3),c(3,2),0):-!.  
      points( c(3,2),c(3,1),0):-!.  
      points( c(3,1),c(2,1),0):-!.  
      points( c(2,1),c(1,1),0):-!.
      points( c(1,1),c(1,2),0):-!.
      points( c(1,2),c(1,3),0):-!.
      points( _,_,2)          :-!. 
     
    
      h([ Hole|T ], H):-
         end([ Hole1|T1 ]),
         tot_dist(T,T1,D),
         sort(T,S),
         H = D + 3*S.
      
      
      tot_dist([],[],0).
      tot_dist( [F|T],[F1|T1],D ):-
         dist(F,F1,D1),
         tot_dist(T,T1,D2),
         D = D1+D2.
      
      
       dist(c(X,Y),c(X1,Y1),D):-
         dist1(X,X1,DX),   
         dist1(Y,Y1,DY),   
         D = DX+DY.
        
       dist1(A,B,D):-
          D = A-B, D>=0,!;
          D = B-A.
      
     
      sort( [ First|T ], S):-
         sort1( [ First|T ], First, S).  
      
     
      sort1( [ X,Y|T ],First , S):-
         points( X,Y,S1),
         sort1( [ Y|T ], First, S2),
         S=S1+S2.
      
     
      sort1( [X], First, S):-
         points( X, First, S).  
    
      show_sol([]).
      show_sol([H|T]):-
         show_sol(T),
         nl,write("-------"),
         show_poz(H),
         readchar(_).
      
    
      show_poz([ F0,F1,F2,F3,F4,F5,F6,F7,F8 ]):-
        
         member1(Y,[3,2,1]), nl,
        
         member1(X,[1,2,3]),
         
        
         member1( poz(Fishka,c(X,Y)), [poz('0',F0), poz('1',F1),poz('2',F2),
                 poz('3',F3), poz('4',F4), poz('5',F5), poz('6',F6),
                 poz('7',F7), poz('8',F8) ] ),
       
         write( " ",Fishka), fail.
      
          
      show_poz(_).
      
      member1(H,[H|_]).
      member1(H,[_|T]):-
          member1(H,T).

PREDICATES
nondeterm male(symbol)
nondeterm female(symbol)
nondeterm wife(symbol,symbol)
nondeterm mother(symbol,symbol)
nondeterm father(symbol,symbol)
nondeterm brother(symbol,symbol)
nondeterm sister(symbol,symbol)
nondeterm sonInLaw(symbol,symbol)
nondeterm brotherInLaw(symbol,symbol)
nondeterm uncle(symbol,symbol)
nondeterm sibling(symbol,symbol)
nondeterm grandson(symbol,symbol)
nondeterm grandfather(symbol,symbol)
Clauses
male(mark).
male(ahmed).
male(zeeshan).
male(summer).
female(sara).
female(sana).
wife(sara,mark).
wife(sana,ahmed).
mother(X,Y):-female(X),father(Z,Y),wife(X,Z),X<>Y.
mother(sara,sana).
father(X,Y):-male(X),mother(Z,Y),wife(Z,X),X<>Y.
brother(X,Y):-male(X),father(Z,X),father(Z,Y),X<>Y.
sister(X,Y):-female(X),father(Z,X),father(Z,Y),X<>Y.
sonInLaw(X,Y):-male(X),father(Y,Z),wife(Z,X) ; male(X),mother(Y,Z),wife(Z,X),X<>Y.
brotherInLaw(X,Y):-male(X),sister(Z,X),wife(Z,Y).
sibling(X,Y):-brother(X,Y);sister(X,Y),X<>Y.
uncle(X,Y):- sibling(X,Z),father(Z,Y),X<>Y.
grandfather(X,Y):- father(X,Z), father(Z,Y);father(X,Z), mother(Z,Y),X<>Y.
grandson(X,Y):- father(Z,X), father(Y,Z);father(Z,X), mother(Y,Z),X<>Y.
Goal
uncle(mark,sana).
My Prolog is giving me Error 1010.

This should work
In WIP7 this works
class predicates
male:(symbol) procedure (x).
female:(symbol) procedure (x).
wife:(symbol,symbol) procedure (x,y).
mother:(symbol,symbol) procedure (x,y).
father:(symbol,symbol) procedure (x,y).
brother:(symbol,symbol) procedure (x,y).
sister:(symbol,symbol) procedure (x,y).
sonInLaw:(symbol,symbol) procedure (x,y).
brotherInLaw:(symbol,symbol) procedure (x,y).
uncle:(symbol,symbol) procedure (x,y).
sibling:(symbol,symbol) procedure (x,y).
grandson:(symbol,symbol) procedure (x,y).
grandfather:(symbol,symbol) procedure (x,y).
clauses
male(mark).
male(ahmed).
male(zeeshan).
male(summer).
female(sara).
female(sana).
wife(sara,mark).
wife(sana,ahmed).
mother(X,Y):-female(X),father(Z,Y),wife(X,Z),X<>Y.
mother(sara,sana).
father(X,Y):-male(X),mother(Z,Y),wife(Z,X),X<>Y.
brother(X,Y):-male(X),father(Z,X),father(Z,Y),X<>Y.
sister(X,Y):-female(X),father(Z,X),father(Z,Y),X<>Y.
sonInLaw(X,Y):-male(X),father(Y,Z),wife(Z,X);male(X),mother(Y,Z), wife(Z,X),X<>Y.
brotherInLaw(X,Y):-male(X),sister(Z,X),wife(Z,Y).
sibling(X,Y):-brother(X,Y);sister(X,Y),X<>Y.
uncle(X,Y):- sibling(X,Z),father(Z,Y),X<>Y.
grandfather(X,Y):-father(X,Z),father(Z,Y);father(X,Z),mother(Z,Y), X<>Y.
grandson(X,Y):- father(Z,X), father(Y,Z);father(Z,X), mother(Y,Z),X<>Y.
clauses
run():-
console::init(),
uncle(mark,sana),
programControl::sleep(1000).
I think that with VIP 5.1 you can put
check_determ

Related

How to use TeeChart to produce such chart?

Using the data points pasted at the end, I get a chart using TeeChart looking like below (2nd image). However, what I want to get is as shown as the 1st image (black line). I am wondering how to do this? Any comments (about how to do or about the algorithm) are appreciated!
by GaussView (IR spectrum)
by TeeChart
data
11.25 0.8558
13.93 0.7101
17.49 1.7783
18.48 0.0972
20.91 0.7608
23.36 2.0540
27.87 1.7063
31.34 0.4998
32.45 0.8735
36.86 1.9740
37.68 1.1448
39.02 1.6381
39.64 2.4984
40.63 2.5854
43.90 1.9891
45.38 1.0168
46.85 3.4588
50.19 0.5997
51.69 3.0986
52.37 5.2783
54.35 1.3672
55.93 1.9774
58.26 1.4327
60.00 0.1276
62.18 0.1294
64.04 2.5145
66.10 7.5823
68.48 0.4689
70.60 3.5168
72.22 6.7262
73.78 2.9225
76.05 1.6195
77.39 2.9711
79.05 3.0244
79.51 7.5896
81.41 4.4896
83.34 4.7092
85.55 5.7364
91.65 9.5119
93.06 4.1190
95.26 0.5367
97.60 1.7773
99.59 4.0967
100.29 3.3551
102.68 2.9290
104.37 2.1907
105.86 3.1003
108.29 4.6200
108.83 1.6020
112.74 4.5426
113.61 5.8697
115.43 5.3545
116.92 7.5064
118.52 1.1735
121.26 3.2800
123.70 0.7140
125.51 12.3312
126.79 0.6539
129.59 1.6488
130.17 3.3001
133.15 5.4448
133.81 5.2958
135.57 0.7273
136.74 2.7725
138.48 7.9547
140.74 4.4754
143.16 4.1672
145.21 2.0647
147.25 6.0894
150.77 6.6854
153.96 0.2456
154.71 5.2882
157.72 3.3148
159.83 41.1787
160.94 3.3881
164.82 21.6722
167.02 25.2616
168.56 5.3165
172.00 6.9968
174.48 3.4963
175.31 3.6395
177.35 1.3092
180.03 6.7443
181.92 2.3712
185.01 1.8564
186.79 8.2453
188.59 11.1710
191.39 2.9369
196.44 5.2397
197.33 6.8805
199.89 15.0378
201.45 4.7054
203.79 13.3486
207.10 5.7904
209.25 11.0755
211.85 23.5711
213.68 17.2254
214.61 3.9448
217.47 34.9757
220.06 5.1604
220.74 3.7671
225.87 13.0953
229.77 8.4948
233.98 21.1654
237.24 17.6599
238.71 25.2668
239.34 15.7494
244.56 43.4527
246.16 36.9053
248.17 7.5639
251.21 8.0873
253.46 4.3431
255.42 5.9059
256.73 1.7785
260.22 14.1219
260.70 4.8738
265.07 10.0827
267.08 4.9080
268.50 11.9286
271.89 8.8873
274.01 29.4943
275.04 29.2369
277.04 52.4743
278.13 14.3284
281.82 3.3507
284.56 21.7815
288.79 8.5983
290.67 30.2466
294.11 10.9149
301.49 7.3059
302.30 67.0245
302.84 6.5049
305.51 0.2989
311.16 4.8017
316.45 16.0656
320.37 42.8200
325.45 36.8340
336.19 35.0153
338.45 18.0032
339.63 3.6068
340.62 5.0152
348.49 77.5149
352.39 84.1067
358.46 16.2392
364.34 56.0846
371.03 78.4101
378.71 50.3951
381.68 79.3127
391.26 10.3953
394.69 75.6727
397.38 50.5976
399.97 40.0959
405.64 23.4627
417.96 12.1802
419.47 21.9191
429.40 1.9362
431.84 10.8746
437.11 6.7498
439.38 42.1917
454.11 18.9428
459.08 41.1182
465.76 50.9344
467.25 27.1854
475.56 130.5899
481.25 72.5219
487.87 25.8915
489.15 5.5288
489.42 124.2637
497.37 167.8169
501.23 6.7103
502.49 9.7129
508.77 26.4849
520.56 9.5302
522.17 2.9284
523.54 124.3465
524.98 79.0902
528.27 53.1656
533.88 12.9278
536.31 203.4675
540.72 33.9929
543.41 142.5774
550.07 37.2596
557.93 168.8374
560.52 60.4300
562.84 36.1606
566.10 151.7689
567.79 66.6189
572.38 149.8744
576.57 79.9780
585.50 112.8536
586.51 95.4084
597.52 3.5723
600.64 60.4112
603.83 147.9974
604.41 29.0763
606.39 7.1134
609.57 6.2102
611.10 7.8785
612.84 162.3687
620.43 170.4984
625.49 160.0876
630.37 36.9260
638.97 40.4913
646.00 25.4423
646.05 17.5637
652.18 23.6302
653.87 45.4506
655.96 31.1678
657.95 43.5278
666.44 17.7154
668.63 78.3033
674.15 20.1193
675.43 28.3611
679.85 99.0228
684.13 62.2844
685.09 36.8384
686.88 44.9261
688.54 86.4601
690.35 23.8856
691.64 245.3722
699.16 120.5513
709.26 2.6988
723.74 332.8580
726.74 6.5182
728.74 165.1788
730.46 5.6564
738.13 13.5268
740.13 12.5284
742.74 113.7637
752.67 23.3185
753.85 50.6479
754.67 2.4454
771.93 6.8897
775.45 195.5114
777.97 60.3044
782.04 1.5514
784.40 28.3898
785.12 127.7568
787.49 6.4007
795.51 7.3133
799.34 201.9055
802.14 19.5573
818.55 382.3869
819.71 6.5877
822.96 14.2146
824.05 2.2121
826.46 111.9575
830.73 29.2754
831.01 24.9736
834.71 22.8259
844.08 59.8333
845.62 40.3083
850.76 135.1998
856.03 2.2111
858.83 5.4722
860.88 228.0665
867.35 122.4081
875.07 5.8894
877.33 74.5747
881.75 28.0580
884.49 4.7371
887.88 27.9916
888.41 81.4206
895.50 18.5746
906.14 37.3150
909.57 39.2727
909.89 13.8018
912.76 3.8752
916.27 0.2486
926.60 12.7987
926.73 10.4374
929.15 131.5315
931.10 2.9229
934.57 113.7453
942.69 91.3771
948.15 25.1075
951.93 33.4258
954.69 44.6893
964.15 1.5994
965.00 0.7321
972.10 8.4069
973.43 7.5676
979.59 10.5092
981.39 30.0315
983.34 157.9592
987.12 24.8756
995.21 81.4163
995.60 22.9050
996.60 18.5511
997.58 41.7678
1001.40 7.2941
1010.63 3.7654
1017.41 12.3927
1020.10 1.2928
1020.50 6.4156
1027.74 3.5186
1029.51 15.7644
1032.33 4.9588
1038.71 4.4052
1042.08 3.1957
1042.54 23.7493
1044.90 0.6490
1051.57 9.5923
1058.97 6.4381
1072.38 13.5097
1075.43 1.4965
1076.01 16.5798
1079.15 0.7097
1082.69 163.1472
1085.62 11.4565
1090.04 9.5450
1104.35 0.4181
1105.81 19.4965
1107.07 1.4116
1107.32 2.1959
1107.51 0.8469
1109.85 16.5227
1116.34 3.7611
1117.27 22.3061
1122.22 5.0637
1123.85 2.0819
1126.87 99.5244
1127.27 0.7508
1129.03 7.9063
1131.13 12.5686
1136.06 2.4318
1138.90 11.9482
1139.10 0.9399
1146.32 3.3872
1159.39 11.9471
1161.78 14.1617
1174.95 23.2351
1179.72 14.9091
1189.14 3.7741
1204.68 17.3601
1205.62 25.2461
1214.86 38.4565
1222.25 4.7630
1222.40 15.9294
1222.83 12.4804
1229.30 17.8518
1248.53 23.6590
1252.67 56.1945
1257.42 8.6184
1261.43 8.7950
1261.70 4.7045
1265.78 16.4704
1267.68 4.8315
1273.64 1.5993
1273.80 83.2365
1275.45 18.8720
1284.93 0.8743
1286.10 12.7644
1286.41 38.1346
1291.55 238.9537
1299.52 27.7401
1302.81 21.4327
1312.97 7.2615
1316.40 37.1928
1319.76 32.1009
1321.66 43.8679
1323.22 11.7175
1324.58 0.5651
1330.94 16.7787
1332.59 16.8946
1337.01 3.1987
1338.49 12.1263
1340.41 31.1700
1345.84 13.8655
1346.50 0.9794
1349.54 14.2011
1357.85 45.9726
1358.09 3.9610
1362.71 5.3914
1366.21 16.9550
1372.10 64.1772
1374.92 161.5665
1380.58 230.3131
1384.00 328.5477
1385.04 5.1667
1390.07 0.1589
1397.37 40.3024
1397.88 5.2971
1398.44 3.5395
1401.91 22.7442
1403.68 0.8136
1404.50 30.1834
1407.30 62.3116
1407.42 3.0998
1410.47 17.7966
1411.88 14.4825
1414.12 10.3780
1418.49 8.3303
1419.19 17.0070
1419.62 3.6385
1419.71 19.0577
1422.55 6.9579
1423.39 1.0293
1431.35 333.3874
1436.26 307.7709
1440.15 41.7923
1441.39 536.8224
1443.14 252.0576
1445.99 216.7363
1449.43 128.0188
1462.98 11.9692
1467.30 28.3347
1473.56 23.1465
1475.93 42.4514
1483.98 36.0277
1484.24 5.2501
1484.39 24.3948
1485.45 10.8186
1490.44 11.5231
1492.27 7.3633
1495.11 8.5312
1495.56 18.0179
1497.77 3.1224
1497.88 14.2399
1498.31 3.0918
1499.72 5.7379
1501.76 26.4984
1504.98 13.7143
1507.61 1.4629
1508.28 8.4327
1508.41 4.8958
1508.48 4.2296
1512.21 8.4668
1515.46 1.8979
1518.07 20.2652
1518.82 9.2094
1521.34 9.8395
1526.17 2.9542
1526.43 9.4439
1528.02 3.3756
1528.30 2.4509
1532.78 5.3007
1534.13 6.5043
1537.24 53.5120
1540.81 1.9113
1543.85 4.4977
1544.20 4.2213
1548.35 3.6878
1552.54 14.8614
1559.24 11.6988
1564.07 74.1574
1566.46 108.9087
1567.58 6.3844
1575.43 2.5287
1577.84 233.8768
1595.41 237.2607
1596.87 369.0431
1616.23 173.9335
1624.09 836.9518
1626.98 233.4742
1628.60 5.4746
1632.35 100.3850
1637.82 390.7923
1643.65 382.0132
1676.36 174.8716
1677.37 240.7762
1681.68 71.5960
1686.63 207.9686
1689.79 321.4797
1706.91 270.6300
1710.36 276.3541
1719.02 103.4710
1722.09 13.0707
1732.52 118.1263
1733.45 134.7822
1737.38 86.6398
1741.65 193.3777
1745.96 267.6557
1748.85 104.5308
1750.11 84.3295
1754.89 142.1761
1762.19 44.6467
1778.03 277.3395
1786.51 54.7132
1801.43 124.4060
2501.45 2817.4313
2892.60 1433.0563
3010.32 37.5543
3018.83 24.9084
3020.63 4.2749
3026.82 31.0382
3027.83 7.3210
3028.25 21.5317
3034.03 19.3657
3042.31 18.5627
3042.36 29.6968
3045.35 18.7716
3047.91 13.3663
3050.76 6.5443
3053.48 25.7608
3055.29 40.7227
3055.58 28.5712
3055.88 7.9362
3057.54 10.2078
3059.36 27.4736
3059.83 26.5108
3059.85 22.3488
3061.56 4.6525
3063.51 25.9303
3065.41 14.8583
3066.43 25.5202
3066.83 40.4775
3068.42 6.6192
3068.55 27.7206
3069.66 5.1897
3074.54 30.3667
3077.72 1.0555
3082.30 19.8899
3085.29 277.0890
3086.03 7.4622
3086.91 55.7138
3090.29 9.7699
3090.42 23.7039
3098.95 15.2559
3100.15 37.0280
3101.05 12.4841
3104.13 31.3489
3104.26 305.3252
3107.27 14.1801
3107.65 8.3824
3111.25 23.7250
3113.32 1.6109
3116.84 31.4006
3118.15 8.3440
3123.33 5.3227
3127.86 7.6340
3129.01 7.9926
3132.66 10.0175
3138.18 348.0472
3138.83 3.9995
3145.04 497.0629
3165.17 3.9671
3168.85 798.7276
3200.74 837.1487
3204.12 38.9204
3206.21 21.6877
3206.27 39.0288
3206.94 34.9876
3212.51 37.8135
3212.92 20.7165
3226.37 15.2672
3281.65 23.1858
3282.58 732.5195
3283.15 78.0229
3283.92 991.2039
3287.78 41.3881
3290.37 28.2757
3290.38 7.2058
3292.55 27.3318
3294.23 639.1337
3297.11 79.7924
3316.31 8.5916
3322.30 531.3133
3334.75 1463.9099
3351.13 264.7960
3360.34 535.8013
3364.82 26.2667
3366.49 742.5906
3384.37 544.7382
3400.63 6.4281
3402.60 899.7517
3453.29 481.2669
3470.55 778.0064
3473.31 615.6872
3500.34 437.9592
3529.86 128.6586
3558.92 229.6075
3574.77 105.5502
3612.50 690.1041
3614.15 29.7018
3616.71 175.4585
3624.01 42.5718
3641.96 104.2644
3672.04 421.7865
3678.61 67.3033
3687.01 73.1667
3714.16 231.0432
3740.14 63.1046
3757.45 102.1256
3763.15 124.6488
3779.08 64.7553
3791.33 34.4075
As TLama has very kindly suggested, the solution is posted separately:
[Solution]
The difference between the plots is due to Lorentz line broadening. See Spectra line in Wikipedia. Very much thank you for all the comments! A very basic working example is given as follows:
unit uCurvFit;
interface
uses
uRtlTypes,
Math, SysUtils;
type
TLineShapeFitFunc = (lsffLorentz, lsffGauss);
TLineShapeFit = function(const RelOffset: Double): Double;
function Lorentz(const RelOffset: Double): Double;
function Gauss(const RelOffset: Double): Double;
procedure SpectrumFit(const OriginalFrequencies, OriginalIntensities
: TADouble; LineShapeFitFunc: TLineShapeFitFunc; var NFreqs: Integer;
var NewFrequencies: TADouble; var NewIntensities: TADouble);
implementation
function Lorentz(const RelOffset: Double): Double;
begin
Result := 1.0 / (1.0 + RelOffset * RelOffset);
end;
function Gauss(const RelOffset: Double): Double;
const
nln2: Double = -0.301029996; // - Log10(2.0);
begin
Result := Exp(nln2 * RelOffset * RelOffset);
end;
procedure SpectrumFit(const OriginalFrequencies, OriginalIntensities
: TADouble; LineShapeFitFunc: TLineShapeFitFunc; var NFreqs: Integer;
var NewFrequencies: TADouble; var NewIntensities: TADouble);
const
FrequencyStep: Double = 1.0;
HwHm: Double = 20.0; // Full Width at Half Maximum
var
I, J: Integer;
MaxFreq, MinFreq: Double;
Intensity, Freq, Center, RelOffset: Double;
LineShapeFit: TLineShapeFit;
begin
MaxFreq := 4000;
MinFreq := 0;
for I := 0 to Length(OriginalFrequencies) do
begin
if MaxFreq < OriginalFrequencies[I] then
MaxFreq := OriginalFrequencies[I];
if MinFreq > OriginalFrequencies[I] then
MinFreq := OriginalFrequencies[I];
end;
case LineShapeFitFunc of
lsffLorentz:
LineShapeFit := Lorentz;
lsffGauss:
LineShapeFit := Gauss;
end;
NFreqs := 1 + Trunc((MaxFreq - MinFreq) / FrequencyStep);
SetLength(NewFrequencies, NFreqs);
SetLength(NewIntensities, NFreqs);
for I := 0 to NFreqs - 1 do
begin
Intensity := 0.0;
Freq := MinFreq + I * FrequencyStep;
for J := 0 to Length(OriginalFrequencies) - 1 do
begin
Center := OriginalFrequencies[J];
RelOffset := (Freq - Center) / HwHm;
Intensity := Intensity + OriginalIntensities[J] * LineShapeFit(RelOffset);
end;
NewFrequencies[I] := Freq;
NewIntensities[I] := Intensity;
end;
end;
end.
Quoting your data source:
1801.43 124.4060
2501.45 2817.4313
and
2501.45 2817.4313
2892.60 1433.0563
and
2892.60 1433.0563
3010.32 37.5543
TeeChart is correctly rendering that given data.
.
If you want to change the data - and the graph - you should add the missed datapoints.
You're to decide how frequently (over which X-steps) your added counts should go. And which delta from y-zero would mean cancelling the propagation (as the difference becomes neglectedly tiny in your eyes).
Then you're to make a polynomial formula, determining how fast the values would fall down around every peak with respect to absolute value of the peak. Something like y == y0 / (a*(x-x0)^4 + b*(x-x0)^2 + c) or something alike. You should try this and that and finally get the number of coefficients and powers that suit your tastes.
Then around each peak (aka primary source datapoint) you should add those secondary, calculated points, until they would fall very close to y-zero or until they would meet the secondary values coming from the adjacent data point, which happen first.
You can derive a formula where two propagating waves would meat, depending upon y0, y1 and abs(x0-x1) or you just can be lazy and calculate full path from both directions then just insert max y-values.
This secondary, enhanced serie you would pass to the TeaChart and it would show what you like.
PS. take a look at mitov.com - he has few free components, but maybe there would be something suitable...
PPS. very rough draft for enriching data http://pastebin.com/JtaqkAkS
Estimation function and config should be manually tuned to get the best possible result, whatever a meaning the "best" would have.

Display string data in message box

Why is this not working with TJSONObject?
procedure TForm1.Button5Click(Sender: TObject);
var
js : TJSONObject;
isoDate1, isoDate2, data : string;
begin
isoDate1 := '2018-01-02T10:00:00.000Z';
isoDate2 := '2018-01-02T10:10:00.000Z';
js := TJSONObject.Create;
js.AddPair(TJsonPair.Create(isoDate1, 'TEST'));
js.AddPair(TJsonPair.Create(isoDate2, 'TEST2'));
outputdebugstring(pchar(js.ToString));
if js.TryGetValue<string>(isoDate1, data) then begin
ShowMessage(data);
end else begin
ShowMessage('data non trouvé pour ' + isoDate1);
end;
end;
output : Sortie de débogage: {"2018-01-02T10:00:00.000Z":"TEST","2018-01-02T10:10:00.000Z":"TEST2"} Processus Project1.exe (6232)
Expected Outcome:
The TryGetValue should put a string in data
ShowMessage should give me 'TEST' in a message box.
Outcome:
The ShowMessage give me 'data non trouvé pour 2018-01-02T10:00:00.000Z'.
Problem is the dot in your JSON path that you query with the TryGetValue method call. Dot char path parser (TJSONPathParser) interprets as key separator of pairs, whose value is about to be obtained. So, for example call like this:
if JSONObject.TryGetValue<string>('Foo.Bar', S) then
DoSomething;
is a query for The value of an object like this:
{"Foo": {"Bar": "The value"}}
not for The value with the key named this way:
{"Foo.Bar": "The value"}
So in your case you were trying to query the value of the 2018-01-02T10:00:00 object's key 000Z, which would require object like this:
{"2018-01-02T10:00:00": {"000Z": "TEST"}}
This JSON path dot notation is hardcoded at this time (without possibility of escaping dot chars in the queried path), so the only way is giving up on that method at this moment, or losing dots from key names.
The problem is the dot in your key. It's used as a seperator.
Delphi interprets '2018-01-02T10:00:00' as an object which has '000Z' as a property.
I would sugguest to get the value like this:
var
...
LJsonValue: TJSONValue;
begin
...
LJsonValue := js.GetValue(isoDate1);
if Assigned(LJsonValue) then
ShowMessage(LJsonValue.Value);
...
end;

Brute Force Algorithm to solve the TSP in Delphi [closed]

I'm writing a program for an extended project to simulate the travelling salesman problem. So far I have written it to allow the user to enter a route, as well as 'solving' a route using a nearest neighbour algorithm. I am now trying to write a brute force algorithm to solve for a selection of cities, from 3 cities up to about 13/14. The program is for the purpose of showing how the increase in number of cities leads to an exponential/factorial increase in the time taken to calculate the shortest route. I have tried to write a recursive function but cannot get my head around how it would work. I am in desperate need of some guidance as to how to do this. Any help would be appreciated.
Since there is no tag with Delphi version, then any version suits the TopicStarter just fine. I would base thus draft on XE2 version then. I also would assume that each town is only visited once. I would assume that there is a road network rather than a private airplane, that is between any chosen cities A and B there may be direct path or may not (connection only through other cities).
type TCity = class
public
Name : string;
Routes : TList<TCity>; // available roads to/from this place
LeftFor : integer; // where did the merchant went next; -1 if did not arrived or left, used to iterate all the paths
CameFrom: TCity; // nil initially
.....
End; // writing this draft from phone ( testing official StackOverflow Android app) would not write boilerplate with creating/free in internal objects - do it yourself
Type TPath = TArray<TCity>; // for your app you would add segments and total cost and whatever
Var World: TArray<TCity >; // fill cities and links yourself
AllPaths: TList<TPath>; // create yourself
Current: TList<TCity >; // create yourself
Procedure SaveResult;
Begin AllPaths.Add( Current.ToArray) end;
Function TryNextCity: boolean;
Var c1,c2: TCity; I : integer;
Begin
c1 := Current.Last; // where we are
While true do begin
Inc( c1.LeftFor) ;
If c1.LeftFor >= c1.Routes.Count // tried all ways?
Then Exit( false );
c2 := c1.Routes (. c1.LeftFor .);
if c2 = c1.CameFrom then continue;
if c2.LeftFor >= 0 then continue; // already were there
AddCity(c2);
Exit( True) ;
End;
End;
Procedure AddCity( const City: TCity) ;
Begin
Assert ( not Current.Contains( City) ) ;
If Current.Count = 0
then City.CameFrom := nil //starting point
else City.CameFrom := Current.Last;
City.LeftFor := -1;
Current.Add(City) ;
End;
Procedure Withdraw;
Begin
Assert ( Current.Count > 0);
With Current.Last do begin
CameFrom := nil;
LeftFor := -1;
End;
Current.Delete( Current.Count - 1) ;
End;
Procedure Recurs;
Var DeadEnd : boolean;
Begin
DeadEnd := true;
while TryNextCity() do begin
DeadEnd := false;
Recurs();
end;
if DeadEnd then SaveResult();
Withdraw ();
End;
Procedure RunBruteForce;
Var c: TCity ;
Begin
AllPaths.Clear;
For c in world do begin
Current.Clear;
AddCity( c );
Recurs();
End;
End;
PS. #MartynA looks like I cannot comment my answer now in Android. So my reply is: this questions as is now falls into a triangle between "do my homework", "write a textbook or at least an essay" and "throw a bunch of vague nice ideas, correct per se, but none of which would be detailed and complete enough to be called an answer".
I only started the answer to try new SO app, and only go on for it does not have options to delete the answer.

Problem with “in” operator in Delphi

Hi guys i have a wierd problem and i don't know where i am doing wrong...
I have the following code please look at the end of it that's where it fails i commented it...
var
IDH:PImageDosHeader;
INH:PImageNtHeaders;
ISH:PImageSectionHeader;
buf:Pointer;
FS:TFileStream;
ep,tmp1,tmp2:DWORD;
i:Word;
begin
if OpenDialog1.Execute then
begin
FS:=TFileStream.Create(OpenDialog1.FileName,fmOpenRead or fmShareDenyNone);
GetMem(buf,FS.size);
FS.Read(buf^,FS.Size);
FS.Free;
IDH:=PImageDosHeader(buf);
INH:=PImageNtHeaders(DWORD(buf) + DWORD(IDH^._lfanew));
ep:=INH^.OptionalHeader.AddressOfEntryPoint;
for i:=0 to INH^.FileHeader.NumberOfSections - 1 do
begin
ISH:=PimageSectionHeader(DWORD(INH) + sizeof(TImageNtHeaders) + i * sizeof(TImageSectionHeader));
tmp1:=ISH^.VirtualAddress;
tmp2:=ISH^.VirtualAddress + ISH^.Misc.VirtualSize;
ShowMessageFmt('%d -> %d .. %d',[ep,tmp1,tmp2]);
if ep in [tmp1..tmp2] then ShowMessage('Got it'); //This fails even if ep is in the defined interval. Why?
end;
end;
end;
Of course i can replace that line with
if (ep>=tmp1) and (ep<=tmp2)
but i want to know what i am doing wrong.
A set is a collection of values of the same type. This type must be ordinal, and a variable of this type must have at most 256 possible values. (Official documentation) Hence, a set cannot contain integers, since there are more than 256 possible integers.
You could use the InRange function:
if InRange(ep, tmp1, tmp2) then
(uses Math).

OpenOffice Calc automation how alter a chart label of a scatter diagram

Hello could you please help me with the following. I have created a scattered chart and draw a chart from data of a column. The used data is not just after the cell which determines the label:
Column O:
Pwm1 <-- This is the cell I want to see as the label
27114 <-- not used data for graph
27055 <-- etc
27092
27070 <-- data for graph starts here
27105
27024
27092 <-- data for graph ends here
I would like the LABEL cell to appear as the Y column label name (Is now 'Column O'), but how?
This as far as I got (code is Delphi but if someone could help me with a basic example that's ok too):
(* Turn the symbol of the data points off *)
oChart.Diagram.SymbolType := _chartChartSymbolTypeNONE;
oDataSeries := oChart.getUsedData;
oDataSequences := oDataSeries.getDataSequences;
ShowMessage(oDataSequences[1].Label.SourceRangeRepresentation);
SourceRangeRepresentation returns the current label, but how to change?
Thanks Ad
This did it:
(*
creat new DataSequence from range representaion
that provides real data and its role in the series
oDataProvider: com.sun.star.chart2.data.XDataProvider
sRangeRepresentation: range address e.g. Sheet1.A1:B2
sRole: role is defined in com.sun.star.chart2.data.DataSequenceRole
*)
Function CreateDataSequence( oDataProvider : Variant; sRangeRepresentation : String; sRole :String ) : Variant;
Var
oDataSequence : Variant;
Begin
(* create .chart2.data.DataSequence from range representation *)
oDataSequence := oDataProvider.createDataSequenceByRangeRepresentation(sRangeRepresentation);
If NOT VarIsEmpty(oDataSequence) Then
oDataSequence.Role := sRole;
Result := oDataSequence;
End;
oNewLabel := CreateDataSequence(oChart.getDataProvider, '$Sheet1.$O$7', 'label');
oDataSequences[1].setLabel(oNewLabel);

PREDICATES
nondeterm male(symbol)
nondeterm female(symbol)
nondeterm wife(symbol,symbol)
nondeterm mother(symbol,symbol)
nondeterm father(symbol,symbol)
nondeterm brother(symbol,symbol)
nondeterm sister(symbol,symbol)
nondeterm sonInLaw(symbol,symbol)
nondeterm brotherInLaw(symbol,symbol)
nondeterm uncle(symbol,symbol)
nondeterm sibling(symbol,symbol)
nondeterm grandson(symbol,symbol)
nondeterm grandfather(symbol,symbol)
Clauses
male(mark).
male(ahmed).
male(zeeshan).
male(summer).
female(sara).
female(sana).
wife(sara,mark).
wife(sana,ahmed).
mother(X,Y):-female(X),father(Z,Y),wife(X,Z),X<>Y.
mother(sara,sana).
father(X,Y):-male(X),mother(Z,Y),wife(Z,X),X<>Y.
brother(X,Y):-male(X),father(Z,X),father(Z,Y),X<>Y.
sister(X,Y):-female(X),father(Z,X),father(Z,Y),X<>Y.
sonInLaw(X,Y):-male(X),father(Y,Z),wife(Z,X) ; male(X),mother(Y,Z),wife(Z,X),X<>Y.
brotherInLaw(X,Y):-male(X),sister(Z,X),wife(Z,Y).
sibling(X,Y):-brother(X,Y);sister(X,Y),X<>Y.
uncle(X,Y):- sibling(X,Z),father(Z,Y),X<>Y.
grandfather(X,Y):- father(X,Z), father(Z,Y);father(X,Z), mother(Z,Y),X<>Y.
grandson(X,Y):- father(Z,X), father(Y,Z);father(Z,X), mother(Y,Z),X<>Y.
Goal
uncle(mark,sana).
My Prolog is giving me Error 1010.

This should work
In WIP7 this works
class predicates
male:(symbol) procedure (x).
female:(symbol) procedure (x).
wife:(symbol,symbol) procedure (x,y).
mother:(symbol,symbol) procedure (x,y).
father:(symbol,symbol) procedure (x,y).
brother:(symbol,symbol) procedure (x,y).
sister:(symbol,symbol) procedure (x,y).
sonInLaw:(symbol,symbol) procedure (x,y).
brotherInLaw:(symbol,symbol) procedure (x,y).
uncle:(symbol,symbol) procedure (x,y).
sibling:(symbol,symbol) procedure (x,y).
grandson:(symbol,symbol) procedure (x,y).
grandfather:(symbol,symbol) procedure (x,y).
clauses
male(mark).
male(ahmed).
male(zeeshan).
male(summer).
female(sara).
female(sana).
wife(sara,mark).
wife(sana,ahmed).
mother(X,Y):-female(X),father(Z,Y),wife(X,Z),X<>Y.
mother(sara,sana).
father(X,Y):-male(X),mother(Z,Y),wife(Z,X),X<>Y.
brother(X,Y):-male(X),father(Z,X),father(Z,Y),X<>Y.
sister(X,Y):-female(X),father(Z,X),father(Z,Y),X<>Y.
sonInLaw(X,Y):-male(X),father(Y,Z),wife(Z,X);male(X),mother(Y,Z), wife(Z,X),X<>Y.
brotherInLaw(X,Y):-male(X),sister(Z,X),wife(Z,Y).
sibling(X,Y):-brother(X,Y);sister(X,Y),X<>Y.
uncle(X,Y):- sibling(X,Z),father(Z,Y),X<>Y.
grandfather(X,Y):-father(X,Z),father(Z,Y);father(X,Z),mother(Z,Y), X<>Y.
grandson(X,Y):- father(Z,X), father(Y,Z);father(Z,X), mother(Y,Z),X<>Y.
clauses
run():-
console::init(),
uncle(mark,sana),
programControl::sleep(1000).
I think that with VIP 5.1 you can put
check_determ

Related

Need to convert following FORTRAN code to C++

Im a very poor programmer, and i was given a program to supposedly help me on my aerodynamic hw. but its in fortran, and im trying to use MATLAB to run this program. any help on converting it to a language matlab understands? (preferabbly c++)
program joukow
c
c computes joukowski airfoil and finds pressure coefficient
c currently set up for symmetric airfoil with sharp trailing edge
c and chord length equal to one.
c profile is written onto prof.dat and cp onto cp.dat
c implicit real*8(a-h,o-z)
complex z,zeta,cw
dimension uz(100),vz(100),xi(100),eta(100),cp(100)
dimension xout(100),yout(100)
open(unit=8,file='prof.dat',status='unknown')
open(unit=9,file='cp.dat',status='unknown')
b=1.d0
write(6,98)
format(2x,'input the radius of the a-circle in z plane')
read(5,99)a
format(f10.0)
xl=2.*a-1.+1./(2.*a-1.)
c xl=a+1./a
c chord=2.*xl
chord=2.+xl
del=a-b
c del =0.1d0
do 50 i=1,100
ri=i
theta=6.2832d0*ri/101.d0
x=-del+a*cos(theta)
y=a*sin(theta)
z=cmplx(x,y)
zeta=z+b**2/z
c
c xi and eta are coordinates of points on airfoil
c
xi(i)=real(zeta)
eta(i)=aimag(zeta)
cw=(1.-a**2/(z+del)**2)/(1.-b**2/z**2)
c
c uz and vz are velocity components on the airfoil assuming the free-stream
c speed is one.
c
uz(i)=real(cw)
vz(i)=-aimag(cw)
c
c xout and yout are airfoil coordinates where the leading edge is at (0,0)
c and the chordlength is one.
c
xout(i)=(xl+xi(i))/chord
yout(i)=eta(i)/chord
write(8,100)xout(i),yout(i)
format(2x,2f10.4)
continue
c
c now calculate the pressure coefficient cp
c
write(6,200)
format(2x,'pressure coefficients')
do 70 i=1,50
cp(i)=1.-(uz(i)**2+vz(i)**2)
write(9,100)xout(i),cp(i)
continue
stop
end
Matlab understands Fortran just fine -- check the documentation. And if that doesn't satisfy you, most of the lines in the program which do any computation could be typed into the Matlab console with very little modification. If you are a poor programmer, I suggest that you spend your time modifying the program into Matlab rather than into C++. I'll write more later if you don't get any better help than I have time for right now.
EDIT: first off, some information on using Fortran source files from Matlab. If you really don't want to (or can't or have performance reasons for not doing so) rewrite the Fortran into Matlab then turn it into a MEX file. Using f2c (or anything else, including your own time and effort) to first translate the Fortran into C or C++ seems pointless to me.
If you don't like that idea, here are some ideas on turning Fortran into Matlab.
First, all lines beginning with C or c are comments so you don't need to translate them. Start with your code:
complex z,zeta,cw
dimension uz(100),vz(100),xi(100),eta(100),cp(100)
dimension xout(100),yout(100)
These lines declare a number of variables. You don't have to declare variables before you use them in Matlab but, there are sometimes good reasons to do so. You don't have to in Fortran either, though this is universally considered a bad idea these days. You could 'declare' these variables in Matlab with statements such as:
uz = zeros(100,1);
vz = zeros(100,1);
By declaring these in advance in your Matlab you allocate memory for them once, and avoid some performance-reducing problems.
The next 2 lines:
open(unit=8,file='prof.dat',status='unknown')
open(unit=9,file='cp.dat',status='unknown')
open a couple of files for output. They are used later in write statements - forget them, write Matlab statements such as save xout instead.
The next line is Fortran but identical in Matlab:
b=1.d0
The next lines get a value for the radius from the console:
write(6,98)
format(2x,'input the radius of the a-circle in z plane')
read(5,99)a
format(f10.0)
again, I suggest you forget these, just use the Matlab console to set the value of a. More Fortran that doesn't need to be translated (though I suggest you either drop the decimal points without following 0s or put a space between them and the subsequent * -- .* is a specific operator in Matlab):
xl=2.*a-1.+1./(2.*a-1.)
chord=2.+xl
del=a-b
A Fortran do loop is the same as a Matlab for loop. Rewrite:
do 50 i=1,100
as
for i = 1:100
As one of the other respondents has noted it's not clear where the matching end statement goes, you'll have to figure that out. Note that I'm just offering a line-by-line translation of Fortran into Matlab. It's not well-written Fortran, and I'm not offering well-written Matlab, I'll leave that to you.
This lot doesn't need to be translated:
ri=i
theta=6.2832d0*ri/101.d0
x=-del+a*cos(theta)
y=a*sin(theta)
cmplx is a Fortran function which returns a complex number which has real part x and imaginary part y:
z=cmplx(x,y)
In Matlab this would be z = x + y * i. Fortran uses ** for exponentiation, Matlab uses ^
zeta=z+b**2/z
and so on and so on.
Hope that helps.
I used f2matlab and a little touching up afterward. Here is the cleaned up and compilable fortran90 code:
program joukow
!
! computes joukowski airfoil and finds pressure coefficient
! currently set up for symmetric airfoil with sharp trailing edge
! and chord length equal to one.
! profile is written onto prof.dat and cp onto cp.dat
! implicit real*8(a-h,o-z)
complex z,zeta,cw
dimension uz(100),vz(100),xi(100),eta(100),cp(100)
dimension xout(100),yout(100)
open(unit=8,file='prof.dat',status='unknown')
open(unit=9,file='cp.dat',status='unknown')
b=1.d0
write(6,98)
98 format(2x,'input the radius of the a-circle in z plane')
read(5,99)a
99 format(f10.0)
xl=2.*a-1.+1./(2.*a-1.)
! xl=a+1./a
! chord=2.*xl
chord=2.+xl
del=a-b
! del =0.1d0
do i=1,100
ri=i
theta=6.2832d0*ri/101.d0
x=-del+a*cos(theta)
y=a*sin(theta)
z=cmplx(x,y)
zeta=z+b**2/z
!
! xi and eta are coordinates of points on airfoil
!
xi(i)=real(zeta)
eta(i)=aimag(zeta)
cw=(1.-a**2/(z+del)**2)/(1.-b**2/z**2)
!
! uz and vz are velocity components on the airfoil assuming the free-stream
! speed is one.
!
uz(i)=real(cw)
vz(i)=-aimag(cw)
!
! xout and yout are airfoil coordinates where the leading edge is at (0,0)
! and the chordlength is one.
!
xout(i)=(xl+xi(i))/chord
yout(i)=eta(i)/chord
write(8,100)xout(i),yout(i)
100 format(2x,2f10.4)
end do
!
! now calculate the pressure coefficient cp
!
write(6,200)
200 format(2x,'pressure coefficients')
do i=1,50
cp(i)=1.-(uz(i)**2+vz(i)**2)
write(9,100) xout(i),cp(i)
end do
stop
end program joukow
Here is the resulting matlab code:
function hw1(varargin)
%
% computes joukowski airfoil and finds pressure coefficient
% currently set up for symmetric airfoil with sharp trailing edge
% and chord length equal to one.
% profile is written onto prof.dat and cp onto cp.dat
% implicit real*8(a-h,o-z)
format_99=['%10.0f'];
format_100=[repmat(' ',1,2),repmat('%10.4f',1,2),'n'];
format_200=[repmat(' ',1,2),'pressure coefficients n'];
fid_8=fopen('prof.dat','w+');
fid_9=fopen('cp.dat','w+');
b=1.0d0;
a=input('input the radius of the a-circle in z plane');
xl=2..*a-1.+1../(2..*a-1.);
% xl=a+1./a
% chord=2.*xl
chord=2.+xl;
del=a-b;
% del =0.1d0
for i=1:100;
ri=i;
theta=6.2832d0.*ri./101.0d0;
x=-del+a.*cos(theta);
y=a.*sin(theta);
z=complex(x,y);
zeta=z+b.^2./z;
%
% xi and eta are coordinates of points on airfoil
%
xi(i)=real(zeta);
eta(i)=imag(zeta);
cw=(1.-a.^2./(z+del).^2)./(1.-b.^2./z.^2);
%
% uz and vz are velocity components on the airfoil assuming the free-stream
% speed is one.
%
uz(i)=real(cw);
vz(i)=-imag(cw);
%
% xout and yout are airfoil coordinates where the leading edge is at (0,0)
% and the chordlength is one.
%
xout(i)=(xl+xi(i))./chord;
yout(i)=eta(i)./chord;
fprintf(fid_8,format_100,xout(i),yout(i));
end; i=100+1;
%
% now calculate the pressure coefficient cp
%
fprintf(1,format_200);
for i=1:50;
cp(i)=1.-(uz(i).^2+vz(i).^2);
fprintf(fid_9,format_100, xout(i),cp(i));
end; i=50+1;
end %program joukow
They both give the same results for me. I didn't check the algorithm for correctness, though, just converted the code.
I don't know how well it's still supported - - but the easiest way used to be f2c which translates fortran directly into c code.

Maple isnt executing function but prints function term

Im using maple Im in worksheetmode I tried using Maple Input and 2D Input and I want to transpose my Matrix A:
A := `<|>`(`<,>`(1, .5, -2), `<,>`(.5, 9/4+b, 5+3*b), `<,>`(-2, 5+3*b, 18+9*b+4*a));
B:= Transpose(A);
When I exectute the sheet I dont get the translated values, there are the same as the input. So my matrix looks like the same as my input matrix plus the function term.
You can see a picture in the following link: Why arent the functions executed?
Meanwhile B:=A^+ is doing it the right way and I get a transposed Matrix. But also other functions only return the function body instead the needed values...
If you are using 2D Input mode (the default) then the extra space you've got between Transpose and the bracketed (B) is interpreted as multiplcation. Get rid of such a space.
Also, either load the package at the start of your document like,
with(LinearAlgebra):
before calling the Transpose command from that package, or call it with it's full name like,
LinearAlgebra:-Transpose(B);

How to prevent loops in cubic Bezier curves

I have a calculation that produces a cubic 2D Bezier curve. In this situation, the endpoints are fixed and my program calculates the internal control points. Most of the time these curves produce simple blends between two nearby shapes. But sometimes the geometry is such that drawing the curve would produce a loop, which would never look good in this application. In such situations, I am willing to modify the control points to prevent the loop. But to do this, I need to detect whether the given cubic Bezier curve will loop when drawn.
I could of course simply sample the curve at many points and look for a loop, but I'd rather find an algebraic solution based on the 8 variables (x and y values for each of the 4 points). Ideally, that solution will tell me not just if there's a loop, but how "big" the loop is in some sense. But even having a binary yes/no answer would be a big help.
Does anyone know of an algorithm that can determine if a given cubic 2D Bezier curve will produce a loop when drawn?
certainly: you can look at its canonical form to see whether the four points result in the curve "ending" in a region where loops must necessarily exist.
The original theory for this is outlined in the 1989 paper "A Geometric Characterization of Parametric Cubic curves"
First the code, some explanation later. The process is somewhat time-consuming, so the code was slighty optimized. Now it resembles a sharp selection, where very few candidates will pass all tests.
type
myType=Integer; {remember to change here to your own type,
an integers are good for an educational purpose}
point_2d=record xx,yy :myType end;
vector_2d=record vx,vy :myType end;
function bezier_has_a_loop(p0,p1,p2,p3:point_2d):boolean;
{-------------------------}
function f_vec_from_2_pts(pa,pb:point_2d):vector_2d;
begin
with Result do begin
vx:=pb.xx - pa.xx;
vy:=pb.yy - pa.yy end end;
{-------------------------}
function f_cross_prod(va,vb : vector_2d):myType;
begin
Result := va.vx*vb.vy - va.vy*vb.vx end;
{-------------------------}
function f_mult(m:myType; v:vector_2d):vector_2d;
begin
with Result do begin
vx := m*v.vx;
vy := m*v.vy end end;
{-------------------------}
function f_sum(va,vb : vector_2d):vector_2d;
begin
with Result do begin
vx := va.vx+vb.vx;
vy := va.vy+vb.vy end end;
{-------------------------}
function f_rotate(v, rotor : vector_2d):vector_2d;
var
m_sin,m_cos:myType; {only for a readability purpose}
begin
m_cos:=rotor.vx {
/sqrt(sqr(rotor.xx)+sqr(rotor.yy)) - unnecessary };
m_sin:=rotor.vy {
/sqrt(sqr(rotor.xx)+sqr(rotor.yy)) - unnecessary };
with Result do begin
vx := -v.vx * m_cos - v.vy *m_sin;
vy := v.vx * m_sin - v.vy *m_cos end end;
{-------------------------}
var
a,b,c, c1,c2,c3 :vector_2d;
ab,ac,bc:myType;
bb,s1,s2,delta,shift,t_1_2 : Double;
begin
a:=f_vec_from_2_pts(p0,p1);
b:=f_vec_from_2_pts(p1,p2);
c:=f_vec_from_2_pts(p2,p3);
ab:=f_cross_prod(a,b); {on the planar,
myType for a cross product is just fine}}
ac:=f_cross_prod(a,c);
bc:=f_cross_prod(b,c);
{==1== No inflection point(s) or cusp allowed}
if ac*ac >= 4*ab*bc then begin Result:=False; exit end;
c3:= f_sum( f_sum(a,c) , f_mult( -2,b ) );
if c3.vy<>0 then begin {Is the bag's handle horizontal?}
a := f_rotate(a,c3);
b := f_rotate(b,c3);
c := f_rotate(c,c3);
c3:= f_sum ( f_sum(a,c) , f_mult(-2,b) );
{Now the handle is forced to be horizontal.}
end;
c1:= f_mult ( 3,a );
c2:= f_sum ( f_mult(3,b) , f_mult(-3,a) );
{ Following 4 restrictions comes from a single caveats for a roots:
0<= t1<t2<=1}
bb:= -c1.vy / c2.vy; { always c2.vy<>0 }
{==2== A central point (t1+t2)/2 outside the limits}
if (bb<0) or (bb>2) then begin Result:=False; exit end;
s1:= c1.vx/c3.vx; { always c3.vx<>0 }
s2:= c2.vx/c3.vx;
delta := -bb*(4*s2+3*bb)-4*s1;
{==3== delta is to big}
if delta>1 then begin Result:=False; exit end;
shift:=sqrt(delta); { always delta>0 }
t_1_2:=bb-shift; {for readability purpose only,
one can omit this and write below: if shift>bb }
{==4== t1 is to low }
if t_1_2<0 then begin Result:=False; exit end;
t_1_2:=bb+shift; { no /2 here,beacause of *2 below}
{==5== t2 is to high}
if t_1_2>2 then Result:=False
else Result:=True { TA DA! Thank you for your patience. }
end;
Now some theory.
Let take into account 4 points P0, P1, P2, P3. These points define (almost always) a cubic Bézier curve.
Let establish the point H1 such as the vector P1_H1 is half of the vector P0_P1.
Let establish the point H2 such as the vector P2_H2 is half of the vector P3_P2.
At the end, let create the vetor h = H1_H2. (Personally I call this vector "the handle of the bag", guess why.)
Bezier curve and its handle
No surprise here, when you start an isotropic scaling or a roation of P0, P1, P2, P3, then vector h will transform accordingly.
Maybe for someone this will be a surprise, the vector h = [_h_x,_h_y] is proportional to the vector [c3x,c3y] created from the highest coefficients of the algebraic form of the cubic Bézier curve. The proportionality coefficient is (-1/2).
(In fact, when the points H1=H2 coincide, the h vector vanishes, c3x=c3y=0, thus the cubic Bézier curve reduces at least into the quadratic Bézier curve, created from P0,H1,P3 points.)
And now the clue: The right rotation can always turn the vector h horizontally (or verically), and this rotation will reduce c3y ( or c3x ) into null, however preserving the loop. In turn, one can reduce the stated problem into a trivial root-finding of a quadratic equation. (I suppose this is a decisive hint to find a solution.)
To measure the loop, I suggest take into account the variable delta from the code above.
0 < delta <= 1
When delta -> 0, the loop vanishes.
When delta -> 1, the loop becomes really pompous.
I'm not quite happy with this proposal, but it is still better than nothing.

Extracting Ring/Sector area from array representing an image

I am trying to extract features from an array representation of an image in MATLAB.
The features have a shape of a circle (ring) and a sector. This is shown in the image below. I have spent quite some time looking for a built-in function which does this. I have managed to do the ring extraction using an ugly looking loop but no idea where to start on the sector part. Any ideas how to implement this or even better a built-in function in MATLAB would be very helpful.
That's pretty easy, with no for loops needed, see for example in case your image is im:
[x y]=meshgrid(1:size(im,1));
f =#(x0,y0,r_max,r_min,theta1,theta2) ...
(x-x0).^2+(y-y0).^2<=r_max^2 & ...
(x-x0).^2+(y-y0).^2>=r_min^2 & ...
atan2(y-y0,x-x0)>=theta1 & ...
atan2(y-y0,x-x0)<=theta2;
f is a one liner anonymous function that accepts all needed parameters and gives a mask of the sector needed. For a ring you can set theta to be -pi to pi, or just delete the atan part from f. For example
r_max=40;
r_min=10;
x0=round(size(im,1)/2); %image center
y0=round(size(im,1)/2); %image center
theta1=deg2rad(10);
theta2=deg2rad(70);
imagesc(f(x0,y0,r_max,r_min,theta1,theta2))
set(gca,'YDir','normal')
axis square

Ada: accessing a record variable

Hi I am making a program to calculate vector components. Since 2D vectors have a horizontal and a vertical component in the Cartesian space, I have decided to use the record construction.
The program first calculates the basis vector and this is what is shown below. The horizontal, vertical components as well as an angle is asked as input. The angle refers to the anticlockwise positive angle from the default Cartesian coordinate system to another rotated Cartesian coordinate system from the original one.
In the file Projections.adb you will see the calculation:
D.Horz := A * Cos (C);
where A is the horizontal component of the original Cartesian coordinate system and C is the angle that denotes the rotation between the new Cartesian coordinate system and the old system.
In the main program Get_projections.adb, the calling procedure is
Vector_basis_r (Component_Horz, Component_Vert, theta, Basis_r);
Ada complains when I issue the command:
Ada.Long_Float_Text_IO.Put (Item => Basis_r.Horz, Fore => 3, Aft => 3, Exp => 0);
when I want to retrieve the horizontal component of the basis vector.
The complaint is:
*invalid prefix in selected component "Basis_r"*.
Any suggestions what I am doing wrong?
The necessary files are down here:
The main file is Get_Projections.adb:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO;
with Ada.Float_Text_IO;
with Projections; Use Projections;
with Ada.Numerics.Long_Elementary_Functions;
use Ada.Numerics.Long_Elementary_Functions;
procedure Get_Projections is
Component_Horz, Component_Vert, theta : Long_Float;
Basis_r : Rectangular;
begin
Ada.Text_IO.Put("Enter the horizontal component ");
Ada.Long_Float_Text_IO.Get (Item => Component_Horz);
Ada.Text_IO.New_Line (1);
Ada.Text_IO.Put("Enter the vertical component ");
Ada.Long_Float_Text_IO.Get (Item => Component_Vert);
Ada.Text_IO.New_Line (1);
Ada.Text_IO.Put("Enter the angle ");
Ada.Long_Float_Text_IO.Get (Item => theta);
Vector_basis_r (Component_Horz, Component_Vert, theta, Basis_r);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("rx = ");
Ada.Long_Float_Text_IO.Put (Item => Basis_r.Horz, Fore => 3, Aft => 3, Exp => 0);
end Get_Projections;
and the accompanying packages are the specification Projections.ads:
package Projections is
type Rectangular is private;
procedure Vector_basis_r (A, B, C : in Long_Float; D : out Rectangular);
private
type Rectangular is
record
Horz, Vert: Long_Float;
end record;
end Projections;
and the package body Projections.adb:
with Ada.Numerics.Long_Elementary_Functions;
use Ada.Numerics.Long_Elementary_Functions;
package body Projections is
procedure Vector_basis_r (A, B, C : in Long_Float; D : out Rectangular) is
begin
D.Horz := A * Cos (C);
D.Vert := B * Sin (c);
end Vector_basis_r;
end Projections;
Thanks a lot...
Rectangular is a private type, therefore other packages do not have access to its components, Horz (or Vert) in this case. The fields of the Rectangular type can only be accessed by Projections' package body, or in the private part or bodies of any child packages of Projections.
Either place the Rectangular type declaration in the public part of package Projections, or provide Get/Set accessors to interact with the record's components.
I would put a put procedure in the projections package:
package Projections is
type Rectangular is private;
procedure Vector_basis_r (A, B, C : in Long_Float; D : out Rectangular);
procedure put (r : in Rectangular);
private
type Rectangular is
record
Horz, Vert: Long_Float;
end record;
end Projections;
Then your privates stay hidden and you can print them with impunity.
put (basis_r);
and have as the body of the put:
procedure put (r : in Rectangular) is
begin
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("rx = ");
Ada.Long_Float_Text_IO.Put (Item => r.Horz, Fore => 3, Aft => 3, Exp => 0);
end put;

Понравилась статья? Поделить с друзьями:
  • Protoc gen go error inconsistent package import paths
  • Protobuf parse error required fields missing cannot determine missing fields for lite message
  • Protherm ошибка f85 разблокировать котел
  • Protherm ошибка f62 pantera
  • Protherm ошибка f61