Getting the state of variables after an error occurs in R - debugging

Let's say I have just called a function, f, and an error occurred somewhere in the function. I just want to be able to check out the values of different variables right before the error occurred.
Suppose my gut tells me it's a small bug, so I'm too lazy to use debug(f) and too lazy to insert browser() into the part of the function where I think things are going wrong. And I'm far too lazy to start putting in print() statements.
Here's an example:
x <- 1:5
y <- x + rnorm(length(x),0,1)
f <- function(x,y) {
y <- c(y,1)
lm(y~x)
}
Calling f(x,y) we get the following error:
Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) :
variable lengths differ (found for 'x')
In this example, I want grab the state of the environment just before lm() is called; that way I can call x and y and see that their lengths are different. (This example may be too simple, but I hope it gets the idea across.)

As pointed out here, there's an easy way to do this, and I think this trick has the potential to change lives for the better.
First, call this:
options(error=recover)
Now when we call f(x,y) we will have an option to choose an environment to recover. Here I select option 1, which opens up a debugger and lets me play around with variables just before lm() is called.
> f(x,y)
Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) :
variable lengths differ (found for 'x')
Enter a frame number, or 0 to exit
1: f(x, y)
2: lm(y ~ x)
3: eval(mf, parent.frame())
4: eval(expr, envir, enclos)
5: model.frame(formula = y ~ x, drop.unused.levels = TRUE)
6: model.frame.default(formula = y ~ x, drop.unused.levels = TRUE)
Selection: 1
Called from: eval(expr, envir, enclos)
Browse[1]> x
[1] 1 2 3 4 5
Browse[1]> y
[1] 1.6591197 0.5939368 4.3371049 4.4754027 5.9862130 1.0000000

You could also just use the debug() function:
> debug(f)
> f(x,y)
debugging in: f(x, y)
debug: {
y <- c(y, 1)
lm(y ~ x)
}
Browse[1]>
debug: y <- c(y, 1)
Browse[1]> x
[1] 1 2 3 4 5
Browse[1]> y
[1] 2.146553 2.610003 2.869081 2.758753 4.433881

options(error=recover)
Probably answers the question best. However, I wanted to mention another handy debugging tool, traceback(). Calling this right after an error has occurred is often enough to pinpoint the bug.

Related

PROLOG Asignation problems

I have to solve a problem involving the WWESupercard game. The idea is to to take 2 cards and make them fight, comparing each stat alone and every combination, making 10 comparations in total. A fighter wins if it gets more than 50% of the fights (6/10).
The problem I have is that the "is" statement is not working for me.
This are some of the "solutions" I've tried so far, using only the base stats and no combinations for faster testing, none of them are working as I intend:
leGana(X,Y) :- T is 0,
((A is 0, (pwr(X,Y) -> A1 is A+1));
(B is 0, (tgh(X,Y) -> B1 is B+1));
(C is 0, (spd(X,Y) -> C1 is C+1));
(D is 0, (cha(X,Y) -> D1 is D+1))),
T1 is T+A1+B1+C1+D1, T1 > 2.
leGana(X,Y) :- T is 0,
((pwr(X,Y) -> T is T+1);
(tgh(X,Y) -> T is T+1);
(spd(X,Y) -> T is T+1);
(cha(X,Y) -> T is T+1)),
T1 > 2.
I've tried other ways, but I keep getting the same 2 error, most of the times:
It fails on "T is T+1" saying "0 is 0+1" and failing
On example 1, it does the "A1 is A+1", getting "1 is 0+1", but then it jumps directly to the last line of the code, getting "T1 is 0+1+_1543+_1546 ..."
Also, sorry if the way I wrote the code is not correct, it's my first time asking for help here, so any advice is welcome.
Prolog is a declarative language, which means that a variable can only have a single value.
If you do this:
X is 1, X is 2.
it will fail because you're trying to say that X has both the value 1 and the value 2, which is impossible ... that is is is not assignment but a kind of equality that evaluates the right-hand side.
Similarly
X = 1, X = 2.
will fail.
If you want to do the equivalent of Python's
def f(x):
result = 1
if x == 0:
result += 1
return result
then you need to do something like this:
f(X, Result) :-
Result1 = 1,
( X = 0
-> Result is Result1 + 1
; Result = Result1
).

Retrieve method content as an `Expr`ession

I have a function f defined as follows.
f(x, y) = 3x^2 + x*y - 2y + 1
How can I retrieve the following quote block for this method, which includes the function contents?
quote # REPL[0], line 2:
((3 * x ^ 2 + x * y) - 2y) + 1
end
As folks have mentioned in the comments, digging through the fields of the methods like this isn't a stable or officially supported API. Further, your simple example is deceiving. This isn't, in general, representative of the original code you wrote for the method. It's a simplified intermediate AST representation with single-assignment variables and drastically simplified control flow. In general, the AST it returns isn't valid top-level Julia code. It just so happens that for your simple example, it is.
That said, there is a documented way to do this. You can use code_lowered() to get access to this intermediate representation without digging through undocumented fields. This will work across Julia versions, but I don't think there are official guarantees on the stability of the intermediate representation yet. Here's a slightly more complicated example:
julia> f(X) = for elt in X; println(elt); end
f (generic function with 1 method)
julia> code_lowered(f)[1]
LambdaInfo template for f(X) at REPL[17]:1
:(begin
nothing
SSAValue(0) = X
#temp# = (Base.start)(SSAValue(0))
4:
unless !((Base.done)(SSAValue(0),#temp#)) goto 13
SSAValue(1) = (Base.next)(SSAValue(0),#temp#)
elt = (Core.getfield)(SSAValue(1),1)
#temp# = (Core.getfield)(SSAValue(1),2) # line 1:
(Main.println)(elt)
11:
goto 4
13:
return
end)
julia> code_lowered(f)[1] == methods(f).ms[1].lambda_template
true
If you really want to see the code exactly as it was written, the best way is to use the embedded file and line information and refer to the original source. Note that this is precisely the manner in which Gallium.jl (Julia's debugger) finds the source to display as it steps through functions. It's undocumented, but you can even access the REPL history for functions defined interactively. See how Gallium does it through here.
First, retrieve the method using methods(f).
julia> methods(f)
# 1 method for generic function "f":
f(x, y) at REPL[1]:1
julia> methods(f).ms
1-element Array{Method,1}:
f(x, y) at REPL[1]:1
julia> method = methods(f).ms[1]
f(x, y) at REPL[1]:1
From here, retrieving the Expression is straightforward; simply use the lambda_template attribute of the method.
julia> method.lambda_template
LambdaInfo template for f(x, y) at REPL[1]:1
:(begin
nothing
return ((3 * x ^ 2 + x * y) - 2 * y) + 1
end)
Edit: This does not work in Julia v0.6+!

Implications as functions in Coq?

I read that implications are functions. But I have a hard time trying to understand the example given in the above mentioned page:
The proof term for an implication P → Q is a function that takes
evidence for P as input and produces evidence for Q as its output.
Lemma silly_implication : (1 + 1) = 2 → 0 × 3 = 0. Proof. intros H.
reflexivity. Qed.
We can see that the proof term for the above lemma is indeed a
function:
Print silly_implication. (* ===> silly_implication = fun _ : 1 + 1 = 2
=> eq_refl
: 1 + 1 = 2 -> 0 * 3 = 0 *)
Indeed, it's a function. But its type does not look right to me. From my reading, the proof term for P -> Q should be a function with an evidence for Q as output. Then, the output of (1+1) = 2 -> 0*3 = 0 should be an evidence for 0*3 = 0, alone, right?
But the Coq print out above shows that the function image is eq_refl : 1 + 1 = 2 -> 0 * 3 = 0, instead of eq_refl: 0 * 3 = 0. I don't understand why the hypothesis 1 + 1 = 2 should appear in the output. Can anyone help explain what is going on here?
Thanks.
Your understanding is correct until:
But the Coq print out above shows that the function image is ...
I think you misunderstand the Print command. Print shows you the term associated with a definition, along with the type of the definition. It does not show the image/output of a function.
For example, the following prints the definition and type of the value x:
Definition x := 5.
Print x.
> x = 5
> : nat
Similarly, the following prints the definition and type of the function f:
Definition f := fun n => n + 2.
Print f.
> f = fun n : nat => n + 2
> : nat -> nat
If you want to see the function's codomain, you have to apply the function to a value, like so:
Definition fx := f x.
Print fx.
> fx = f x
> : nat
If you want to see the image/output of a function Print won't help you. What you need is Compute. Compute takes a term (e.g. a function application) and reduces it as far as possible:
Compute (f x).
> = 7
> : nat

is there a formula to get a term from nested loop?

I have a nested loop as follows :
xl = yl = [a for a in range(1,12)]
ll = [a for a in range(0,6)]
c = 0;
output = []
for x in xl:
for y in yl:
if (y > x):
for l in ll :
output.append("{0}-{1}-{2}".format(x,y,l));
c+=1;
Given a value of c which is the position of a certain term, I need to get the value of that term.
For example if c = 10, I need the 10th element of output.
it would be awesome if someone told could give me a generic formula for all nested loops.
I tried googling, but I don't even know what terms to google.
Well you have put the output into an array, so you can simply look at output[10].
As for the bigger problem that you are trying to solve, I believe that you want to learn about generators. Here is how you work with them. First you put your loop in a function, and call yield where you want and no return statement. Like so.
def loop_generator ():
xl = yl = [a for a in range(1,12)]
ll = [a for a in range(0,6)]
for x in xl:
for y in yl:
if (y > x):
for l in ll :
yield (x, y, 1)
Now x = loop_generator() will return a generator. This is an object that, every time you call next on it, will start running code in the function and will return the next point yield would be called. If you run out of yields it will raise the StopIteration exception.
So your code now can be finished off with:
my_generator = loop_generator()
# Throw away 9 values
for i in range(9):
next(my_generator)
# Get the one I want
x, y, l = next(my_generator)
# Show what I got.
print "{0}-{1}-{2}".format(x,y,l)
This strategy can be used to turn any nested loop into something that you can step through and pull values out of.
Incidentally Python's native looping constructs all know to call next and terminate cleanly on StopIteration so that the following works as you might hope:
for x, y, l in loop_generator():
print "{0}-{1}-{2}".format(x,y,l)

Obtain x as result for Re[x] in mathematica

I'm trying to obtain the real part of the result of an operation which involves an undefined variable (let's say x).
How can I have Mathematica return x when I execute Re[x] if I know that x will never be a complex number? I think this involves telling Mathematica that x is a real, but I don't know how.
In my case the expression for which I want the real part is more complicated than a simple variable, but the concept will remain the same.
Some examples:
INPUT OUTPUT DESIRED RESULT
----- ------ --------------
Re[x] Re[x] x
Re[1] 1 1
Re[Sin[x]] Re[Sin[x]] Sin[x]
Re[1+x+I] 1 + Re[x] 1+x
Re[1 + x*I] 1-Im[x] 1
You can use for example the input Simplify[Re[x], x \[Element] Reals] which will give x as output.
Use ComplexExpand. It assumes that the variables are real unless you indicate otherwise. For example:
In[76]:= ComplexExpand[Re[x]]
Out[76]= x
In[77]:= ComplexExpand[Re[Sin[x]]]
Out[77]= Sin[x]
In[78]:= ComplexExpand[Re[1+x+I]]
Out[78]= 1+x
Two more possibilities:
Assuming[x \[Element] Reals, Refine[Re[x]]]
Refine[Re[x], x \[Element] Reals]
Both return x.
It can at times be useful to define UpValues for a symbol. This is far from robust, but it nevertheless can handle a number of cases.
Re[x] ^= x;
Im[x] ^= 0;
Re[x]
Re[1]
Re[1 + x + I]
Re[1 + x*I]
x
1
1 + x
1
Re[Sin[x]] does not evaluate as you desire, but one of the transformations used by FullSimplify does place it in a form that triggers Re[x]:
Re[Sin[x]] // FullSimplify
Sin[x]

Resources