Pair GP polynomial operator - polynomial-math

There is trouble with PARI/GP. Does anyone know to operate the right function/command in PARI/GP, for fining the minimal polynomial of
[y = x^2-x+1 (mod x^6+x^5+x^4+x^3+x^2+x+1)]
PARI/GP gives this error:
gp > minpoly(x^6+x^5+x^4+x^3+x^2+x+1,{v=x^2-x+1})
*** at top-level: ...(x^6+x^5+x^4+x^3+x^2+x+1,v=x^2-x+1)
*** ^----------
*** incorrect type in evaluator [variable name expected] (t_INT).
Thanks for helping.
I also try:
(11:36) gp > elt = Mod(x^2-x+1, x^6+x^5+x^4+x^3+x^2+x+1)
%52 = Mod(43, 39991)
(11:36) gp > poly = minpoly(elt, v='y)
%53 = Mod(1, 39991)*y + Mod(39948, 39991)
(11:36) gp > subst(poly, variable(poly), elt)
%54 = Mod(0, 39991)
(11:36) gp >
Is this supposed to be a script?

In fact, you want the following call:
elt = Mod('x^2-'x+1, 'x^6+'x^5+'x^4+'x^3+'x^2+'x+1)
poly = minpoly(elt, v='y)
gp > y^6 - 6*y^5 + 15*y^4 - 20*y^3 + 22*y^2 - 6*y + 1
Just to verify:
subst(poly, variable(poly), elt)
gp > 0
Parameter v for minpoly just stands for the variable name, not the modulo.

Related

Using the GPU with Lux and NeuralPDE Julia

I am trying to run a model using the GPU, no problem with the CPU. I think somehow using measured boundary conditions is causing the issue but I am not sure. I am following this example: https://docs.sciml.ai/dev/modules/NeuralPDE/tutorials/gpu/. I am following this example for using measured boundary conditions: https://docs.sciml.ai/dev/modules/MethodOfLines/tutorials/icbc_sampled/
using Random
using NeuralPDE, Lux, CUDA, Random
using Optimization
using OptimizationOptimisers
using NNlib
import ModelingToolkit: Interval
using Interpolations
# Measured Boundary Conditions (Arbitrary For Example)
bc1 = 1.0:1:1001.0 .|> Float32
bc2 = 1.0:1:1001.0 .|> Float32
ic1 = zeros(101) .|> Float32
ic2 = zeros(101) .|> Float32;
# Interpolation Functions Registered as Symbolic
itp1 = interpolate(bc1, BSpline(Cubic(Line(OnGrid()))))
up_cond_1_f(t::Float32) = itp1(t)
#register_symbolic up_cond_1_f(t)
itp2 = interpolate(bc2, BSpline(Cubic(Line(OnGrid()))))
up_cond_2_f(t::Float32) = itp2(t)
#register_symbolic up_cond_2_f(t)
itp3 = interpolate(ic1, BSpline(Cubic(Line(OnGrid()))))
init_cond_1_f(x::Float32) = itp3(x)
#register_symbolic init_cond_1_f(x)
itp4 = interpolate(ic2, BSpline(Cubic(Line(OnGrid()))))
init_cond_2_f(x::Float32) = itp4(x)
#register_symbolic init_cond_2_f(x);
# Parameters and differentials
#parameters t, x
#variables u1(..), u2(..)
Dt = Differential(t)
Dx = Differential(x);
# Arbitrary Equations
eqs = [Dt(u1(t, x)) + Dx(u2(t, x)) ~ 0.,
Dt(u1(t, x)) * u1(t,x) + Dx(u2(t, x)) + 9.81 ~ 0.]
# Boundary Conditions with Measured Data
bcs = [
u1(t,1) ~ up_cond_1_f(t),
u2(t,1) ~ up_cond_2_f(t),
u1(1,x) ~ init_cond_1_f(x),
u2(1,x) ~ init_cond_2_f(x)
]
# Space and time domains
domains = [t ∈ Interval(1.0,1001.0),
x ∈ Interval(1.0,101.0)];
# Neural network
input_ = length(domains)
n = 10
chain = Chain(Dense(input_,n,NNlib.tanh_fast),Dense(n,n,NNlib.tanh_fast),Dense(n,4))
strategy = GridTraining(.25)
ps = Lux.setup(Random.default_rng(), chain)[1]
ps = ps |> Lux.ComponentArray |> gpu .|> Float32
discretization = PhysicsInformedNN(chain,
strategy,
init_params=ps)
# Model Setup
#named pdesystem = PDESystem(eqs,bcs,domains,[t,x],[u1(t, x),u2(t, x)])
prob = discretize(pdesystem,discretization);
sym_prob = symbolic_discretize(pdesystem,discretization);
# Losses and Callbacks
pde_inner_loss_functions = sym_prob.loss_functions.pde_loss_functions
bcs_inner_loss_functions = sym_prob.loss_functions.bc_loss_functions
callback = function (p, l)
println("loss: ", l)
println("pde_losses: ", map(l_ -> l_(p), pde_inner_loss_functions))
println("bcs_losses: ", map(l_ -> l_(p), bcs_inner_loss_functions))
return false
end;
# Train Model (Throws Error)
res = Optimization.solve(prob,Adam(0.01); callback = callback, maxiters=5000)
phi = discretization.phi;
I get the following error:
GPU broadcast resulted in non-concrete element type Union{}.
This probably means that the function you are broadcasting contains an error or type instability.
Please Advise.

this python program guess a random number, how to calculate the average numberguesses?

import random
i went to add another function to calculate the number guesses
def guess(x):
randomNumb = random.randint(1, x)
guess = 0
while guess != randomNumb :
guess = int(input(f'entre number between 1 and {x} : '))
print(guess)
if guess < randomNumb :
print('guess is low')
elif guess > randomNumb :
print('guess is high')
print(f'guess is right {randomNumb}')
guess(100)

How to generate arbitrary instances of a language given its concrete syntax in Rascal?

Given the concrete syntax of a language, I would like to define a function "instance" with signature str (type[&T]) that could be called with the reified type of the syntax and return a valid instance of the language.
For example, with this syntax:
lexical IntegerLiteral = [0-9]+;
start syntax Exp
= IntegerLiteral
| bracket "(" Exp ")"
> left Exp "*" Exp
> left Exp "+" Exp
;
A valid return of instance(#Exp) could be "1+(2*3)".
The reified type of a concrete syntax definition does contain information about the productions, but I am not sure if this approach is better than a dedicated data structure. Any pointers of how could I implement it?
The most natural thing is to use the Tree data-type from the ParseTree module in the standard library. It is the format that the parser produces, but you can also use it yourself. To get a string from the tree, simply print it in a string like so:
str s = "<myTree>";
A relatively complete random tree generator can be found here: https://github.com/cwi-swat/drambiguity/blob/master/src/GenerateTrees.rsc
The core of the implementation is this:
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
Tree randomTree(type[Tree] gr)
= randomTree(gr.symbol, 0, toMap({ <s, p> | s <- gr.definitions, /Production p:prod(_,_,_) <- gr.definitions[s]}));
Tree randomTree(\char-class(list[CharRange] ranges), int rec, map[Symbol, set[Production]] _)
= randomChar(ranges[arbInt(size(ranges))]);
default Tree randomTree(Symbol sort, int rec, map[Symbol, set[Production]] gr) {
p = randomAlt(sort, gr[sort], rec);
return appl(p, [randomTree(delabel(s), rec + 1, gr) | s <- p.symbols]);
}
default Production randomAlt(Symbol sort, set[Production] alts, int rec) {
int w(Production p) = rec > 100 ? p.weight * p.weight : p.weight;
int total(set[Production] ps) = (1 | it + w(p) | Production p <- ps);
r = arbInt(total(alts));
count = 0;
for (Production p <- alts) {
count += w(p);
if (count >= r) {
return p;
}
}
throw "could not select a production for <sort> from <alts>";
}
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
It is a simple recursive function which randomly selects productions from a reified grammar.
The trick towards termination lies in the weight of each rule. This is computed a priori, such that every rule has its own weight in the random selection. We take care to give the set of rules that lead to termination at least 50% chance of being selected (as opposed to the recursive rules) (code here: https://github.com/cwi-swat/drambiguity/blob/master/src/Termination.rsc)
Grammar terminationWeights(Grammar g) {
deps = dependencies(g.rules);
weights = ();
recProds = {p | /p:prod(s,[*_,t,*_],_) := g, <delabel(t), delabel(s)> in deps};
for (nt <- g.rules) {
prods = {p | /p:prod(_,_,_) := g.rules[nt]};
count = size(prods);
recCount = size(prods & recProds);
notRecCount = size(prods - recProds);
// at least 50% of the weight should go to non-recursive rules if they exist
notRecWeight = notRecCount != 0 ? (count * 10) / (2 * notRecCount) : 0;
recWeight = recCount != 0 ? (count * 10) / (2 * recCount) : 0;
weights += (p : p in recProds ? recWeight : notRecWeight | p <- prods);
}
return visit (g) {
case p:prod(_, _, _) => p[weight=weights[p]]
}
}
#memo
rel[Symbol,Symbol] dependencies(map[Symbol, Production] gr)
= {<delabel(from),delabel(to)> | /prod(Symbol from,[_*,Symbol to,_*],_) := gr}+;
Note that this randomTree algorithm will not terminate on grammars that are not "productive" (i.e. they have only a rule like syntax E = E;
Also it can generate trees that are filtered by disambiguation rules. So you can check this by running the parser on a generated string and check for parse errors. Also it can generated ambiguous strings.
By the way, this code was inspired by the PhD thesis of Naveneetha Vasudevan of King's College, London.

How to convert a Maple expression x*y to Matlab for the result x.*y?

A Maple expression (for example, x^3+x*y) can be converted to Matlab by
with(CodeGeneration):
Matlab(x^3+x*y);
However, in Matlab, there are two kinds of product: A*B and A.*B. The above way will give x^3+x*y. Is there a convenient way to get the result x.^3+x.*y?
The language definition for Maple's CodeGeneration[Matlab] can be extended to handle various instances of the elementwise tilde (~) operator.
Since 'x*~y' seems to automatically simplify to `~`[`*`](x, ` $`, y), and since there appears to be a hard-coded error emitted by the presence of the name " $", then that name is substituted by NULL in the usage code below.
> restart:
> with(CodeGeneration): with(LanguageDefinition):
> LanguageDefinition:-Define("NewMatlab", extend="Matlab",
> AddFunction("`~`[`^`]", [Vector,integer]::Vector,
> proc(X,Y)
> Printer:-Print(X,".^",Y)
> end proc,
> numeric=double),
> AddFunction("`~`[`*`]", [Vector,integer]::Vector,
> proc(X,Y)
> Printer:-Print(X,".*",Y)
> end proc,
> numeric=double));
> expr:=''x^~y + x^~3 + x*~y'':
> Translate(subs(` $`=NULL, expr ), language="NewMatlab");
cg = x.^y + x.^3 + x.*y;
> p := proc(x,y)
> x^~y + x^~3 + x*~y;
> end proc:
> f := subs(` $`=NULL, eval(p) ):
> Translate(f, language="NewMatlab");
function freturn = f(x, y)
freturn = x.^y + x.^3 + x.*y;
For whatever it's worth, Maple 2015 can do this translation directly, without the extra help kindly provided by acer:
> f := (x,y)->x^~y + x^~3 + x*~y:
> CodeGeneration:-Matlab(f);
function freturn = f(x, y)
freturn = x .^ y + x .^ 3 + x .* y;
If the Matlab(x^3+x*y) expression gives out the code x^3+x*y in written format, then you can simply convert it into x.^3+x.y , just by using "Find & Replace" option of any notepad application. Just find all "" and "^" , and then replace them with ".*" and ".^" .
Hope this helps.

Error attempting to use initial conditions

I'm doing a quick problem in Maple with a differential equation and a few initial conditions, but I'm getting an error message that I can't seem to understand given the context. Can anyone quickly elaborate on what's going on here? How do I fix this issue?
> KVLl2 := -4*(i2(t)-2)-12*(i2(t)-i3(t)) = 0;
-16 i2(t) + 8 + 12 i3(t) = 0
> KVLl3 := -12*(i3(t)-i2(t))-4*i3(t)-3.5*(diff(i3(t), t)) = 0;
/ d \
-16 i3(t) + 12 i2(t) - 3.5 |--- i3(t)| = 0
\ dt /
> mySoln := dsolve({KVLl2, KVLl3, i2(0) = 1, i3(0) = 1}, i2, i3);
Error, (in dsolve) found the following equations not depending
on the unknowns of the input system: {1 = 1}
Thanks in advance
Maple doesn't know what to do with i2 and i3 you provided as target functions. If you look at the help of dsolve (?dsolve), you see that it requires its target functions to be specified in terms of their variables (t in this case) and as a list. Try using this
dsolve({KVLl2, KVLl3, i2(0) = 1, i3(0) = 1}, {i2(t), i3(t)});
No errors here but no solution either (this might be related to your equation)