Carl Love

## 26668 Reputation

11 years, 232 days
Himself
Wayland, Massachusetts, United States
My name was formerly Carl Devore.

## Statistics:-LinearFit...

Following the directions given on the Wikipedia page "Weibull distribution", section "Parameter estimation", subsection "Ordinary least square using Weibull plot", I only made a single small change to your computation: I changed (i - 0.5)/n to (i - 0.3)/(n + 0.4). Anything else that may appear to be a change is merely a mathematically equivalent simplification. Then I used Statistics:-LinearFit to do the regression.

 > restart :
 > St:= Statistics:
 > S:= -<-255.172, -235.249, -196.935, -132.567, -77.3946, -32.1839, -0.766284>;

 > n:= St:-Count(S);

 > lnpof:= map(i-> ln(-ln(1-(i-0.3)/(n+0.4))), St:-Rank(S)^+);

 > lnsigma:= ln~(S);

 > plot((data:= ), style= point);

 > PV:= St:-LinearFit([1, ln_x], data, ln_x, output= parametervector, summarize);

Summary:
----------------
Model: -2.4778919+.47999708*ln_x
----------------
Coefficients:
Estimate  Std. Error  t-value  P(>|t|)
Parameter 1   -2.4779    0.4212     -5.8834   0.0020
Parameter 2    0.4800    0.0931      5.1576   0.0036
----------------

 > k:= PV[2]; lambda:= exp(-PV[1]/k);

On the Maple help page ?Weibull, k is called c, and lambda is called b.

 > X:= St:-RandomVariable(Weibull(lambda,k)):
 > plot(St:-PDF(X,t), t= 0..9);

 >

## Mathematical vs. Syntactic equality...

This Answer is fundamentally the same as the one by @nm ; I just want to give some background information.

The command evalb, when applied to an equation, checks whether the two sides of the equation are syntactically identical; but you want to check whether the two sides are mathematically equivalent.

Two expressions are syntactically identical if they are stored in exactly the same way in the computer's memory. (In Maple, in practice, this means that only one copy is actually stored at all.) Via a process that Maple calls automatic simplification, some expressions which are typed in differently will become syntactically identical:

evalb(sin(a+b) = sin(b+a));

true

I think that you (and most other readers here) already understand basically what it means for two expressions to be mathematically equivalent. Let me try to be more precise (although this is still not a perfect definition): Two expressions are mathematically equivalent if they are numerically equal for all possible numeric substitutions of their variables for which they're both defined and which satisfy the "current assumptions". The "current assumptions", if unspecified, are all complex numbers. In Maple, assuming or assume can be used to specify assumptions.

Of course, if two expressions are syntactically identical they are also mathematically equivalent. But the converse isn't true. It can be proven (see Richardson's Theorem) that it's impossible to create a perfect algorithm to determine mathematical equivalence. So, whether you use isexpandsimplify, or numerous other commands, there will always be undecidable cases. However, one may hope that in the cases where the equivalence is already established via a well-known and elementary theorem (such as the case you present), Maple will be able to verify it. The best command to try first is is:

is(sin(x + y) = sin(x)*cos(y) + cos(x)*sin(y));
true

The reason that is is the best first choice is that it will give up and return FAIL if after some reasonable amount of time it cannot decide true or false. Other commands may run for an infeasible amount of time.

Regarding checking integrations: Suppose that f is the expression that you want to integrate (let's say with respect to x), and is your proposed antiderivative that you want to check. Then do

is(f = diff(F,x));

You may need to include assumptions on x. Appropriate assumptions are likely obvious. For example,

is(f = diff(F,x)) assuming x > -1, x < 1;

There's usually no need to exclude isolated singularities such as specific values of x that make a denominator 0.

Keep in mind that the default assumption in Maple is "all complex numbers", not "all real numbers". The calculus of functions of complex variables is sufficiently similar to that of real variables that you usually do not need to make the distinction.

## Complete extensively commented solution...

Level curves and orthogonal trajectories via numeric solution of an ODE

Author: Carl Love <carl.j.love@gmail.com>, 2024-May-24

 > restart :
 > interface(prompt= "") :

We are working with the level curves in the plane for this function:

F:= (x,y)-> x*y^2 - x^2 - y^2;

In other words, the curves specified implicitly by the equation

F(x,y) = k;

for any real constant k. Trajectories orthogonal to the level curves are important because they are the projections into the coordinate plane of the paths of steepest ascent/descent on the corresponding surface. Slopes of orthogonal trajectories are the negative reciprocals of the implicit derivative dy/dx, which we find by partial differentiation: dy/dx = - (dF/dx)/(dF/dy), so the orthogonal direction is (dF/dy)/(dF/dx). An unknown (aka dependent) function needs to be expressed "as a function of" its independent variable (x in this case). In other words (i.e., without symbolic-computation jargon), we need to change y to y(x).

Tj_ode:= diff(y(x),x) = (D[2]/D[1])(F)(x, y(x));

Note that when using D operator for partial derivatives, you don't specify the differentiation variable directly; instead, you specify its position in the function's argument sequence. So, D[2] is the derivative with respect to (w.r.t.) y, and D[1] is w.r.t. x.

 >

It's reasonable to guess that Maple can solve this ODE symbolically, but it can't do it directly:

dsolve(Tj_ode);

The NULL response to the above command shows that Maple cannot solve it symbolically, unless, perhaps some other options are given. I choose not to pursue that possibility, because a numeric solve is totally adequate for this.

I name the starting point (x0, y0) and ask dsolve to construct a numeric solver for this generic starting point:

Tj_sol:= dsolve({Tj_ode, y(x0)=y0}, numeric, parameters= [x0, y0]);

Note that the order in which I specified the parameters will be important later. Maple's cryptic response to the above command simply means everything is fine and the numeric colver has been constructed.

Get a 2D contour plot, choosing somewhat arbitrary ranges for x and y:

plots:-contourplot(
(Cspec:= (F(x,y):= lhs(C)), (x_rng:= x= -2..2), (y_rng:= y= -2..2))
);

The color bar shows the value of k for the level curve of the corresponding color.  The color bar clutters the final plot (IMO), so I remove it, and I add some additional k values to fill in the center. Suitable values of k can be guessed by mosuing over the above plot (clickiing on any level curve shows its k value).

Cplot:= plots:-contourplot(
(Cspec:= Cspec, 'contours'= [seq(-0.4..-2, -0.4), seq(-3..-15, -2)]),
'colorbar'= false, thickness= 0.7
);

Even without the color bar, clicking on level curves still shows their k values.

A 3D-plot will help with understanding what a "steepest path" means:

surf_plot:= plot3d(Cspec, 'style'= 'surfacecontour', 'transparency'= 0.3);

Make up any two starting points (there's no limit on how many points you use), and record the count of them for convenience:

Pts:= [[-1, 1/2], [1, -1]]:
npts:= nops(Pts);

Plot the orthogonal trajectories in the coordinate plane:

plots:-display(  #command to merge plots
Cplot,
(
#Iterate over Pts, setting P= [x0, y0] and setting j to the numeric
#position of P in Pts:
for j,P in Pts do
Tj_sol('parameters'= P);  #Reset 'parameters' for each point.
plots:-odeplot(  #plotter for numeric dsolve solutions
Tj_sol, [x,y(x)], x_rng,
'thickness'= 3, 'linestyle'= 'dash',
#Use pure chromatic colors ("HUEs") evenly spaced on the
#visible spectrum:
'color'= 'COLOR'('HUE', 0.86*(j-1)/npts),
'legend'= 'typeset'(
``(x[0],y[0]) = P[],
#Punctuate _between_ legends, but not at end:
`if`(j<npts, ";   ", "")
)
)
od
),
'view'= rhs~([x_rng, y_rng]),
#Scale so that right-angle intersections display "true":
'scaling'= 'constrained',
'title'= 'typeset'(
"Level curves of ", F(x,y), "and some orthogonal trajectories"
),
'titlefont'= ['TIMES', 'BOLD', 16],
'caption'= "trajectories for starting points",
'captionfont'= ['TIMES', 14],
'size'= [800\$2]  #800x800 pixels
);

By doing essentially the same thing, we can plot the corresponding "steepest-descent paths" on the surface

plots:-display(
surf_plot,
(
for j,P in Pts do
Tj_sol('parameters'= P);
plots:-odeplot(
Tj_sol, [x,y(x),F(x,y(x))], x_rng,
'thickness'= 2, 'color'= 'COLOR'('HUE', 0.86*(j-1)/npts)
)
od
),
'view'= [rhs~([x_rng, y_rng])[], -16..0]
);

 >

## Environment variables; kernelopts(level)...

printlevel is an "environment variable". That means that if its value is changed within a procedure, then it is automatically reset to its previous value when the procedure exits. Thus, you don't need to store the previous value or reset printlevel yourself.

What you're calling the "depth" can be measured by kernelopts(level).

## Limitations of assuming...

I ignore your weird use of RETURN. Without it, the second integral gives true*x, whereas I'd expect false*x. There are reasonable limitations on the "depth" within an expression to which assuming can penetrate. Compare:

(coulditbe(y=1) assuming y>=0, y<=x) assuming additionally, x>0, x<1;

true

coulditbe(y=1) assuming y>=0, y<=x, x>0, x<1;

false

The first case seems more akin to your integral.

## ListTools:-Classify...

Your graph_list can be partitioned into a table of equivalence classes under isomorphism by

ListTools:-Classify(g-> [seq](op(4, GraphTheory:-CanonicalGraph(g))), graph_list)

## unapply...

Define the function with unapply:

f:= unapply(a*x, x)

A synonym for unapply is MakeFunction.

## Extra spaces in 2d input...

I assume that you're using 2D Input which you've converted to 1D for posting here. If so, then you need to remove any space characters you have after displaytextplot, and draw. Also, the arguments to display need to be in parentheses. If I change your display command to

```display(
textplot(
[
[coordinates(S)[], "S"], [coordinates(P)[], "P"], [coordinates(H)[], "H"],
[coordinates(K)[], "K"], [coordinates(M)[], "M"]
], font = [times, bold, 16], align = [above, right]
),
draw([
delta(color = blue), deltap(color = blue), D(color = red), c1(color = black),
S(color = black, symbol = solidcircle, symbolsize = 16),
P(color = black, symbol = solidcircle, symbolsize = 16)
]),
scaling = constrained, axes = none, view = [-15 .. 15, -15 .. 15]
);```

then I get this plot (for which you'll likely want to change some of the sizes):

## Simplify doesn't work on equations...

The simplify command doesn't work on equations (except in the sense that it's mapped to the left and right sides independently). In common mathematical usage, as taught in secondary-school algebra, "simplification" is only performed on expressions, not equations.

## Using standard plot3d...

The Python code shown in your forum link handles the minutiae of setting up grids/meshes for 3D plots and converting spherical and cylindrical coordinates to rectangular. This is unnecessary in Maple; the plot3d command handles that in the background.

```(* Original Python code:

from matplotlib import pyplot as plt
from math import sqrt, pi, cos, sin
import numpy as np

fig = plt.figure()

t_grid = np.linspace(-1 - sqrt(7), -1 + sqrt(7), 50)
s_grid = np.linspace(-1, 1, 50)
T, S = np.meshgrid(t_grid, s_grid)
theta_fun = lambda t, s: 0.2 * pi * (t + 1 + sqrt(7)) / sqrt(7) - 0.4 * pi + 0.1
phi_fun = lambda t, s: pi * s / (4 * sqrt(2)) * sqrt(max(2 - t ** 2 / abs(t - 3), 0))
for k in range(1, 16):
phi0 = 0.4 * pi * k
r = 14 - 0.8 * k
x_fun = lambda t, s: r * cos(phi0 + phi_fun(t, s)) * cos(theta_fun(t, s))
y_fun = lambda t, s: r * sin(phi0 + phi_fun(t, s)) * cos(theta_fun(t, s))
z_fun = lambda t, s: r * sin(theta_fun(t, s))
X = np.array(list(map(x_fun, T.flatten(), S.flatten()))).reshape((50, 50))
Y = np.array(list(map(y_fun, T.flatten(), S.flatten()))).reshape((50, 50))
Z = np.array(list(map(z_fun, T.flatten(), S.flatten()))).reshape((50, 50))
ax.plot_surface(X, Y, Z, cmap='Reds')
z = np.linspace(-25, -10, 50)
p = np.linspace(0, 2 * pi, 50)
Z, P = np.meshgrid(z, p)
X = np.cos(P)
Y = np.sin(P)
ax.plot_surface(X, Y, Z, cmap='Greens')
ax.set_box_aspect(aspect=(1, 1, 1.5))
*)```

The original author plotted the petals using a nonstandard form of spherical coordinates that has the cos(theta) and sin(theta) exchanged, where theta is the altitude angle. I adjusted this to standard spherical coordinates by replacing theta with Pi/2 - theta. The original stem was done using standard cylindrical coordinates.

I don't know the exact details of the Python coloring function cmap. I made an approximation using plot option colorscheme and the ColorTools package.

For the lightmodel, I simply chose what looked best to me from the very limited choices (five) Maple offers. I chose an orientation that looked good to me.

My algebraic formulas are mathematically equivalent to the Python; however, I simplified them, so they're not syntactically identical. If Python has some difference between math.sin and numpy.sin (likewise for cos), I don't know what it is. The original author used both (perhaps unintentionally).

Surprisingly, Maple has no plot option equivalent to aspect, so I used plottools:-scale, which will do essentially the same thing provided that the options axes= none and scaling= constrained are used and that one doesn't care about the actual numerical values stored in the plot.

```#Maple translation:
cmap:= C-> colorscheme= ([ColorTools:-Lighten, ColorTools:-Darken] @@~ 2)(C):
aspect:= (S::And(list(realcons), 3 &under nops))-> (P::specfunc(PLOT3D))->
plots:-display(plottools:-scale(P, S[]), 'axes'= 'none', 'scaling'= 'constrained')
:
k:= [\$1..16]:
(aspect([1, 1, 3/2]) @ plots:-display)(
plot3d(
`[]`~(
14 -~ 4/5*~k,
Pi*~(2/5*~k +~ s*sqrt(max(2 - t^2/abs(t-3), 0)/32)),
(Pi*(7 - 2/sqrt(7)*(t+1)) - 1)/10
),
t= -1-sqrt(7)..-1+sqrt(7), s= -1..1, coords= spherical, cmap("Red")
),
plot3d(1, theta= 0..2*Pi, z= -25..-10, coords= cylindrical, cmap("Green")),
style= surface, lightmodel= light4, orientation= [49, 52, 27]
);
```

## It's hopeless...

Your system is far more than "a little" complicated. I think that there's no hope of solving this (with Maple or anything else). Maple will likely continue working on it until it runs out of memory, and then crash.

Yes, it's reasonable for it to run for days, weeks, etc., on such a system.

No, there's no way that multi-core processing can help with this.

I believe that both of those answers would be true for any mathematical software.

For what its worth, you can easily (nearly instatntaneously) eliminate 4 of the variables. The complexity of the remaining two equations might help you appreciate why this is unsolvable.

(Sols, Eqs):= eliminate({eq||(1..6)}, {u,v,w,x, y})[]:
print~(Sols): print~(Eqs=~0):

## hastype(..., typefunc(name, Not(mathfunc...

I believe that this simple procedure handles all the cases presented so far, requiring no input other than the equation itself. It also accepts and gracefully handles expressions

• implicitly equated to 0,
• with only 1 term,
• with multiple unknown dependent functions (such as would appear in any system of DEs),
• with no unknown dependent functions, or
• with no diff (such as may appear in a system of DAEs).
```LeftRight:= proc(Q::{`=`(algebraic), algebraic})
local
_0,
(L,R):= selectremove(hastype, _0 + `if`(Q::`=`, (lhs-rhs)(Q), Q), 'typefunc'(name, Not(mathfunc)))
;
eval(`if`(L=0, R=0, L = -R), _0= 0)
end proc
:
test_cases := <
diff(u(x,t),t,t) + 3 + 2*diff(u(x,t),t) + 4*t + x^2 + x^3/3
+ diff(u(x,t),t,x,x) + diff(u(x,t),x,x,x,x) = x*t^2,
y(x) + diff(y(x),x) + cos(x) + g(y(x)) + diff(f(x),x) + 1/x = sin(x),
diff(f(x),x) + 1/x = sin(x),
y(x) + x,
x*diff(y(x),x) + x = y(x) + diff(y(x),x\$2),
x^2 + 1/y(x) + diff(y(x),x) + sin(x) = y(x)^2,
1 + x,
diff(y(x),x)= 0,
diff(y(x),x\$2) = y(x) - x,
sin(x)+y(x)=0
>:
<test_cases | <seq(`&nbsp;`, numelems(test_cases))> | LeftRight~(test_cases)>;
```

## In any base, without NumberTheory...

Here is a set of procedures that do what your procedure was expected to do, and do it in any base, not just base-10. For pedagogical reasons, I have not used any package commands. All commands that I use (except ifactors) are simple integer arithmetic. I did this for pedagogical reasons; I don't have anything against  the NumberTheory package. Many of my procedures duplicate functionality from NumberTheory. And their code is so arithmetically simple that I think you'll be able to learn from them. All of these procedures run in time equal to or slightly less than their NumberTheory counterparts.

Also, it seems that RepeatDecimal subpackage of NumberTheory is limited to base-10.

 > restart:
 > interface(prompt= "") :

(*
P_log(N,p) returns (e, N/p^e) where e is the largest exponent such that p^e divides N.
*)
P_log:= proc(N::posint, p::And(posint, Not(1))) local e:= 0, n, q:= N;
while irem((n:= q), p, 'q') = 0 do e++ od;
(e,n)
end proc
:
(*
Totient(m) returns the number of elements in the multiplicative group mod m.
This is also called "Euler's totient" or "Euler's phi".
*)
Totient:= (m::posint)-> local p; mul(p[1]^(p[2]-1)*(p[1]-1), p= ifactors(m)[2])
:
(*
Base(N,R) returns a list of minimal length d of the base-R (or radix-R) digits of N in order from
most-significant to least-significant digit.
*)
Base:= (N::nonnegint, R::And(posint, Not(1)), d::posint)->
local n:= N, D:= R^max(d, 1 + ilog[R](n)); [do iquo(n, (D/= R), 'n') until D=1]
:
(*
P_factors(n) returns a list of the distinct prime factors of n.
*)
P_factors:= (n::integer)-> index~(ifactors(n)[2], 1)
:
(*
M_Order(X,m) returns the smallest T>0 such that X^T mod m = 1, a.k.a., the multiplicative
order of X (mod m).
For convenience, I allow modulus m=1 and return 0 in any such case.
*)
M_Order:= proc(X::posint, m::And(posint, satisfies(m-> igcd(m,X)=1)))
local p, T:= Totient(m), q, x:= irem(X,m);
for p in P_factors(T) do while irem(T,p,'q') = 0 and x&^q mod m = 1 do T:= q od od;
`if`(m=1, 0, T)
end proc
:
(*
periode(r,R) returns [q, nops(dL), dL] where
representation of rational number r,
and
dL is the list of repeating digits in radix-R representation.

"Radix" is a more-formal word for "base", as in "base-10 arithmetic".
The radix R defaults to 10.
*)
periode:= proc(r::{integer,fraction}, R::And(posint, Not(1)):= 10)
local b:= denom(r), f, i, p, q:= 0, M;
for f in P_factors(R) do (i,b):= P_log(b,f); q:= max(q,i) od;
[q, (p:= M_Order(R,b)), Base(abs(numer(frac(r*R^q)))*(R^p-1)/b, R, p)]
end proc
:

#Test cases:
periode(2/3);

periode(2/35);

periode(3/140);

periode(3/5, 2);

periode(1/13);

#Preben's example:
CodeTools:-Usage(periode(1007/200035));

memory used=2.29MiB, alloc change=0 bytes, cpu time=0ns, real time=4.00ms, gc time=0ns

## Use `is` for mathematical equality...

Your problem comes from using the default equality operator = to check the mathematical equality of algebraic expressions, but = only checks whether the expressions are syntactically identical in their unsimplified form. That's a much stronger form of equality than mathematical equality. Use the command is to check mathematical equality. Your code should include something to do if is returns FAIL, which means that it couldn't determine mathematical equality. Here's a revision of your procedure:

 > restart:
 > CauchyRiemann:= proc(expr::algebraic, z::name:= ':-z') local     x, y,     (u,v):= op(evalc([Re,Im](eval(expr, z= x+I*y)))),     (u_x, u_y, v_x, v_y):= op(diff~([u,u,v,v], [x,y,x,y])),     (flag1, flag2):= op(is~([u_x, u_y] =~ [v_y, -v_x]) assuming additionally, (x,y)::~real) ;       print~([         'f(z)'=expr, ``,         'u(x,y)'=u, 'u[x](x,y)'=u_x, 'u[y](x,y)'=u_y, ``,         'v(x,y)'=v, 'v[x](x,y)'=v_x, 'v[y](x,y)'=v_y, ``,              if flag1 then 'u[x]=v[y]', u_x=v_y         elif not flag1 then 'u[x]<>v[y]', u_x<>v_y         else `Couldn't determine whether ` || ('u[x]=v[y]')         fi,         if flag2 then 'u[y] = -v[x]', u_y = -v_x         elif not flag2 then 'u[y] <> -v[x]', u_y <> -v_x         else `Couldn't determine whether ` || ('u[y] = -v[x]')         fi,         ``,         if flag1 and flag2 then            `Fullfill the Cauchy-Riemann Equations`,            `The derivative is:`='u[x]+I*v[y]', 'diff(f(z),z)'=u_x+I*v_y         else            `Cauchy-Riemann ?`         fi,         ``     ]);     flag1 and flag2 end proc:          f(z):=1/(z+2): CauchyRiemann(f(z));

 >

## Explicit multiplication...

Use explicit multiplication symbols:

PDE :=
diff(G(a, H, phi, PI), a)*(aH) + diff(G(a, H, phi, PI), H)*(k/a^2 - kappa^2/2*PI^2/a^6)
+ diff(G(a, H, phi, PI), phi)*(PI/a^3)
= diff(G(a, H, phi, PI), PI)*(a^3*diff(V(phi), phi))
;

pdsolve(PDE, G);

 1 2 3 4 5 6 7 Last Page 1 of 384
﻿