How to create in Sage system of equations using elements from boolean field - equation

I want to create a field on 8 elements, and then, using this elements make a System of equations like:
nb = 8
varl = [c+ str(p) for c in 'xy' for p in range (nb)]
B = BooleanPolynomialRing(names = varl)
f1 = x1 + x7*x2
f2 = x4*x6*x8 + x7
and then....
But in this case Sage give me an error
NameError: name 'x1' is not defined
And in this case:
f1 = x[3] + x[1]*x[2]
f2 = x[4]*x[6]*x[2] + x[7]
error:
TypeError: 'sage.symbolic.expression.Expression' object does not support indexing

Once B is defined as in the question, its variables have a "display name"
but no "call name", i.e. they display as x0, x2, ..., x7
and y1, y2, ..., y7, but we have not told Sage we would
also like to be able to call them by typing x0, x2, ..., x7
and y1, y2, ..., y7.
One way to make this possible is to run:
sage: B.inject_variables()
after which we can run the following with no error:
sage: f1 = x1 + x7*x2
Beware for f2 though: the code in the question defines
x0 to x7 but no x8.

Related

Solve for the coefficients of (functions of) the independent variable in a symbolic equation

Using Octave's symbolic package, I define a symbolic function of t like this:
>> syms a b c d t real;
>> f = poly2sym([a b c], t) + d * exp(t)
f = (sym)
2 t
a⋅t + b⋅t + c + d⋅ℯ
I also have another function with known coefficients:
>> g = poly2sym([2 3 5], t) + 7 * exp(t)
g = (sym)
2 t
2⋅t + 3⋅t + 7⋅ℯ + 5
I would like to solve f == g for the coefficients a, b, c, d such that the equation holds for all values of t. That is, I simply want to equate the coefficients of t^2 in both equations, and the coefficients of exp(t), etc. I am looking for this solution:
a = 2
b = 3
c = 5
d = 7
When I try to solve the equation using solve, this is what I get:
>> solve(f == g, a, b, c, d)
ans = (sym)
t 2 t
-b⋅t - c - d⋅ℯ + 2⋅t + 3⋅t + 7⋅ℯ + 5
───────────────────────────────────────
2
t
It solves for a in terms of b, c, d, t. This is understandable since in essence there is no difference between the variables b, c and t. But I was wondering if there was a method to somehow separate the terms (using their symbolic form w. r. t. the variable t) and solve the resulting system of linear equations on a, b, c, d.
Note: The function I wrote here is a minimal example. What I am really trying to do is to solve a linear ordinary differential equation using the method of undetermined coefficients. For example, I define something like y = a*exp(-t) + b*t*exp(-t), and solve for diff(y, t, t) + diff(y,t) + y == t*exp(-t). But I believe solving the problem with simpler functions will lead me to the right direction.
I have found a terribly slow and dirty method to get the job done. The coefficients have to be linear in a, b, ... though.
The idea is to follow these steps:
Write the equation in f - g form (which equals zero)
Use expand() to separate the terms
Use children() to get the terms in the equation as a symbolic vector
Now that we have the terms in a vector, we can find those that are the same function of t and add their coefficients together. The way I checked this was by checking if the division of two terms had t as a symbolic variable
For each term, find other terms with the same function of t, add all these coefficients together, save the obtained equation in a vector
Pass the vector of created equations to solve()
This code solves the equation I wrote in the note at the end of my question:
pkg load symbolic
syms t a b real;
y = a * exp(-t) + b * t * exp(-t);
lhs = diff(y, t, t) + diff(y, t) + y;
rhs = t * exp(-t);
expr = expand(lhs - rhs);
chd = children(expr);
used = false(size(chd));
equations = [];
for z = 1:length(chd)
if used(z)
continue
endif
coefficients = 0;
for zz = z + 1:length(chd)
if used(zz)
continue
endif
division = chd(zz) / chd(z);
vars = findsymbols(division);
if sum(has(vars, t)) == 0 # division result has no t
used(zz) = true;
coefficients += division;
endif
endfor
coefficients += 1; # for chd(z)
vars = findsymbols(chd(z));
nott = vars(!has(vars, t));
if length(nott)
coefficients *= nott;
endif
equations = [equations, expand(coefficients)];
endfor
solution = solve(equations == 0);

AttributeError: 'NoneType' object has no attribute 'zero_'

The Grad sub object becomes "None" if expand the expression. Not sure why? Can somebody give some clue.
If expand the w.grand.zero_() throw error as "AttributeError: 'NoneType' object has no attribute 'zero_'"
Thanks,
Ganesh
import torch
x = torch.randint(size = (1,2), high = 10)
w = torch.Tensor([16,-14])
b = 36
y = w * x + b
epoch = 20
learning_rate = 0.01
w1 = torch.rand(size= (1,2), requires_grad= True)
b1 = torch.ones(size = [1], requires_grad= True)
for i in range(epoch):
y1 = w1 * x + b1
loss = torch.sum((y1-y)**2)
loss.backward()
with torch.no_grad():
#w1 = w1 - learning_rate * w1.grad //Not Working : w1.grad becomes "None" not sure how ;(
#b1 = b1 - learning_rate * b1.grad
w1 -= (learning_rate * w1.grad) // Working code.
b1 -= (learning_rate * b1.grad)
w1.grad.zero_()
b1.grad.zero_()
print("B ", b1)
print("W ", w1)
The thing is that in your working code you are modifying existing variable which has grad attribute, while in the non-working case you are creating a new variable.
As new w1/b1 variable is created it has no gradient attribute as you didn't call backward() on it, but on the "original" variable.
First, let's check whether that's really the case:
print(id(w1)) # Some id returned here
w1 = w1 - learning_rate * w1.grad
# In case below w1 address doesn't change
# w1 -= learning_rate * w1.grad
print(id(w1)) # Another id here
Now, you could copy it in-place and not brake it, but there is no point to do so and your working case is much clearer, but for posterity's sake:
w1.copy_(w1 - learning_rate * w1.grad)
The code you provided is updating the parameters w and b using gradient descent. In the first line, w.grad is the gradient of the loss function with respect to the parameter w and lr is the learning rate, a scalar value that determines the step size in the direction of the gradient.
The second line, b = b - b.grad * lr is updating the parameter b in the same way, by subtracting the gradient of the loss with respect to b multiplied by the learning rate.
However, the second line is incorrect, it should be b -= b.grad * lr instead of b = b - b.grad * lr
Using b = b - b.grad * lr would cause the parameter b to be re-assigned to the new value, but the original b would not be updated, therefore, the value of b would be None.
On the other hand, using b -= b.grad * lr will update the value of b in place, so the original b will be updated and its value will not be None.

Storing coefficients from a Regression in Stata

I am trying to store the coefficients from a simulated regression in a variable b1 and b2 in the code below, but I'm not quite sure how to go about this. I've tried using return scalar b1 = _b[x1] and return scalar b2 = _b[x2], from the rclass() function, but that didn't work. Then I tried using scalar b1 = e(x1) and scalar b2 = e(x2), from the eclass() function and also wasn't successful.
The goal is to use these stored coefficients to estimate some value (say rhat) and test the standard error of rhat.
Here's my code below:
program montecarlo2, eclass
clear
version 11
drop _all
set obs 20
gen x1 = rchi2(4) - 4
gen x2 = (runiform(1,2) + 3.5)^2
gen u = 0.3*rnormal(0,25) + 0.7*rnormal(0,5)
gen y = 1.3*x1 + 0.7*x2 + 0.5*u
* OLS Model
regress y x1 x2
scalar b1 = e(x1)
scalar b2 = e(x2)
end
I want to do something like,
rhat = b1 + b2, and then test the standard error of rhat.
Let's hack a bit at your program:
Version 1
program montecarlo2
clear
version 11
set obs 20
gen x1 = rchi2(4) - 4
gen x2 = (runiform(1,2) + 3.5)^2
gen u = 0.3*rnormal(0,25) + 0.7*rnormal(0,5)
gen y = 1.3*x1 + 0.7*x2 + 0.5*u
* OLS Model
regress y x1 x2
end
I cut drop _all as unnecessary given the clear. I cut the eclass. One reason for doing that is the regress will leave e-class results in its wake any way. Also, you can if you wish add
scalar b1 = _b[x1]
scalar b2 = _b[x2]
scalar r = b1 + b2
either within the program after the regress or immediately after the program runs.
Version 2
program montecarlo2, eclass
clear
version 11
set obs 20
gen x1 = rchi2(4) - 4
gen x2 = (runiform(1,2) + 3.5)^2
gen u = 0.3*rnormal(0,25) + 0.7*rnormal(0,5)
gen y = 1.3*x1 + 0.7*x2 + 0.5*u
* OLS Model
regress y x1 x2
* stuff to add
end
Again, I cut drop _all as unnecessary given the clear. Now the declaration eclass is double-edged. It gives the programmer scope for their program to save e-class results, but you have to say what they will be. That's the stuff to add indicated by a comment above.
Warning: I've tested none of this. I am not addressing the wider context. #Dimitriy V. Masterov's suggestion of lincom is likely to be a really good idea for whatever your problem is.

Failing to solve a simple ODE with Octave

I am new to Octave, so I am trying to make some simple examples work before moving onto more complex projects.
I am trying to resolve the ODE dy/dx = a*x+b, but without success. Here is the code:
%Funzione retta y = a*x + b. Ingressi: vettore valori t; coefficienti a,b
clear all;
%Inizializza argomenti
b = 1;
a = 1;
x = ones(1,20);
function y = retta(a, x, b) %Definisce funzione
y = ones(1,20);
y = a .* x .+ b;
endfunction
%Calcola retta
x = [-10:10];
a = 2;
b = 2;
r = retta(a, x, b)
c = b;
p1 = (a/2)*x.^2+b.*x+c %Sol. analitica di dy/dx = retta %
plot(x, r, x, p1);
% Risolve eq. differenziale dy/dx = retta %
y0 = b; x0 = 0;
p2 = lsode(#retta, y0, x)
And the output is:
retta3code
r =
-18 -16 -14 -12 -10 -8 -6 -4 -2 0 2 4 6 8 10 12 14 16 18 20 22
p1 =
Columns 1 through 18:
82 65 50 37 26 17 10 5 2 1 2 5 10 17 26 37 50 65
Columns 19 through 21:
82 101 122
error: 'b' undefined near line 9 column 16
error: called from:
error: retta at line 9, column 4
error: lsode: evaluation of user-supplied function failed
error: lsode: inconsistent sizes for state and derivative vectors
error: /home/fabio/octave_file/retta3code.m at line 21, column 4
So, the function retta works properly the first time, but it fails when used in lsode.
Why does that happen? What needs to be changed to make the code work?
Somehow you still miss some important parts of the story. To solve an ODE y'=f(y,x) you need to define a function
function ydot = f(y,x)
where ydot has the same dimensions as y, both have to be vectors, even f they are of dimension 1. x is a scalar. For some traditional reason, lsode (a FORTRAN code used in multiple solver packages) prefers the less used order (y,x), in most text books and other solvers you find the order (x,y).
Then to get solution samples ylist over sample points xlist you call
ylist = lsode("f", y0, xlist)
where xlist(1) is the initial time.
The internals of f are independent of the sample list list and what size it has. It is a separate issue that you can use multi-evaluation to compute the exact solution with something like
yexact = solexact(xlist)
To pass parameters, use anonymous functions, like in
function ydot = f(y,x,a,b)
ydot = [ a*x+b ]
end
a_val = ...
b_val = ...
lsode(#(y,x) f(y,x,a_val, b_val), y0, xlist)
The code as modified below works, but I'd prefer to be able to define the parameters a and b out of the function and then pass them to rdot as arguments.
x = [-10,10];
a = 1;
b = 0;
c = b;
p1 = (a/2).*(x.^2)+b.*x+c %Sol. analitica di dy/dx = retta %
function ydot = rdot(ydot, x)
a = 1;
b = 0;
ydot = ones(1,21);
ydot = a.*x .+ b;
endfunction
y0 = p1(1); x0 = 0;
p2 = lsode("rdot", y0, x, x0)'
plot(x, p1, "-k", x, p2, ".r");

Math - Get x & y coordinates at intervals along a line

I'm trying to get x and y coordinates for points along a line (segment) at even intervals. In my test case, it's every 16 pixels, but the idea is to do it programmatically in ActionScript-3.
I know how to get slope between two points, the y intercept of a line, and a2 + b2 = c2, I just can't recall / figure out how to use slope or angle to get a and b (x and y) given c.
Does anyone know a mathematical formula to figure out a and b given c, y-intercept and slope (or angle)? (AS3 is also fine.)
You have a triangle:
|\ a^2 + b^2 = c^2 = 16^2 = 256
| \
| \ c a = sqrt(256 - b^2)
a | \ b = sqrt(256 - a^2)
| \
|__________\
b
You also know (m is slope):
a/b = m
a = m*b
From your original triangle:
m*b = a = sqrt(256 - b^2)
m^2 * b^2 = 256 - b^2
Also, since m = c, you can say:
m^2 * b^2 = m^2 - b^2
(m^2 + 1) * b^2 = m^2
Therefore:
b = m / sqrt(m^2 + 1)
I'm lazy so you can find a yourself: a = sqrt(m^2 - b^2)
Let s be the slop.
we have: 1) s^2 = a^2/b^2 ==> a^2 = s^2 * b^2
and: 2) a^2 + b^2 = c^2 = 16*16
substitute a^2 in 2) with 1):
b = 16/sqrt(s^2+1)
and
a = sqrt((s^2 * 256)/(s^2 + 1)) = 16*abs(s)/sqrt(s^2+1)
In above, I assume you want to get the length of a and b. In reality, your s is a signed value, so a could be negative. Therefore, the incremental value of a will really be:
a = 16s/sqrt(s^2+1)
The Point class built in to Flash has a wonderful set of methods for doing exactly what you want. Define the line using two points and you can use the "interpolate" method to get points further down the line automatically, without any of the trigonometry.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/Point.html#interpolate()
The Slope is dy/dx. Or in your terms A/B.
Therefore you can step along the line by adding A to the Y coordinate, and B to the X coordinate. You can Scale A and B to make the steps bigger or smaller.
To Calculate the slope and get A and B.
Take two points on the line (X1,Y1) , (X2,Y2)
A= (Y2-Y1)
B= (X2-X1)
If you calculate this with the two points you want to iterate between simply divide A and B by the number of steps you want to take
STEPS=10
yStep= A/STEPS
xStep= B/STEPS
for (i=0;i<STEPS;i++)
{
xCur=x1+xStep*i;
yCur=y1+yStep*i;
}
Given the equation for a line as y=slope*x+intercept, you can simply plug in the x-values and read back the y's.
Your problem is computing the step-size along the x-axis (how big a change in x results from a 16-pixel move along the line, which is b in your included plot). Given that you know a^2 + b^2 = 16 (by definition) and slope = a/b, you can compute this:
slope = a/b => a = b * slope [multiply both sides by b]
a^2 + b^2 = 16 => (b * slope)^2 + b^2 = 16 [by substitution from the previous step]
I'll leave it to you to solve for b. After you have b you can compute (x,y) values by:
for x = 0; x += b
y = slope * x + intercept
echo (x,y)
loop