How to modify a set of Ansys Fluent variables with Scheme file i/o? - file-io

The Problem
My co-worker and I have been trying to get some Scheme code working that will take input from a TSV file and assign those values to variables already defined in the Ansys software.
The Files
The TSV file is organized as follows:
1 0.7 0.8 0.7 1.0 0.5 [...]
2 0.9 0.9 0.3 0.5 0.5 [...]
3 0.5 0.8 0.3 0.3 0.7 [...]
4 0.6 0.2 1.0 0.5 0.5 [...]
5 0.9 0.0 0.0 0.8 0.3 [...]
6 0.5 0.6 0.3 0.4 1.0 [...]
[ ... ]
1998 0.5 0.0 0.2 0.9 0.0 [...]
1999 0.8 0.2 0.2 0.7 0.2 [...]
2000 0.7 0.2 0.8 0.4 0.5 [...]
The first column is the flow-time at which that particular set of inputs needs to be assigned to the variables in the software; the other 96 columns represent the 96 variables that need to be set.
The Scheme code that I have so far is this:
;Set variables
(define (setFunc)
(lambda(row-position outflow-number flow-wt-1)
(let outflow-string ((string-append("def bc outflow " outflow-number " ~a")))
(if (< row-position 180)
(ti-menu-load-string (format #f (outflow-string) flow-wt-1))
(ti-menu-load-string (format #f (outflow-string) 0.0))
)
)
)
)
;Read a file to a list of chars
(define (file->char_list)
(call-with-input-file "doorstates.txt"
(lambda(input-port)
(let loop ((x (read-char input-port)))
(if (not (eof-object? x))
(#t (begin (cons x (loop (read-char input-port)))))
)
)
)
)
)
;Main
(begin
(let inFile ((apply string (file->char_list)))
(let inFileList ((string-split (inFile #\newline)))
(let index ((0))
; Row position = flow-time - 1
(define rowPosition ((- flow-time 1)))
(let loop ((index))
(cond ((>= index (length inFileList))
'()
)
((= (- index (* (/ index 97) 97)) 0)
(+ index 1)
(loop (index))
)
((= (/ index 97) rowPosition)
; Column position = index - (rowPosition * rowLength)
(define colPosition ((- index (* rowPosition 97))))
(setFunc (rowPosition colPosition list-ref inFileList index))
(+ index 1)
(loop (index))
)
(else
(+ index 1)
(loop (index))
)
)
)
)
)
)
)
When the above code is run with the Ansys software it produces the following error:
Error: eval: unbound variable
Error Object: string
All the sources I've read have said that the most likely cause of an unbound variable is that extra parentheses were put around parameters that aren't functions (like literals); but everything I've seen has also had double parentheses around let arguments.
The Point
I had never worked with Scheme or any other LISP variation before being put on this project so if there are any errors or common practices I'm missing please let me know. Also if the above Scheme code is total crap and not doing what I need it to do please let me know and suggest next steps!

You are misinterpreting the error message. Your begin is missing a closing parenthesis. Thus, the end of file is encountered within the "list" starting with (begin .... Furthermore, you are using let incorrectly. You need to enclose the code that uses the variables, e.g.:
(let ((a 1))
(+ a 7))
I suggest using an editor that understand s-expressions.

Related

Confused with "do" variables in Racket code

Don't understand why
"a"
and
"b"
work in the code ? should we define var
"a"
and
"b"
before
"do"
?
(define v1 3)
(define v2 2)
(do ((a 1 (+ a v1))
(b 2 (+ b v2)))
((>= a b) (if (= a b) 'YES 'NO)))
After (do the local variables for the do loop are defined:
(a 1 (+ a v1)) meaning: define local loop variable a with starting value 1 and assigning (+ a v1) to a at the beginning of a new round
(b 2 (+ b v2)) meaning: define local loop variable b with starting value 2 and assigning (+ b v2) to b at the beginning of a new round
So, a and b are defined in the do loop.
There are no control flow operations other than procedure calls.
do is just a macro. The R5RS report gives an implementation:
(define-syntax do
(syntax-rules ()
((do ((var init step ...) ...)
(test expr ...)
command ...)
(letrec
((loop
(lambda (var ...)
(if test
(begin
(if #f #f)
expr ...)
(begin
command
...
(loop (do "step" var step ...)
...))))))
(loop init ...)))
((do "step" x)
x)
((do "step" x y)
y)))
Your code turns into something like this:
(let loop ((a 1) (b 2))
(if (>= a b)
(if (= a b) 'YES 'NO)
(loop (+ a v1) (+ b v2))))

Optimization of MiniZinc model

I have a MiniZinc model which is supposed to find d[1 .. n] and o[1..k, 0 .. n] such that
x[k] = o[k,0] + d[1]*o[k,1] + d[2]*o[k,2] ... d[n]+o[k,n] and the sum of absolute values of o[k,i]'s is minimized.
I have many different x[i] and d[1..n] should remain the same for all of them.
I have a working model which is pasted below, which finds a good solution in the n=2 case really quickly (less than a second) however, if I go to n=3 (num_dims in the code) even after an hour I get no answer except the trivial one (xi=o0), even though the problem is somewhat recursive, in that a good answer for 2 dimensions can serve as a starting point for 3 dimensions by using o0 as xi for a new 2 dimensional problem.
I have used MiniZinc before, however, I do not have a background in OR or Optimization, thus I do not really know how to optimize my model. I would be helpful for any hints on how to do that, either by adding constraints or somehow directing the search. Is there a way to debug such performance problems in MiniZinc?
My current model:
% the 1d offsets
array [1 .. num_stmts] of int : x;
x = [-10100, -10001, -10000, -9999, -9900, -101, -100, -99, -1, 1, 99, 100, 101, 9900, 9999, 10000, 10001, 10100];
int : num_stmts = 18;
% how many dimensions we decompose into
int : num_dims = 2;
% the dimension sizes
array [1 .. num_dims] of var int : dims;
% the access offsets
array [1 .. num_stmts, 1 .. num_dims] of var int : offsets;
% the cost function: make access distance (absolute value of offsets) as small as possible
var int : cost = sum (s in 1 .. num_stmts, d in 1 .. num_dims) (abs(offsets[s,d]));
% dimensions must be positive
constraint forall (d in 1 .. num_dims) (dims[d] >= 0);
% offsets * dimensions must be equal to the original offsets
constraint forall (s in 1 .. num_stmts) (
x[s] = offsets[s,1] + sum(d in 2 .. num_dims) (offsets[s,d] * dims[d-1])
);
% disallow dimension crossing
constraint forall (s in 1 .. num_stmts, d in 1 .. num_dims) (
abs(offsets[s,d]) < dims[d]
);
% all dims together need to match the array size
constraint product (d in 1..num_dims) (dims[d]) = 1300000;
solve minimize cost;
output ["dims = ", show(dims), "\n"] ++
[ if d == 1 then show_int(6, x[s]) ++ " = " else "" endif ++
" " ++ show_int(4, offsets[s, d]) ++ if d>1 then " * " ++ show(dims[d-1]) else "" endif ++
if d == num_dims then "\n" else " + " endif |
s in 1 .. num_stmts, d in 1 .. num_dims];
Are you using the MiniZinc IDE? Have you tried using a different solver?
I was struggling with a problem of dividing n random positive integers into m groups (m < n) where the sum of each group was supposed to be as close as possible to some other number.
When n reached about 100 and m about 10, it took significantly longer time (30 min+) and the result was not satisfying. This was using the default Gecode (bundled) solver. By chance I went through each and everyone of the solvers and found that the COIN-OR CBC (bundled) found an optimal solution within 15 s.

loop function is taking too long

I'm trying to do a function who implements a sum of n cubes:
1^3 + 2^3 + 3^3 + ... + n^3 = sum
My function should receive a sum and return a n or -1 if n doesn't exists.
Some examples:
(find-n 9) ; should return 2 because 1^3 + 2^3 = 9
(find-n 100) ; should return 4 because 1^3 + 2^3 + 3^3 + 4^3 = 100
(find-n 10) ; should return -1
After some work I made these two functions:
; aux function
(defn exp-3 [base] (apply *' (take 3 (repeat base))))
; main function
(defn find-n [m]
(loop [sum 0
actual-base 0]
(if (= sum m)
actual-base
(if (> sum m)
-1
(recur (+' sum (exp-3 (inc actual-base))) (inc actual-base))))))
These functions are working properly but is taking too long to evaluate operations with BigNumbers, as example:
(def sum 1025247423603083074023000250000N)
(time (find-n sum))
; => "Elapsed time: 42655.138544 msecs"
; => 45001000
I'm asking this question to raise some advices of how can I make this function faster.
This is all about algebra, and little to do with Clojure or programming. Since this site does not support mathematical typography, let's express it in Clojure.
Define
(defn sigma [coll] (reduce + coll))
and
(defn sigma-1-to-n [f n]
(sigma (map f (rest (range (inc n))))))
(or
(defn sigma-1-to-n [f n]
(->> n inc range rest (map f) sigma))
)
Then the question is, given n, to find i such that (= (sigma-1-to-n #(* % % %) i) n).
The key to doing this quickly is Faulhaber's formula for cubes. It tells us that the following are equal, for any natural number i:
(#(*' % %) (sigma-1-to-n identity i))
(sigma-1-to-n #(* % % %) i)
(#(*' % %) (/ (*' i (inc i)) 2))
So, to be the sum of cubes, the number
must be a perfect square
whose square root is the sum of the first so many numbers.
To find out whether a whole number is a perfect square, we take its approximate floating-point square root, and see whether squaring the nearest integer recovers our whole number:
(defn perfect-square-root [n]
(let [candidate (-> n double Math/sqrt Math/round)]
(when (= (*' candidate candidate) n)
candidate)))
This returns nil if the argument is not a perfect square.
Now that we have the square root, we have to determine whether it is the sum of a range of natural numbers: in ordinary algebra, is it (j (j + 1)) / 2, for some natural number j.
We can use a similar trick to answer this question directly.
j (j + 1) = (j + 1/2)^2 + 1/4
So the following function returns the number of successive numbers that add up to the argument, if there is one:
(defn perfect-sum-of [n]
(let [j (-> n (*' 2)
(- 1/4)
double
Math/sqrt
(- 0.5)
Math/round)]
(when (= (/ (*' j (inc j)) 2) n)
j)))
We can combine these to do what you want:
(defn find-n [big-i]
{:pre [(integer? big-i) ((complement neg?) big-i)]}
(let [sqrt (perfect-square-root big-i)]
(and sqrt (perfect-sum-of sqrt))))
(def sum 1025247423603083074023000250000N)
(time (find-n sum))
"Elapsed time: 0.043095 msecs"
=> 45001000
(Notice that the time is about twenty times faster than before, probably because HotSpot has got to work on find-n, which has been thoroughly exercised by the appended testing)
This is obviously a lot faster than the original.
Caveat
I was concerned that the above procedure might produce false negatives (it will never produce a false positive) on account of the finite precision of floating point. However, testing suggests that the procedure is unbreakable for the sort of number the question uses.
A Java double has 52 bits of precision, roughly 15.6 decimal places. The concern is that with numbers much bigger than this, the procedure may miss the exact integer solution, as the rounding can only be as accurate as the floating point number that it starts with.
However, the procedure solves the example of a 31 digit integer correctly. And testing with many (ten million!) similar numbers produces not one failure.
To test the solution, we generate a (lazy) sequence of [limit cube-sum] pairs:
(defn generator [limit cube-sum]
(iterate
(fn [[l cs]]
(let [l (inc l)
cs (+' cs (*' l l l))]
[limit cs]))
[limit cube-sum]))
For example,
(take 10 (generator 0 0))
=> ([0 0] [1 1] [2 9] [3 36] [4 100] [5 225] [6 441] [7 784] [8 1296] [9 2025])
Now we
start with the given example,
try the next ten million cases and
remove the ones that work.
So
(remove (fn [[l cs]] (= (find-n cs) l)) (take 10000000 (generator 45001000 1025247423603083074023000250000N)))
=> ()
They all work. No failures. Just to make sure our test is valid:
(remove (fn [[l cs]] (= (find-n cs) l)) (take 10 (generator 45001001 1025247423603083074023000250000N)))
=>
([45001001 1025247423603083074023000250000N]
[45001002 1025247514734170359564546262008N]
[45001003 1025247605865263720376770289035N]
[45001004 1025247696996363156459942337099N]
[45001005 1025247788127468667814332412224N]
[45001006 1025247879258580254440210520440N]
[45001007 1025247970389697916337846667783N]
[45001008 1025248061520821653507510860295N]
[45001009 1025248152651951465949473104024N]
[45001010 1025248243783087353664003405024N])
All ought to fail, and they do.
Just avoiding the apply (not really all that fast in CLJ) gives you a 4x speedup:
(defn exp-3 [base]
(*' base base base))
And another 10%:
(defn find-n [m]
(loop [sum 0
actual-base 0]
(if (>= sum m)
(if (= sum m) actual-base -1)
(let [nb (inc actual-base)]
(recur (+' sum (*' nb nb nb)) nb)))))
The following algorithmic-based approach relies on one simple formula which says that the sum of the cubes of the first N natural numbers is: (N*(N+1)/2)^2
(defn sum-of-cube
"(n*(n+1)/2)^2"
[n]
(let [n' (/ (*' n (inc n)) 2)]
(*' n' n')))
(defn find-nth-cube
[n]
((fn [start end prev]
(let [avg (bigint (/ (+' start end) 2))
cube (sum-of-cube avg)]
(cond (== cube n) avg
(== cube prev) -1
(> cube n) (recur start avg cube)
(< cube n) (recur avg end cube))))
1 n -1))
(time (find-nth-cube 1025247423603083074023000250000N))
"Elapsed time: 0.355177 msecs"
=> 45001000N
We want to find the number N such that the sum of 1..N cubes is some number X. To find if such a number exists, we can perform a binary search over some range for it by applying the above formula to see whether the result of the formula equals X. This approach works because the function at the top is increasing, and thus any value f(n) which is too large means that we must look for a lower number n, and any value f(n) which is too small means that we must look for a larger number n.
We choose a (larger than necessary, but easy and safe) range of 0 to X. We will know that the number exists if our formula applied to a given candidate number yields X. If it does not, we continue the binary search until either we find the number, or until we have tried the same number twice, which indicates that the number does not exist.
With an upper bound of logN, only takes 1 millisecond to compute 1E100 (1 googol), so it's very efficient for an algorithmic approach.
You may want to use some mathematical tricks.
(a-k)^3 + (a+k)^3 = 2a^3+(6k^2)a
So, a sum like:
(a-4)^3+(a-3)^3+(a-2)^3+(a-1)^3+a^3+(a+1)^3+(a+2)^3+(a+3)^3+(a+4)^3
= 9a^3+180a
(please confirm correctness of the calculation).
Using this equation, instead of incrementing by 1 every time, you can jump by 9 (or by any 2 k+1 you like). You can check for the exact number whenever you hit a bigger number than n.
Other way to improve is to have a table of ns and sums, by making a batch of computations once and use this table later in function find-n.

Using local variables in scheme

I have been asked to translate a couple of C functions to scheme for an assignment. My professor very briefly grazed over how Scheme works, and I am finding it difficult to understand. I want to create a function that checks to see which number is greater than the other, then keeps checking every time you input a new number. The issue I am having is with variable declaration. I don't understand how you assign a value to an id.
(define max 1)
(define (x x)
(let maxfinder [(max max)]
(if (= x 0)
0
(if (> max x)
max
((= max x) maxfinder(max))))))
The trouble I keep running into is that I want to initialize max as a constant, and modify x. In my mind this is set up as an infinite loops with an exit when x = 0. If max is > x, which it should not be for the first time through, then set max = to x, and return x. I don't know what to do with the constant max. I need it to be a local variable. Thanks
Parenthesis use is very strict. Besides special forms they are used to call procedures. eg (> max x) calls procedure > with arguments max and x. ((if (> x 3) - +) 6 x) is an example where the if form returns a procedure and the result is called.
((= max x) ...) evaluates (= max x) and since the result is not a procedure it will fail.
maxfinder without parenthesis is just a procedure object.
(max) won't work since max is a number, not a procedure.
As for you problem. You add the extra variables you need to change in the named let. Eg. a procedure that takes a number n and makes a list with number 0-n.
(define (make-numbered-list n)
(let loop ((n n) (acc '()))
(if (zero? n)
acc
(loop (- n 1) (cons n acc)))))
Local variables are just locally bound symbols. This can be rewritten
(define (make-numbered-list n)
(define (loop n acc)
(if (zero? n)
acc
(loop (- n 1) (cons n acc))))
(loop n '()))
Unlike Algol dialects like C you don't mutate variables in a loop, but use recusion to alter them.
Good luck
If i understand you correctly, you are looking for the equivalent of a C function's static variable. This is called a closure in Scheme.
Here's an example implementation of a function you feed numbers to, and which will always return the current maximum:
(define maxfinder
(let ((max #f)) ; "static" variable, initialized to False
(lambda (n) ; the function that is defined
(when (or (not max) (< max n)) ; if no max yet, or new value > max
(set! max n)) ; then set max to new value
max))) ; in any case, return the current max
then
> (maxfinder 1)
1
> (maxfinder 10)
10
> (maxfinder 5)
10
> (maxfinder 2)
10
> (maxfinder 100)
100
So this will work, but provides no mechanism to reuse the function in a different context. The following more generalised version instantiates a new function on every call:
(define (maxfinder)
(let ((max #f)) ; "static" variable, initialized to False
(lambda (n) ; the function that is returned
(when (or (not max) (< max n)) ; if no max yet, or new value > max
(set! max n)) ; then set max to new value
max))) ; in any case, return the current max
use like this:
> (define max1 (maxfinder)) ; instantiate a new maxfinder
> (max1 1)
1
> (max1 10)
10
> (max1 5)
10
> (max1 2)
10
> (max1 100)
100
> (define max2 (maxfinder)) ; instantiate a new maxfinder
> (max2 5)
5
Define a function to determine the maximum between two numbers:
(define (max x y)
(if (> x y) x y))
Define a function to 'end'
(define end? zero?)
Define a function to loop until end? computing max
(define (maximizing x)
(let ((input (begin (display "number> ") (read))))
(cond ((not (number? input)) (error "needed a number"))
((end? input) x)
(else (maximizing (max x input))))))
Kick it off:
> (maximizing 0)
number> 4
number> 1
number> 7
number> 2
number> 0
7

Query for "surrounding hex tiles" based on axial coordinates

After reading Red Blob Games' excellent article on heaxgon tile maps and their coordinates.
I am wondering how one would write a SQL-query that returns the tiles surrounding a centered tile up to a range of X. (assuming the "axial coordinates" covered in the article)
A simple idea I first had was
WHERE x BETWEEN tile_x - 1 AND tile_x + 1 AND y BETWEEN tile_y - 1 AND tile_y + 1
But this will return too many tiles, in a way that creates a shape more like a rhombus rather than a circle, which is what I need.
Unfortunately, I haven't found a conclusive answer to this, maybe someone here can give me a hint.
I already thought about some tricks on the sum of the coordinates and wether they are larger of lower than the range, but this won't work with the axial coordinates.
From the diagrams in the linked article, it seems that something like
where (x between tile_x and tile_x + 1) and (y between tile_y - 1 and tile_y + 1)
or (x = tile_x - 1) and (y = tile_y)
should work
If you want to find the tiles (tile_x, tile_y) within a distance n from a given tile (x, y), it will be easier if the x coordinate is modified by adding 0.5 to the x coordinate of each row having an odd distance from the given tile, such that the symmetry is increased:
-1.5 -0.5 0.5 1.5
-2 -1 0 1 2
-2.5 -1.5 -0.5 0.5 1.5 2.5
-3 -2 -1 0 1 2 3
-2.5 -1.5 -0.5 0.5 1.5 2.5
-2 -1 0 1 2
-1.5 -0.5 0.5 1.5
This can be achieved using the expression tile_x + 0.5 * tile_y%2
As the number of tiles within the given distance is reduced by one
from row to row, the limits of (modified) x coordinates in a given
row is n - abs(tile_y - y)/2.
Then the tiles is within a distance n if
abs(tile_y - y) <= n
and abs(tile_x - x + 0.5 * (tile_y-y)%2) <= n - abs(tile_y - y)/2
In sql:
SELECT tile_x, tile_y
FROM tiles
WHERE ABS(tile_y - y) <= n
AND ABS(tile_x - x +0.5*(tile_y-y)%2) + ABS(tile_y - y) / 2 <= n
After some more reading, I found that the article I linked actually alread solves that problem, although somewhat hidden, so here is a more "straight forward" answer.
(Nonetheless, Terje D.'s answer works fine, I just post this because I feel it's a little easier to understand than the "sorcery" of his answer)
In the article from Red Blob Games, he actually describes the formula that calculates the distance between two given hexes:
function hex_distance(Hex(q1, r1), Hex(q2, r2)) {
return (abs(q1 - q2) + abs(r1 - r2)
+ abs(q1 + r1 - q2 - r2)) / 2;
}
I translated this into a function in MySQL
CREATE FUNCTION `rangeBetweenTiles`(tile1q int, tile1r int, tile2q int, tile2r int) RETURNS int(11)
DETERMINISTIC
BEGIN
RETURN (abs(tile1q - tile2q) + abs(tile1r - tile2r)
+ abs(tile1q + tile1r - tile2q - tile2r)) / 2;
END
And use this in another function:
CREATE FUNCTION `isInRange`(tile1q int, tile1r int, tile2q int, tile2r int, `range` Int) RETURNS tinyint(1)
DETERMINISTIC
BEGIN
RETURN rangeBetweenTiles(tile1q, tile1r, tile2q, tile2r) <= `range`;
END
Which can then be used very easily in a select statement:
select *
from tiles
where isInRange(:tile_q, :tile_r, positionQ, positionR, :n)
And it works perfectly fine for any :n