script-fu variables set from cond but treated as unset - gimp

I'm trying to set up a script for raw photos, to allow me to add two copies of the existing file (all taken from ufraw), at different exposures so I can recover shadow and highlight detail. The part for the shadow file is now working, hard-coded to use the same layer for its mask and with a mode of NORMAL.
But I want to pass an option for the shadow mask, so that I can take it from the shadow layer or the base layer (the normal exposure) AND set the mode to NORMAL or LIGHTEN-ONLY. The following code does not error:
(cond ( < shadow-option 2 ) (define (sm-source shadow-layer))
(else (define (sm-source base-layer))))
(cond ( = shadow-option 0 ) (define (shadow-mode NORMAL))
(else (define (shadow-mode LIGHTEN-ONLY))))
Maybe my cond tests are not going to do what I want, but AFAICS both sm-source and shadow-mode must have a value, either from the test being true, or from the else ?
But both appear to not be defined when I try to reference them. The first use is on the next line of my script:
(gimp-layer-set-mode shadow-layer shadow-mode)
But I get Error: ( : 1) eval: unbound variable: shadow-mode. If I comment that line and replace it by a hardcoded mode, I then get a similar error for sm-source.

Related

Print values of constraint at each iteration during optimization

How can we do this from Pydrake? Print values of constraint at each iteration during optimization
EDIT 1:
I tried:
def update(n):
print(n)
prog.AddVisualizationCallback(update, n)
in accordance with the example here at the bottom: https://github.com/RobotLocomotion/drake/blob/master/tutorials/debug_mathematical_program.ipynb
But it spat out this error:
prog.AddVisualizationCallback(update, n)
TypeError: AddVisualizationCallback(): incompatible function arguments. The following argument types are supported:
1. (self: pydrake.solvers.mathematicalprogram.MathematicalProgram, arg0: Callable[[numpy.ndarray[numpy.float64[m, 1]]], None], arg1: numpy.ndarray[object[m, 1]]) -> pydrake.solvers.mathematicalprogram.Binding[VisualizationCallback]
Here are a few possibilities:
You can use AddVisualizationCallback to make effectively an empty generic constraint that gets called on each iteration.
You might also want to increase the solver verbosity level (see the “debugging mathematical programs” tutorial) so that the solver itself prints some progress info.
Depending on what sort of constraint you’re thinking about, you could potentially just implement the constraint itself as a python method (with a print statement inside) instead of whatever you’re doing to add it right now.

Maxima: Is there any way to make functions defined within the main function be local, in a similar way to local variables?

I wonder if there is any way to make functions defined within the main function be local, in a similar way to local variables. For example, in this function that calculates the gradient of a scalar function,
grad(var,f) := block([aux],
aux : [gradient, DfDx[i]],
gradient : [],
DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
for i in [1,2,3] do (
gradient : append(gradient, [DfDx[i]])
),
return(gradient)
)$
The variable gradient that has been defined inside the main function grad(var,f) has no effect outside the main function, as it is inside the aux list. However, I have observed that the function DfDx, despite being inside the aux list, does have an effect outside the main function.
Is there any way to make the sub-functions defined inside the main function to be local only, in a similar way to what can be made with local variables? (I know that one can kill them once they have been used, but perhaps there is a more elegant way)
To address the problem you are needing to solve here, another way to compute the gradient is to say
grad(var, e) := makelist(diff(e, var1), var1, var);
and then you can say for example
grad([x, y, z], sin(x)*y/z);
to get
cos(x) y sin(x) sin(x) y
[--------, ------, - --------]
z z 2
z
(There isn't a built-in gradient function; this is an oversight.)
About local functions, bear in mind that all function definitions are global. However you can approximate a local function definition via local, which saves and restores all properties of a symbol. Since the function definition is a property, local has the effect of temporarily wiping out an existing function definition and later restoring it. In between you can create a temporary function definition. E.g.
foo(x) := 2*x;
bar(y) := block(local(foo), foo(x) := x - 1, foo(y));
bar(100); /* output is 99 */
foo(100); /* output is 200 */
However, I don't this you need to use local -- just makelist plus diff is enough to compute the gradient.
There is more to say about Maxima's scope rules, named and unnamed functions, etc. I'll try to come back to this question tomorrow.
To compute the gradient, my advice is to call makelist and diff as shown in my first answer. Let me take this opportunity to address some related topics.
I'll paste the definition of grad shown in the problem statement and use that to make some comments.
grad(var,f) := block([aux],
aux : [gradient, DfDx[i]],
gradient : [],
DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
for i in [1,2,3] do (
gradient : append(gradient, [DfDx[i]])
),
return(gradient)
)$
(1) Maxima works mostly with expressions as opposed to functions. That's not causing a problem here, I just want to make it clear. E.g. in general one has to say diff(f(x), x) when f is a function, instead of diff(f, x), likewise integrate(f(x), ...) instead of integrate(f, ...).
(2) When gradient and Dfdx are to be the local variables, you have to name them in the list of variables for block. E.g. block([gradient, Dfdx], ...) -- Maxima won't understand block([aux], aux: ...).
(3) Note that a function defined with square brackets instead of parentheses, e.g. f[x] := ... instead of f(x) := ..., is a so-called array function in Maxima. An array function is a memoizing function, i.e. if f[x] is called two or more times, the return value is only computed once, and then returned every time thereafter. Sometimes that's a useful optimization when the domain of the function comprises a finite set.
(4) Bear in mind that x_1, x_2, x_3, are distinct symbols, not related to each other, and not related to x[1], x[2], x[3], even if they are displayed the same. My advice is to work with subscripted symbols x[i] when i is a variable.
(5) About building up return values, try to arrange to compute the whole thing at one go, instead of growing the result incrementally. In this case, makelist is preferable to for plus append.
(6) The return function in Maxima acts differently than in other programming languages; it's a little hard to explain. A function returns the value of the last expression which was evaluated, so if gradient is that last expression, you can just write grad(var, f) := block(..., gradient).
Hope this helps, I know it's obscure and complex. The Maxima programming language was not designed before being implemented, and some of the decisions are clearly questionable at the long interval of more than 50 years (!) later. That's okay, they were figuring it out as they went along. There was not a body of established results which could provide a point of reference; the original authors were contributing to what's considered common knowledge today.

How to get a path for script-fu function: gimp-drawable-edit-stroke-item

I am struggling with getting the actual path (or vector) object from an id. I want to stroke a path and the currently advised way of doing so seems to be the method gimp-drawable-edit-stroke-item. This needs an item as input. By the way I tried to find a list of all predefined types in script-fu but also didn't find anything. So I am not sure what the typ Item really is but it looks like you can pass a vector to it.
All I can find so far to identify a path is using (cadr(gimp-image-get-vectors p-image)) which seems to only give me an id. As the following (gimp-drawable-edit-stroke-item p-drawable (cadr(gimp-image-get-vectors p-image))) leads to an "Error: Invalid type for argument 2 to gimp-drawable-edit-stroke-item".
Having to navigate lists instead of using names for fields is the reason why I never bothered with Scheme/script-fu since Gimp can be scripted in Python.
This said, with my limited Lisp knowledge:
(gimp-image-get-vectors p-image) returns a (count (v1 v2 v3 ...)) list
so (cadr (gimp-image-get-vectors p-image)) returns the list, and not a single item of the list.
You can get the "active path" directly with (gimp-image-get-vectors p-image) (using the paths list doesn't tell you which path in the list is meant by the user anyway).
"I want to stroke a path"
Rather than gimp-drawable-edit-stroke-item, gimp-pencil (or gimp-brush) can do it:
(define (stroke-path drawable color width . path)
(gimp-context-set-line-miter-limit 5) ; default: 10, default mitre up to 60 pixels
(gimp-context-set-stroke-method STROKE-LINE) ; default STROKE-PAINT-METHOD
(gimp-context-set-line-cap-style CAP-BUTT) ; CAP-ROUND, CAP-SQUARE
(gimp-context-set-line-join-style JOIN-ROUND) ; JOIN-MITER, JOIN-ROUND, JOIN-BEVEL
(gimp-context-set-foreground color)
(gimp-context-set-line-width width) ; default: 6
(let ((vec (apply vector path)))
(gimp-pencil drawable (vector-length vec) vec)
)
)

Maxima spline result not changing in loop

I'm trying to iterate over 2 parameters to get two splines for each pair. The code:
y_arr:[0.2487,0.40323333333333,0.55776666666667,0.7123]$
str_h_arr:[-0.8,-1.0,-1.2,-1.4]$
z_points:[0,0.1225,0.245,0.3675,0.49,0.6125,0.735,0.8575,0.98,1.1025,1.225,1.3475,1.47,
1.5925,1.715,1.8375,1.96,2.0825,2.205,2.26625,2.3275,2.3765,2.401,2.4255,2.43775,
2.4451,2.448775,2.45]$
length(a)$
length(b)$
load(interpol)$
for y_k:1 thru length(a) do (
for h_k:1 thru length(b) do (
y:y_arr[y_k],
str_h:str_h_arr[h_k],
bot_startpoints: [[-2.45,0],[0,y],[2.45,0]],
top_startpoints: [[-2.45,str_h_min],[0,y+str_h],[2.45,str_h_min]],
spline: cspline(bot_startpoints),
bot(x):=''spline,
print(bot(0))
)
);
//Part with top spline is skipped.
For all iterations output is now the same: 0.7123
What I want to get is two splines like in picture
Members of y_arr are y values in x=0, str_h_arr: height between splines in x=0.
So bot(0) should give me all values from y_arr.
If i don't use loop and just give this block values of y_k and h_k, it's working properly.
Can anybody point me to where I'm (or Maxima is) wrong with using loop with cspline?
The problem is that quote-quote (two single quotes, '') is applied only once, when it is read in input; it is not applied every time the expression in evaluated in the loop.
Looks like you need only to evaluate the spline at x = 0 and nothing else. So I'll suggest ev(spline, x=0) to evaluate it. You can also construct a lambda expression and evaluate that.
Here is the program after I've revised it as described above. Also, it is simpler and clearer to write for y in y_arr do (...) rather than making use of an explicit index for y_arr.
y_arr:[0.2487,0.40323333333333,0.55776666666667,0.7123]$
str_h_arr:[-0.8,-1.0,-1.2,-1.4]$
z_points:[0,0.1225,0.245,0.3675,0.49,0.6125,0.735,0.8575,0.98,1.1025,1.225,1.3475,1.47,
1.5925,1.715,1.8375,1.96,2.0825,2.205,2.26625,2.3275,2.3765,2.401,2.4255,2.43775,
2.4451,2.448775,2.45]$
load(interpol)$
for y in y_arr do (
for str_h in str_h_arr do (
bot_startpoints: [[-2.45,0],[0,y],[2.45,0]],
top_startpoints: [[-2.45,str_h_min],[0,y+str_h],[2.45,str_h_min]],
spline: cspline(bot_startpoints),
print (ev (spline, x=0))));
This is the output I get:
0.2487
0.2487
0.2487
0.2487
0.40323333333333
0.40323333333333
0.40323333333333
0.40323333333333
0.55776666666667
0.55776666666667
0.55776666666667
0.55776666666667
0.7123
0.7123
0.7123
0.7123

BST printing without mutating?

So i basically want to printbst's .. here is a little more detail
Provide a function (printbst t) that prints a BST constructed from BST as provided by bst.rkt in the following format:
-Each node in the BST should be printed on a separate line;
-the left subtree should be printed after the root;
-The right subtree should be printed before the root;
-The key value should be indented by 2d spaces where d is its depth, or distance from the root. That is, the root should not be indented, the keys in its subtrees should be intended 2 spaces, the keys in their subtrees 4 spaces, and so on.
For example, the complete tree containing {1,2,3,4,5,6} would be printed like this:
6
5
4
3
2
1
Observe that if you rotate the output clockwise and connect each node to its subtrees, you arrive at the conventional graphical representation of the tree. Do not use mutation.
Here is what i have so far:
#lang racket
;;Note: struct-out exports all functions associated with the structure
(provide (struct-out BST))
(define-struct BST (key left right) #:transparent)
(define (depth key bst)
(cond
[(or (empty? bst) (= key (BST-key bst))) 0]
[else (+ 1 (depth key (BST-right bst)) (depth key (BST-left bst)))]))
(define (indent int)
(cond
[(= int 0) ""]
[else " " (indent (sub1 int))]))
(define (printbst t)
(cond
[(empty? t) (newline)]
[(and (empty? (BST-right t)) (empty? (BST-left t)))
(printf "~a~a" (indent (depth (BST-key t) t)) (BST-key t))]))
My printbst only prints a tree with one node thou .... i have an idea but it involves mutation, which i can't use :( ..... Any suggestions ? Should i change my approach to the problem all together?
Short answer: yes, you're going to want to restructure this more or less completely.
On the bright side, I like your indent function :)
The easiest way to write this problem involves making recursive calls on the subtrees. I hope I'm not giving away too much when I tell you that in order to print a subtree, there's one extra piece of information that you need.
...
Based on our discussion below, I'm going to first suggest that you develop the closely related recursive program that prints out the desired numbers with no indentation. So then the correct output would be:
6
5
4
3
2
1
Updating that program to the one that handles indentation is just a question of passing along a single extra piece of information.
P.S.: questions like this that produce output are almost impossible to write good test cases for, and consequently not great for homework. I hope for your sake that you have lots of other problems that don't involve output....

Resources