How to write more than 7 columns into a csv file by IDL? - idl-programming-language

I have been tried to write 8 columns in a CSV file by using IDL, but seems the maximum columns that I can wrote is 7?
IDL> write_csv,ffout,date_time,tmin_tmax,precp,wind,rh,sun_hrs,glb_rad,net_rad
WRITE_CSV: Incorrect number of arguments

The documentation for WRITE_CSV indicates you can write up to 8 columns, which works for me:
x = findgen(10)
write_csv, 'test.csv', x, x, x, x, x, x, x, x
In any case, if you need to write more columns, it is easy enough to use PRINTF to output each line:
for i = 0L, n_lines - 1L do begin
printf, lun, a[i], b[i], c[i], d[i], e[i], f[i], g[i], h[i], $
format='(%"%f, %f, %f, %f, %f, %f, %f, %f")'
endfor
You can change the format codes as appropriate, or use the Fortran-style format codes as you prefer.

As long as your input arrays are one-dimensional you can just concatenate them (and do an additional transpose):
a = FINDGEN(3)
b = TRANSPOSE([ [a], [a], [a], [a], [a], [a], [a], [a], [a], [a] ])
WRITE_CSV, 'test.csv', b

Related

Outputting variable name and value in a loop

I want to loop over a list of variables nad output the variable name and value. E.g., say I have x=1 and y=2, then I want an output
x is 1
y is 2
I suspect I need to use Symbols for this. Here is my approach, but it isn't working:
function t(x,y)
for i in [x,y]
println("$(Symbol(i)) is $(eval(i))") # outputs "1 is 1" and "2 is 2"
end
end
t(1, 2)
Is there a way to achieve this? I guess a Dictionary would work, but would be interested to see if Symbols can also be used here.
One option is to use a NamedTuple:
julia> x = 1; y = 2
2
julia> vals = (; x, y)
(x = 1, y = 2)
julia> for (n, v) ∈ pairs(vals)
println("$n is $v")
end
x is 1
y is 2
Note the semicolon in (; x, y), which turns the x and y into kwargs so that the whole expression becomes shorthand for (x = x, y = y).
I will also add that your question looks like like you are trying to dynamically work with variable names in global scope, which is generally discouraged and an indication that you probably should be considering a datastructure that holds values alongside labels, such as the dictionary proposed in the other answer or a NamedTuple. You can google around if you want to read more on this, here's a related SO question:
Is it a good idea to dynamically create variables?
You can do this by passing the variable names:
x = 1
y = 2
function t(a, b)
for i in [a, b]
println("$(i) is $(eval(i))")
end
end
t(:x, :y)
x is 1
y is 2
At the start of the function, there's no record of the "x"-ness of x, or the "y"-ness of y. The function only sees 1 and 2. It's a bit confusing that you also called your two local variables x and y, I renamed them to show what's happening more clearly.
A solution with dictionaries would be nicer:
dict = Dict()
dict[:x] = 1
dict[:y] = 2
function t(d)
for k in keys(d)
println("$(k) is $(d[k])")
end
end
t(dict)
y is 2
x is 1
If you rather want to see programmatically what variables are present you could use varinfo or names:
julia> x=5; y=7;
julia> varinfo()
name size summary
–––––––––––––––– ––––––––––– –––––––
Base Module
Core Module
InteractiveUtils 316.128 KiB Module
Main Module
ans 8 bytes Int64
x 8 bytes Int64
y 8 bytes Int64
julia> names(Main)
7-element Vector{Symbol}:
:Base
:Core
:InteractiveUtils
:Main
:ans
:x
With any given name it's value can be obtained via getfield:
julia> getfield(Main, :x)
5
If you are rather inside a function than use #locals macro:
julia> function f(a)
b=5
c=8
#show Base.#locals
end;
julia> f(1)
#= REPL[13]:4 =# Base.#locals() = Dict{Symbol, Any}(:a => 1, :b => 5, :c => 8)
Dict{Symbol, Any} with 3 entries:
:a => 1
:b => 5
:c => 8

how to generate instruction for llvm vector comparison

In LLVM, we can create a comparison instruction for scalar instruction easily. For example, if we have:
%a = fsub double %1, %2
%b = fadd double %3, %4
%c = fcmp one double %a, %b
where instruction %c can be generated by:
c = new FCmpInst(insertAt, FCmpInst::FCMP_ONE, %a, %b, instName)
Can we do the similar comparison conveniently for vector instructions? For example, if %a and %b are the following respectively:
%a = fsub <2 x double>, %5, %6; %5 and %6 are in vector type
%b = fadd <2 x double>, %7, %8
Can we have the similar comparison as the scalar version to check the equivalence for %a and %b?
I actually tried the same instruction as the above, but it produces the following error "void llvm::BranchInst::AssertOK(): Assertion `getCondition()->getType()->isIntegerTy(1) && "May only branch on boolean predicates!"' failed." when I load the pass.
fcmp of a vector returns a vector of boolean results. You'll need to change the way you reduce that into a boolean predicate for branching purposes.
For your case, you'll want to compare the result of the fcmp with zero.
I think http://lists.llvm.org/pipermail/llvm-dev/2012-September/053046.html may contain the answer to your question.
It can be summarized to
sign extend your boolean vector to an integer vector
bitcast the integer vector to a integer of same size
make the comparison on the integer
%a = fsub <2 x double>, %5, %6;
%b = fadd <2 x double>, %7, %8
%c = fcmp one <2 x i1>, %a, %b
%d = sext <2 x i1> %c to <2 x i64>
%e = bitcast <2 x i64> %d to i128
%f = icmp ne %e, 0
br i1 %f, label %true1, label %false2
The sign extension is used so that backends of standard vector instruction sets map this instruction without switching vector size.

Decompression of a list in prolog

I need to decompress a list in prolog , like in the example below :
decode([[a,1],[b,2],[c,1],[d,3]],L).
L = [a, b, b, c, d, d, d] ;
I made this code :
divide(L,X,Y):-length(X,1),append(X,Y,L).
divide2(L,X,Y):-divide(L,[X|_],[Y|_]).
makelist(_,N,[]):- N =< 0 .
makelist(X,Y,[X|Result]):-Y1 is Y-1,makelist(X,Y1,Result).
makelist2(L,L2):-divide2(L,X,Y),makelist(X,Y,L2).
decode([],[]).
decode([H|T],L):-makelist2(H,H2),append(H2,L,L2),decode(T,L2).
and when i call
makelist2([a,3],L2).
L2 = [a,a,a].
but when i call
decode([[a,3],[b,1],[c,4]],L)
runs continuously. What am i doing wrong ?
Another variation of the theme, using a slightly modified version of Boris' repeat/3 predicate:
% True when L is a list with N repeats of X
repeat([X, N], L) :-
length(L, N),
maplist(=(X), L).
decode(Encoded, Decoded) :-
maplist(repeat, Encoded, Expanded),
flatten(Expanded, Decoded).
If Encode = [[a,1],[b,2],[c,1],[d,3]], then in the above decode/2, the maplist/3 call will yield Expanded = [[a],[b,b],[c],[d,d,d]], and then the flatten/2 call results in Decoded = [a,b,b,c,d,d,d].
In SWI Prolog, instead of flatten/2, you can use append/2 since you only need a "flattening" at one level.
EDIT: Adding a "bidirectional" version, using a little CLPFD:
rle([], []).
rle([X], [[1,X]]).
rle([X,Y|T], [[1,X]|R]) :-
X \== Y, % use dif(X, Y) here, if available
rle([Y|T], R).
rle([X,X|T], [[N,X]|R]) :-
N #= N1 + 1,
rle([X|T], [[N1,X]|R]).
This will yield:
| ?- rle([a,a,a,b,b], L).
L = [[3,a],[2,b]] ? ;
(1 ms) no
| ?- rle(L, [[3,a],[2,b]]).
L = [a,a,a,b,b] ? ;
no
| ?- rle([a,a,a,Y,Y,Z], [X, [N,b],[M,c]]).
M = 1
N = 2
X = [3,a]
Y = b
Z = c ? a
no
| ?- rle([A,B,C], D).
D = [[1,A],[1,B],[1,C]] ? ;
C = B
D = [[1,A],[2,B]] ? ;
B = A
D = [[2,A],[1,C]] ? ;
B = A
C = A
D = [[3,A]] ? ;
(2 ms) no
| ?- rle(A, [B,C]).
A = [D,E]
B = [1,D]
C = [1,E] ? ;
A = [D,E,E]
B = [1,D]
C = [2,E] ? ;
A = [D,E,E,E]
B = [1,D]
C = [3,E] ? ;
...
| ?- rle(A, B).
A = []
B = [] ? ;
A = [C]
B = [[1,C]] ? ;
A = [C,D]
B = [[1,C],[1,D]] ? ;
...
As #mat suggests in his comment, in Prolog implementations that have dif/2, then dif(X,Y) is preferable to X \== Y above.
The problem is in the order of your append and decode in the last clause of decode. Try tracing it, or even better, trace it "by hand" to see what happens.
Another approach: see this answer. So, with repeat/3 defined as:
% True when L is a list with N repeats of X
repeat(X, N, L) :-
length(L, N),
maplist(=(X), L).
You can write your decode/2 as:
decode([], []).
decode([[X,N]|XNs], Decoded) :-
decode(XNs, Decoded_rest),
repeat(X, N, L),
append(L, Decoded_rest, Decoded).
But this is a slightly roundabout way to do it. You could define a difference-list version of repeat/3, called say repeat/4:
repeat(X, N, Reps, Reps_back) :-
( succ(N0, N)
-> Reps = [X|Reps0],
repeat(X, N0, Reps0, Reps_back)
; Reps = Reps_back
).
And then you can use a difference-list version of decode/2, decode_1/3
decode(Encoded, Decoded) :-
decode_1(Encoded, Decoded, []).
decode_1([], Decoded, Decoded).
decode_1([[X,N]|XNs], Decoded, Decoded_back) :-
repeat(X, N, Decoded, Decoded_rest),
decode_1(XNs, Decoded_rest, Decoded_back).
?- decode([[a,1],[b,2],[c,1],[d,3]],L).
L = [a, b, b, c, d, d, d].
?- decode([[a,3],[b,1],[c,0],[d,3]],L).
L = [a, a, a, b, d, d, d].
?- decode([[a,3]],L).
L = [a, a, a].
?- decode([],L).
L = [].
You can deal with both direction with this code :
:- use_module(library(lambda)).
% code from Pascal Bourguignon
packRuns([],[]).
packRuns([X],[[X]]).
packRuns([X|Rest],[XRun|Packed]):-
run(X,Rest,XRun,RRest),
packRuns(RRest,Packed).
run(Var,[],[Var],[]).
run(Var,[Var|LRest],[Var|VRest],RRest):-
run(Var,LRest,VRest,RRest).
run(Var,[Other|RRest],[Var],[Other|RRest]):-
dif(Var,Other).
%end code
pack_1(In, Out) :-
maplist(\X^Y^(X = [V|_],
Y = [V, N],
length(X, N),
maplist(=(V), X)),
In, Out).
decode(In, Out) :-
when((ground(In); ground(Out1)),pack_1(Out1, In)),
packRuns(Out, Out1).
Output :
?- decode([[a,1],[b,2],[c,1],[d,3]],L).
L = [a, b, b, c, d, d, d] .
?- decode(L, [a,b,b,c,d,d,d]).
L = [[a, 1], [b, 2], [c, 1], [d, 3]] .
a compact way:
decode(L,D) :- foldl(expand,L,[],D).
expand([S,N],L,E) :- findall(S,between(1,N,_),T), append(L,T,E).
findall/3 it's the 'old fashioned' Prolog list comprehension facility
decode is a poor name for your predicate: properly done, you predicate should be bi-directional — if you say
decode( [[a,1],[b,2],[c,3]] , L )
You should get
L = [a,b,b,c,c,c].
And if you say
decode( L , [a,b,b,c,c,c] ) .
You should get
L = [[a,1],[b,2],[c,3]].
So I'd use a different name, something like run_length_encoding/2. I might also not use a list to represent individual run lengths as [a,1] is this prolog term: .(a,.(1,[]). Just use a simple term with arity 2 — myself, I like using :/2 since it's defined as an infix operator, so you can simply say a:1.
Try this on for size:
run_length_encoding( [] , [] ) . % the run-length encoding of the empty list is the empty list.
run_length_encoding( [X|Xs] , [R|Rs] ) :- % the run-length encoding of a non-empty list is computed by
rle( Xs , X:1 , T , R ) , % - run-length encoding the prefix of the list
run_length_encoding( T , Rs ) % - and recursively run-length encoding the remainder
. % Easy!
rle( [] , C:N , [] , C:N ) . % - the run is complete when the list is exhausted.
rle( [X|Xs] , C:N , [X|Xs] , C:N ) :- % - the run is complete,
X \= C % - when we encounter a break
. %
rle( [X|Xs] , X:N , T , R ) :- % - the run continues if we haven't seen a break, so....
N1 is N+1 , % - increment the run length,
rle( Xs, X:N1, T, R ) % - and recurse down.
. % Easy!
In direct answer to the original question of, What am I doing wrong?...
When I ran the original code, any expected use case "ran indefinitely" without yielding a result.
Reading through the main predicate:
decode([],[]).
This says that [] is the result of decoding []. Sounds right.
decode([H|T],L) :- makelist2(H,H2), append(H2,L,L2), decode(T,L2).
This says that L is the result of decoding [H|T] if H2 is an expansion of H (which is what makelist2 does... perhaps - we'll go over that below), and H2 appended to this result gives another list L2 which is the decoded form of the original tail T. That doesn't sound correct. If I decode [H|T], I should (1) expand H, (2) decode T giving L2, then (3) append H to L2 giving L.
So the corrected second clause is:
decode([H|T], L) :- makelist2(H, H2), decode(T, L2), append(H2, L2, L).
Note the argument order of append/3 and that the call occurs after the decode of the tail. As Boris pointed out previously, the incorrect order of append and the recursive decode can cause the continuous running without any output as append with more uninstantiated arguments generates a large number of unneeded possibilities before decode can succeed.
But now the result is:
| ?- decode([[a,3]], L).
L = [a,a,a] ? ;
L = [a,a,a,a] ? ;
...
If you try out our other predicates by hand in the Prolog interpreter, you'll find that makelist2/2 has an issue:
It produces the correct result, but also a bunch of incorrect results. Let's have a look at makelist2/2. We can try this predicate by itself and see what happens:
| ?- makelist2([a,3], L).
L = [a,a,a] ? ;
L = [a,a,a,a] ? ;
...
There's an issue: makelist2/2 should only give the first solution, but it keeps going, giving incorrect solutions. Let's look closer at makelist/2:
makelist2(L,L2) :- divide2(L,X,Y), makelist(X,Y,L2).
It takes a list L of the form [A,N], divides it (via divide2/3) into X = A and Y = N, then calls an auxiliary, makelist(X, Y, L2).
makelist(_,N,[]):- N =< 0 .
makelist(X,Y,[X|Result]):-Y1 is Y-1,makelist(X,Y1,Result).
makelist/3 is supposed to generate a list (the third argument) by replicating the first argument the number of times given in the second argument. The second, recursive clause appears to be OK, but has one important flaw: it will succeed even if the value of Y is less than or equal to 0. Therefore, even though a correct solution is found, it keeps succeeding on incorrect solutions because the base case allows the count to be =< 0:
| ?- makelist(a,2,L).
L = [a,a] ? ;
L = [a,a,a] ? ;
We can fix makelist/2 as follows:
makelist(_,N,[]):- N =< 0 .
makelist(X,Y,[X|Result]):- Y > 0, Y1 is Y-1, makelist(X,Y1,Result).
Now the code will generate a correct result. We just needed to fix the second clause of decode/2, and the second clause of makelist/3.
| ?- decode([[a,3],[b,4]], L).
L = [a,a,a,b,b,b,b]
yes
The complete, original code with just these couple of corrections looks like this:
divide(L, X, Y) :- length(X, 1), append(X, Y, L).
divide2(L, X, Y) :- divide(L, [X|_], [Y|_]).
makelist(_, N, []) :- N =< 0 .
makelist(X, Y, [X|Result]) :- Y > 0, Y1 is Y-1, makelist(X,Y1,Result).
makelist2(L, L2) :- divide2(L, X, Y), makelist(X, Y, L2).
decode([], []).
decode([H|T], L) :- makelist2(H,H2), decode(T,L2), append(H2,L2,L).
Note some simple, direct improvements. The predicate, divide2(L, X, Y) takes a list L of two elements and yields each, individual element, X and Y. This predicate is unnecessary because, in Prolog, you can obtain these elements by simple unification: L = [X, Y]. You can try this right in the Prolog interpreter:
| ?- L = [a,3], L = [X,Y].
L = [a,3]
X = a
Y = 3
yes
We can then completely remove the divide/3 and divide2/3 predicates, and replace a call to divide2(L, X, Y) with L = [X,Y] and reduce makelist2/2 to:
makelist2(L, L2) :- L = [X, Y], makelist(X, Y, L2).
Or more simply (because we can do the unification right in the head of the clause):
makelist2([X,Y], L2) :- makelist(X, Y, L2).
You could just remove makelist2/2 and call makelist/2 directly from decode/2 by unifying H directly with its two elements, [X, N]. So the original code simplifies to:
makelist(_, N, []) :- N =< 0 .
makelist(X, Y, [X|Result]) :- Y > 0, Y1 is Y-1, makelist(X,Y1,Result).
decode([], []).
decode([[X,N]|T], L) :- makelist(X, N, H2), decode(T, L2), append(H2, L2, L).
And makelist/3 can be performed a bit more clearly using one of the methods provided in the other answers (e.g., see Boris' repeat/3 predicate).

Where is nat base 10 converted to num base 2?

For term "15::nat", the value 15 is automatically converted to the binary value (num.Bit1 (num.Bit1 (num.Bit1 num.One))). I would like to know where that's done, so I can know how it's done.
(Small update: I know that 15 is a type class numeral constant, which gets converted to binary Num.num, which gets mapped to nat, so maybe the nat is decimal, or maybe it's binary. However, my basic question remains the same. Where is the decimal to binary conversion done?)
I show below how I know about the conversion.
I define notation to show me that Num.numeral :: (num => 'a) is coercing 15 to Num.num.
abbreviation nat_of_numeral :: "num => nat" where
"nat_of_numeral n == (numeral n)"
notation nat_of_numeral ("n#N|_" [1000] 1000)
Next, 15 gets coerced to binary in a term command:
term "15::nat"
(*The output:*)
term "n#N|(num.Bit1 (num.Bit1 (num.Bit1 num.One))) :: nat"
And next, 15 gets coerced before it gets used in a proof goal:
lemma "15 = n#N|(num.Bit1 (num.Bit1 (num.Bit1 num.One)))" (*
goal (1 subgoal):
1. n#N|(num.Bit1 (num.Bit1 (num.Bit1 num.One))) =
n#N|(num.Bit1 (num.Bit1 (num.Bit1 num.One))) *)
by(rule refl)
The conversion seems to be decently fast, as shown by this:
(*140 digits: 40ms*)
term "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
::nat"
I also want to convert base 2 to base 10, but if I see how the above is done, it might show me how to do that.
Here's the overview of how I think it's done.
It starts in the Num.thy parse_translation, at the ML function numeral_tr.
In that function, there is the use of Lexicon.read_xnum of lexicon.ML, which takes a string argument.
I don't know the details, but string "15" is extracted from an expression like
"15 = n#N|(num.Bit1 (num.Bit1 (num.Bit1 num.One)))",
and fed to read_xnum, where there is this equivalency:
Lexicon.read_xnum "15" = {leading_zeros = 0, radix = 10, value = 15}
In read_xnum the function Library.read_radix_int of library.ML is used, and it takes as arguments an integer radix and a list of digits, such as shown in this equivalency:
Library.read_radix_int 10 ["1","5"] = (15, []);
Next, the conversion from 15 to (num.Bit1 (num.Bit1 (num.Bit1 num.One))) is a result of IntInf.quotRem in the parse_translation.
This takes me out of convenient HTML linking for isabelle.in.tum.de/repos.
IntInf.quotRem is in Isabelle2013-2\contrib\polyml-5.5.1-1\src\basis\IntInf.sml, and is defined as
val quotRem: int*int->int*int = RunCall.run_call2C2 POLY_SYS_quotrem,
which leads to Isabelle2013-2\contrib\polyml-5.5.1-1\src\basis\RuntimeCalls.ML line 83:
val POLY_SYS_quotrem = 104 (* DCJM 05/03/10 *).
For Windows that takes me to Isabelle2013-2\contrib\polyml-5.5.1-1\src\libpolyml\x86asm.asm line 1660, though I could be leaving out some important details:
quotrem_really_long:
MOVL Reax,Redi
CALLMACRO CALL_IO POLY_SYS_quotrem
CALLMACRO RegMask quotrem,(M_Reax OR M_Redi OR M_Redx OR Mask_all).
I think that's enough of an overview to answer my question. A string "15" is converted to an ML integer, and then some assembly language level quotient/remainder division is used to convert 15 to binary Num.num.
I'm actually only interested in how "15" is converted to 15 in read_radix_int, and whether the details of that function will help me. I explain the application more below.
From here, I put in more detail for myself, to put in a nice form much of the information I collected.
What's sort of the deal
I start with a binary number as a bool list, something like [True, True, True, True] for binary 15, though here, I simplify it in some ways.
That then gets converted to something like [[True, False, True, False], [True, False, True]], which is decimal 15.
The real problem can be finding the right search phrase
Searching on something like "decimal to binary conversion" returns links to a lot of basic math algorithms, which aren't what I'm looking for.
Normal programming conversions aren't what I need either, which is just making explicit the underlying fact that integers are already in binary form:
Convert from base 10 to base 2 using bitwise operations
C: Convert decimal to binary
Finally, other searches led me to the right word, "radix". Additionally, I resorted to doing searches on how things are done in C, where bit shifts are what I'm trying to tie into, though these may not be what I need:
Binary to decimal and decimal to binary base conversion using bitwise operators in C
C Program to Convert Decimal to Binary using Bitwise AND operator
Radix leading back to Num.thy
"Radix" took me back to Num.thy, which is where I thought the action might be, but hadn't seen anything that was obvious to me.
I include some source from Num.thy, lexicon.ML, and IntInf.sml:
(* THE TWO MAIN EXTERNAL FUNCTIONS IN THE TRANSLATIONS: read_xnum, quotRem *)
ML{*
Lexicon.read_xnum; (* string ->
{leading_zeros: int, radix: int, value: int}.*)
Lexicon.read_xnum "15"; (* {leading_zeros = 0, radix = 10, value = 15}.*)
Lexicon.read_xnum "15" = {leading_zeros = 0, radix = 10, value = 15};
IntInf.quotRem; (* int * int -> int * int.*)
IntInf.quotRem (5,3); (* (1, 2) *)
*}
parse_translation {* (* Num.thy(293) *)
let
fun num_of_int n =
if n > 0 then
(case IntInf.quotRem (n, 2) of
(0, 1) => Syntax.const #{const_name One}
| (n, 0) => Syntax.const #{const_name Bit0} $ num_of_int n
| (n, 1) => Syntax.const #{const_name Bit1} $ num_of_int n)
else raise Match
val pos = Syntax.const #{const_name numeral}
val neg = Syntax.const #{const_name neg_numeral}
val one = Syntax.const #{const_name Groups.one}
val zero = Syntax.const #{const_name Groups.zero}
fun numeral_tr [(c as Const (#{syntax_const "_constrain"}, _)) $ t $ u] =
c $ numeral_tr [t] $ u
| numeral_tr [Const (num, _)] =
let
val {value, ...} = Lexicon.read_xnum num;
in
if value = 0 then zero else
if value > 0
then pos $ num_of_int value
else neg $ num_of_int (~value)
end
| numeral_tr ts = raise TERM ("numeral_tr", ts);
in [("_Numeral", K numeral_tr)] end
*}
ML{* (* lexicon.ML(367) *)
(* read_xnum: hex/bin/decimal *)
local
val ten = ord "0" + 10;
val a = ord "a";
val A = ord "A";
val _ = a > A orelse raise Fail "Bad ASCII";
fun remap_hex c =
let val x = ord c in
if x >= a then chr (x - a + ten)
else if x >= A then chr (x - A + ten)
else c
end;
fun leading_zeros ["0"] = 0
| leading_zeros ("0" :: cs) = 1 + leading_zeros cs
| leading_zeros _ = 0;
in
fun read_xnum str =
let
val (sign, radix, digs) =
(case Symbol.explode (perhaps (try (unprefix "#")) str) of
"0" :: "x" :: cs => (1, 16, map remap_hex cs)
| "0" :: "b" :: cs => (1, 2, cs)
| "-" :: cs => (~1, 10, cs)
| cs => (1, 10, cs));
in
{radix = radix,
leading_zeros = leading_zeros digs,
value = sign * #1 (Library.read_radix_int radix digs)}
end;
end;
*}
ML{* (* IntInf.sml(42) *)
val quotRem: int*int->int*int = RunCall.run_call2C2 POLY_SYS_quotrem
*}
A big part of what I was looking for; radix again
(* THE FUNCTION WHICH TRANSLATES A LIST OF DIGITS/STRINGS TO A ML INTEGER *)
ML{*
Library.read_radix_int; (* int -> string list -> int * string list *)
Library.read_radix_int 10 ["1","5"]; (* (15, []): int * string list.*)
Library.read_radix_int 10 ["1","5"] = (15, []);
*}
ML{* (* library.ML(670) *)
fun read_radix_int radix cs =
let
val zero = ord "0";
val limit = zero + radix;
fun scan (num, []) = (num, [])
| scan (num, c :: cs) =
if zero <= ord c andalso ord c < limit then
scan (radix * num + (ord c - zero), cs)
else (num, c :: cs);
in scan (0, cs) end;
*}
The low-level division action
There's the high-level Integer.div_mod in integer.ML, which wasn't used for the translation above:
fun div_mod x y = IntInf.divMod (x, y);
In Isabelle2013-2\contrib\polyml-5.5.1-1\src\basis\IntInf.sml, the higher-level divMod can be compared to the lower-level quotRem:
ML{* (* IntInf.sml(42) *)
val quotRem: int*int->int*int = RunCall.run_call2C2 POLY_SYS_quotrem
(* This should really be defined in terms of quotRem. *)
fun divMod(i, j) = (i div j, i mod j)
*}
With the low-level action for quotRem apparently being done at the assembly language level:
ML{* (* RuntimeCalls.ML(83) *)
val POLY_SYS_quotrem = 104 (* DCJM 05/03/10 *)
*}
(* x86asm.asm(1660)
quotrem_really_long:
MOVL Reax,Redi
CALLMACRO CALL_IO POLY_SYS_quotrem
CALLMACRO RegMask quotrem,(M_Reax OR M_Redi OR M_Redx OR Mask_all)
*)
These various forms of div and mod are important to me.
I'm thinking that div and mod are to be avoided if possible, but tying into quotRem would be the way to go, I think, if division is unavoidable.

idl/gdl ERROR: function not found or scalar subscript out of range

i try to solve this problem with my code. When i compile i have the follow error message:
% POINCARE: Ambiguous: POINCARE: Function not found: XT or: POINCARE: Scalar subscript out of range [>].e
% Execution halted at: POINCARE 38 poincare.pro
% $MAIN$
It's very simple:
1) i OPEN THE FILE AND COUNT THE NUMBER OF ROWS AND COLUMNS,
2) save the fle in a matrix of ROWSxCOLUMNS,
3) take the rows that i want and save them as vectors,
Now i want to modify the columns as follow:
A) translate each element of first and second column (x and y) by a costant factor (xc, yc ....)
B) apply some manipulation of each new element of this two new columns (xn ,yn ...)
C) if the value pyn is greater than 0. then save the rows with the four value of xn ,pxn.
Here the code:
pro poincare
file = "orbitm.txt"
rows =File_Lines(file) ; per le righe
openr,lun,file,/Get_lun ; per le colonne
line=""
readf,lun,line
cols = n_elements(StrSplit(line, /RegEx, /extract))
openr,1,"orbitm.txt"
data = dblarr(cols,rows)
readf,1,data
close,1
x = data(0,*) ; colonne e righe
y = data(1,*)
px = data(2,*)
py = data(3,*)
mu =0.001
xc = 0.5-mu
yc = 0.5*sqrt(3.)
openw,3,"section.txt"
for i=1, rows-2 do begin
xt = x(i)-xc
yt = y(i)-yc
pxt = px(i)-yc
pyt = py(i)+xc
tau = y(i)/(y(i)-y(i+1))
xn = xt(i) + (xt(i+1)-xt(i))*tau
yn = yt(i) + (yt(i+1)-yt(i))*tau
pxn = pxt(i) + (pxt(i+1)-pxt(i))*tau
pyn = pyt(i) + (pyt(i+1)-pyt(i))*tau
if (pyt(i) GT 0.) then begin
printf,3, xt(i), pxt(i)
endif
endfor
close,3
end
I attach also the first rows of my input orbitm.txt:
0.73634 0.66957 0.66062 -0.73503
0.86769 0.54316 0.51413 -0.82823
0.82106 0.66553 0.60353 -0.74436
0.59526 0.88356 0.79569 -0.52813
0.28631 1.0193 0.92796 -0.24641
-0.29229E-02 1.0458 0.96862 0.21874E-01
-0.21583 1.0090 0.95142 0.22650
-0.33994 0.96091 0.92099 0.35144
-0.38121 0.93413 0.90831 0.39745
-0.34462 0.93959 0.92534 0.36561
-0.22744 0.96833 0.96431 0.25054
-0.24560E-01 0.99010 0.99480 0.45173E-01
0.25324 0.95506 0.96459 -0.24000
0.55393 0.81943 0.82584 -0.54830
0.78756 0.61644 0.61023 -0.77367
0.88695 0.53076 0.50350 -0.82814
I can see a few issues that are immediately obvious. The first is that you define the variables XT, YT, PXT, and PYT inside your FOR loop as scalars. Shortly after, you try to index them as if they are arrays with multiple elements. Either your definition for these variables needs to change, or you need to change your definition of XN, YN, PXN, and PYN. Otherwise, this will not work as written. I have attached a modified version of your code with some suggestions and comments included.
pro poincare
file = "orbitm.txt"
rows =File_Lines(file) ; per le righe
openr,lun,file,/Get_lun ; per le colonne
line=""
readf,lun,line
cols = n_elements(StrSplit(line, /RegEx, /extract))
free_lun,lun ;; need to close this LUN
;; define data array
data = dblarr(cols,rows)
;;openr,1,"orbitm.txt"
;;readf,1,data
;; data = dblarr(cols,rows)
;;close,1
openr,lun,"orbitm.txt",/get_lun
readf,lun,data
free_lun,lun ;; close this LUN
;;x = data(0,*) ; colonne e righe
;;y = data(1,*)
;;px = data(2,*)
;;py = data(3,*)
x = data[0,*] ;; use []'s instead of ()'s in IDL
y = data[1,*]
px = data[2,*]
py = data[3,*]
mu = 0.001
xc = 0.5 - mu ;; currently a scalar
yc = 0.5*sqrt(3.) ;; currently a scalar
;; Perhaps you want to define XT, YT, PXT, and PYT as:
;; xt = x - xc[0]
;; yt = y - yc[0]
;; pxt = px - yc[0]
;; pyt = py + xc[0]
;; Then you could index these inside the FOR loop and
;; remove their definitions therein.
;;openw,3,"section.txt"
openw,lun,"section.txt",/get_lun
for i=1L, rows[0] - 2L do begin
xt = x[i] - xc ;; currently a scalar
yt = y[i] - yc ;; currently a scalar
pxt = px[i] - yc ;; currently a scalar
pyt = py[i] + xc ;; currently a scalar
tau = y[i]/(y[i] - y[i+1]) ;; currently a scalar
;; In the following you are trying to index XT, YT, PXT, and PYT but
;; each are scalars, not arrays!
xn = xt[i] + (xt[i+1] - xt[i])*tau
yn = yt[i] + (yt[i+1] - yt[i])*tau
pxn = pxt[i] + (pxt[i+1] - pxt[i])*tau
pyn = pyt[i] + (pyt[i+1] - pyt[i])*tau
if (pyt[i] GT 0.) then begin
printf,lun, xt[i], pxt[i]
endif
endfor
free_lun,lun ;; close this LUN
;;close,3
;; Return
return
end
General IDL Notes: You should use []'s instead of ()'s to index arrays to avoid confusion with functions. It is generally better to let IDL define a logical unit number (LUN) and then free the LUN than use CLOSE.

Resources