-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPDESolver.py
More file actions
5698 lines (4801 loc) · 238 KB
/
PDESolver.py
File metadata and controls
5698 lines (4801 loc) · 238 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025 Philippe Billet
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
PDESolver — A Spectral Method PDE Solver with Symbolic Capabilities
Overview
--------
PDESolver is a powerful Python module for solving partial differential equations (PDEs)
using spectral methods, enhanced with symbolic capabilities via SymPy. It combines high-precision
numerical methods with symbolic analysis of differential and pseudo-differential operators,
making it suitable for both research and educational applications.
Key Features
------------
- **Symbolic Parsing**: Define PDEs using SymPy expressions for full symbolic manipulation
- **Spectral Methods**: Uses Fourier transforms for high-accuracy spatial differentiation
- **Nonlinear Support**: Handles nonlinear terms via pseudo-spectral evaluation and dealiasing
- **Time Integration**:
- Exponential time stepping for linear systems
- ETD-RK4 (Exponential Time Differencing with 4th-order Runge-Kutta) for stiff or nonlinear systems
- **Pseudo-Differential Operators (`psiOp`)**:
- Define equations using `psiOp(symbol, u)` for arbitrary pseudo-differential symbols
- Supports symbolic inversion, adjoint computation, and asymptotic expansions
- **Boundary Conditions**:
- Periodic (via FFT)
- Dirichlet (via pseudo-differential operator)
- **Interactive Analysis**:
- Explore symbol properties (`|p(x, ξ)|`, group velocity)
- Visualize Hamiltonian flows and characteristic sets
- **Visualization**:
- Animate solutions in 1D/2D
- Plot real, imaginary, absolute, or phase components of complex solutions
Symbolic Workflow
-----------------
PDESolver supports full symbolic definition of PDEs using SymPy syntax. It automatically extracts and analyzes:
- Linear operators in frequency space `L(k)`
- Dispersion relations `ω(k)`
- Nonlinear terms
- Pseudo-differential operators (`psiOp`)
- Source terms
Example Definition
------------------
```python
from PDESolver import *
# Define PDE
t, x, xi = symbols('t x xi', real=True)
u = Function('u')
#equation = Eq(diff(u, t, t), diff(u, x, 2) - u) # boundary_condition : 'periodic'
equation = Eq(diff(u(t,x), t), -psiOp(xi**2 + 1, u(t,x))) # boundary_condition : 'periodic' or 'dirichlet'
# Init solver
solver = PDESolver(equation)
# Setup domain
solver.setup(
Lx=2*np.pi, Nx=256,
Lt=2.0, Nt=1000,
initial_condition=lambda x: np.sin(x),
initial_velocity=lambda x: 0*x,
boundary_condition='periodic' # or 'dirichlet'
)
# Solve & animate
solver.solve()
ani = solver.animate(component='real')
HTML(ani.to_jshtml())
```
Numerical Methods
-----------------
Spectral Differentiation
-----------------
- Uses FFT-based spatial differentiation.
- Dealiasing is applied to nonlinear terms using a sharp cutoff.
- Handles 1D and 2D spatial domains.
Time Integration
-----------------
- First-order evolution:
- Default exponential stepping.
- ETD-RK4 support for stiff or nonlinear systems.
- Second-order evolution:
- Leapfrog-style update.
- ETD-RK4 adapted for second-order systems.
- Supports acceleration from pseudo-differential operators.
Pseudo-Differential Operators
-----------------------------
- Symbolic expressions like `xi**2 + 1` define the operator symbol.
- Evaluated using the Kohn–Nirenberg quantization.
- Supports non-periodic domains and Dirichlet boundary conditions through symbolic inversion.
Interactive Symbol Analysis
---------------------------
Use `interactive_symbol_analysis(pseudo_op)` to explore:
- Symbol amplitude and phase
- Group velocity fields
- Hamiltonian flows
- Characteristic sets
- Micro-support estimates
This is particularly useful for studying:
- Wave propagation
- Singularity propagation
- Stability and dispersion properties
- Microlocal behavior of solutions
Example Use Case
----------------
```python
from PDESolver import *
# Definition of symbols
t, x, xi = symbols('t x xi', real=True)
u = Function('u')
# Evolution equation: ∂²u/∂t² = -ψOp(x² + ξ², u)
p_expr = x**2 + xi**2
equation = Eq(diff(u(t,x), t, t), -psiOp(p_expr, u(t,x)))
# Creation of the solver
solver = PDESolver(equation)
# Parameters
Lx = 12.0
Nx = 256
Lt = 3.0
Nt = 600
n = 2 # Order of Hermite
lambda_n = 2 * n + 1
# Initial function: u₀(x) = Hₙ(x) * exp(-x² / 2)
initial_condition = lambda x: eval_hermite(n, x) * np.exp(-x**2 / 2)
# Zero initial velocity: ∂ₜ u(0,x) = 0
initial_velocity = lambda x: 0.0 * x
# Exact solution
def u_exact(x, t):
return np.cos(np.sqrt(lambda_n) * t) * eval_hermite(n, x) * np.exp(-x**2 / 2)
# Solver setup
solver.setup(
Lx=Lx,
Nx=Nx,
Lt=Lt,
Nt=Nt,
boundary_condition='dirichlet',
initial_condition=initial_condition,
initial_velocity=initial_velocity,
)
# Solving
solver.solve()
# Validation tests
n_test = 5
for i in range(n_test + 1):
t_eval = i * Lt / n_test
solver.test(u_exact=u_exact, t_eval=t_eval, threshold=50, component='real')
```
Applications
------------
PDESolver is ideal for:
- Educational tools (visualization of PDE solutions and symbolic analysis)
- Microlocal analysis (Hamiltonian flows)
- Operator theory (pseudo-differential calculus, inversion, adjoints)
Dependencies
------------
- numpy, scipy
- sympy for symbolic manipulation
- matplotlib for visualization
- ipywidgets for interactive analysis
- scipy.fft, scipy.integrate, scipy.signal
"""
import numpy as np
from numpy.linalg import svd
import matplotlib.pyplot as plt
from scipy.fft import fft2, ifft2, fft, ifft, fftfreq, fftshift, ifftshift
from scipy.signal.windows import hann
from scipy.integrate import solve_ivp
from scipy.ndimage import maximum_filter
from scipy.sparse import diags
from scipy.sparse.linalg import svds
from scipy.integrate import trapezoid as scipy_trapezoid
from sympy import (
symbols, Function,
solve, pprint, Mul,
lambdify, expand, Eq, simplify, trigsimp, N,
radsimp, ratsimp, cancel,
Lambda, Piecewise, Basic, degree, Pow, preorder_traversal, Heaviside,
powdenest, expand, Matrix,
sqrt, I, pi, series, oo,
re, im, arg, Abs, conjugate,
sin, cos, tan, cot, sec, csc, sinc,
asin, acos, atan, acot, asec, acsc,
sinh, cosh, tanh, coth, sech, csch,
asinh, acosh, atanh, acoth, asech, acsch,
exp, ln, log, factorial,
gegenbauer, chebyshevu, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre,
diff, Derivative, integrate,
fourier_transform, inverse_fourier_transform,
)
from sympy.core.function import AppliedUndef
from scipy.special import legendre, eval_hermite, airy, eval_genlaguerre, jv, kv, sph_harm, gamma
from scipy.spatial.distance import cdist
from scipy.stats import norm
from scipy.stats import wasserstein_distance
from scipy.interpolate import RegularGridInterpolator
from scipy.integrate import odeint
from matplotlib import cm
from matplotlib.animation import FuncAnimation, FFMpegWriter
import matplotlib.animation as animation
from matplotlib import rc
from functools import partial
from PIL import Image
import librosa, librosa.display
import soundfile as sf
from misc import *
from IPython.display import display, clear_output, HTML, Video
from ipywidgets import interact, FloatSlider, Dropdown, VBox, HBox, interactive_output
from itertools import product
from mpl_toolkits.mplot3d import Axes3D
import os
plt.rcParams['text.usetex'] = False
FFT_WORKERS = max(1, os.cpu_count() // 2)
NUM_COLS = 150
class PseudoDifferentialOperator:
"""
Pseudo-differential operator with dynamic symbol evaluation on spatial grids.
Supports both 1D and 2D operators, and can be defined explicitly (symbol mode)
or extracted automatically from symbolic equations (auto mode).
Parameters
----------
expr : sympy expression
Symbolic expression representing the pseudo-differential symbol.
vars_x : list of sympy symbols
Spatial variables (e.g., [x] for 1D, [x, y] for 2D).
var_u : sympy function, optional
Function u(x, t) used in auto mode to extract the operator symbol.
mode : str, {'symbol', 'auto'}
- 'symbol': directly uses expr as the operator symbol.
- 'auto': computes the symbol automatically by applying expr to exp(i x ξ).
Attributes
----------
dim : int
Spatial dimension (1 or 2).
fft, ifft : callable
Fast Fourier transform and inverse (scipy.fft or scipy.fft2).
p_func : callable
Evaluated symbol function ready for numerical use.
Notes
-----
- In 'symbol' mode, `expr` should be expressed in terms of spatial variables and frequency variables (ξ, η).
- In 'auto' mode, the symbol is derived by applying the differential expression to a complex exponential.
- Frequency variables are internally named 'xi' and 'eta' for consistency.
- Uses numpy for numerical evaluation and scipy.fft for FFT operations.
Examples
--------
>>> # Example 1: 1D Laplacian operator (symbol mode)
>>> from sympy import symbols
>>> x, xi = symbols('x xi', real=True)
>>> op = PseudoDifferentialOperator(expr=xi**2, vars_x=[x], mode='symbol')
>>> # Example 2: 1D transport operator (auto mode)
>>> from sympy import Function
>>> u = Function('u')
>>> expr = u(x).diff(x)
>>> op = PseudoDifferentialOperator(expr=expr, vars_x=[x], var_u=u(x), mode='auto')
"""
def __init__(self, expr, vars_x, var_u=None, mode='symbol'):
self.dim = len(vars_x)
self.mode = mode
self.symbol_cached = None
self.expr = expr
self.vars_x = vars_x
if self.dim == 1:
x, = vars_x
xi_internal = symbols('xi', real=True)
expr = expr.subs(symbols('xi', real=True), xi_internal)
self.fft = partial(fft, workers=FFT_WORKERS)
self.ifft = partial(ifft, workers=FFT_WORKERS)
if mode == 'symbol':
self.p_func = lambdify((x, xi_internal), expr, 'numpy')
self.symbol = expr
elif mode == 'auto':
if var_u is None:
raise ValueError("var_u must be provided in mode='auto'")
exp_i = exp(I * x * xi_internal)
P_ei = expr.subs(var_u, exp_i)
symbol = simplify(P_ei / exp_i)
symbol = expand(symbol)
self.symbol = symbol
self.p_func = lambdify((x, xi_internal), symbol, 'numpy')
else:
raise ValueError("mode must be 'auto' or 'symbol'")
elif self.dim == 2:
x, y = vars_x
xi_internal, eta_internal = symbols('xi eta', real=True)
expr = expr.subs(symbols('xi', real=True), xi_internal)
expr = expr.subs(symbols('eta', real=True), eta_internal)
self.fft = partial(fft2, workers=FFT_WORKERS)
self.ifft = partial(ifft2, workers=FFT_WORKERS)
if mode == 'symbol':
self.symbol = expr
self.p_func = lambdify((x, y, xi_internal, eta_internal), expr, 'numpy')
elif mode == 'auto':
if var_u is None:
raise ValueError("var_u must be provided in mode='auto'")
exp_i = exp(I * (x * xi_internal + y * eta_internal))
P_ei = expr.subs(var_u, exp_i)
symbol = simplify(P_ei / exp_i)
symbol = expand(symbol)
self.symbol = symbol
self.p_func = lambdify((x, y, xi_internal, eta_internal), symbol, 'numpy')
else:
raise ValueError("mode must be 'auto' or 'symbol'")
else:
raise NotImplementedError("Only 1D and 2D supported")
if mode == 'auto':
print("\nsymbol = ")
pprint(self.symbol, num_columns=NUM_COLS)
def evaluate(self, X, Y, KX, KY, cache=True):
"""
Evaluate the pseudo-differential operator's symbol on a grid of spatial and frequency coordinates.
The method dynamically selects between 1D and 2D evaluation based on the spatial dimension.
If caching is enabled and a cached symbol exists, it returns the cached result to avoid recomputation.
Parameters
----------
X, Y : ndarray
Spatial grid coordinates. In 1D, Y is ignored.
KX, KY : ndarray
Frequency grid coordinates. In 1D, KY is ignored.
cache : bool, default=True
If True, stores the computed symbol for reuse in subsequent calls to avoid redundant computation.
Returns
-------
ndarray
Evaluated symbol values over the input grid. Shape matches the input spatial/frequency grids.
Raises
------
NotImplementedError
If the spatial dimension is not 1D or 2D.
"""
if cache and self.symbol_cached is not None:
return self.symbol_cached
if self.dim == 1:
symbol = self.p_func(X, KX)
elif self.dim == 2:
symbol = self.p_func(X, Y, KX, KY)
if cache:
self.symbol_cached = symbol
return symbol
def clear_cache(self):
"""
Clear cached symbol evaluations.
"""
self.symbol_cached = None
def principal_symbol(self, order=1):
"""
Compute the leading homogeneous component of the pseudo-differential symbol.
This method extracts the principal part of the symbol, which is the dominant
term under high-frequency asymptotics (|ξ| → ∞). The expansion is performed
in polar coordinates for 2D symbols to maintain rotational symmetry, then
converted back to Cartesian form.
Parameters
----------
order : int
Order of the asymptotic expansion in powers of 1/ρ, where ρ = |ξ| in 1D
or ρ = sqrt(ξ² + η²) in 2D. Only the leading-order term is returned.
Returns
-------
sympy.Expr
The principal symbol component, homogeneous of degree `m - order`, where
`m` is the original symbol's order.
Notes:
- In 1D, uses direct series expansion in ξ.
- In 2D, expands in radial variable ρ while preserving angular dependence.
- Useful for microlocal analysis and constructing parametrices.
"""
p = self.symbol
if self.dim == 1:
xi = symbols('xi', real=True, positive=True)
return simplify(series(p, xi, oo, n=order).removeO())
elif self.dim == 2:
xi, eta = symbols('xi eta', real=True, positive=True)
# Homogeneous radial expansion: we set (ξ, η) = ρ (cosθ, sinθ)
rho, theta = symbols('rho theta', real=True, positive=True)
p_rho = p.subs({xi: rho * cos(theta), eta: rho * sin(theta)})
expansion = series(p_rho, rho, oo, n=order).removeO()
# Revert back to (ξ, η)
expansion_cart = expansion.subs({rho: sqrt(xi**2 + eta**2),
cos(theta): xi / sqrt(xi**2 + eta**2),
sin(theta): eta / sqrt(xi**2 + eta**2)})
return simplify(powdenest(expansion_cart, force=True))
def is_homogeneous(self, tol=1e-10):
"""
Check whether the symbol is homogeneous in the frequency variables.
Returns
-------
(bool, Rational or float or None)
Tuple (is_homogeneous, degree) where:
- is_homogeneous: True if the symbol satisfies p(λξ, λη) = λ^m * p(ξ, η)
- degree: the detected degree m if homogeneous, or None
"""
from sympy import symbols, simplify, expand, Eq
from sympy.abc import l
if self.dim == 1:
xi = symbols('xi', real=True, positive=True)
l = symbols('l', real=True, positive=True)
p = self.symbol
p_scaled = p.subs(xi, l * xi)
ratio = simplify(p_scaled / p)
if ratio.has(xi):
return False, None
try:
deg = simplify(ratio).as_base_exp()[1]
return True, deg
except Exception:
return False, None
elif self.dim == 2:
xi, eta = symbols('xi eta', real=True, positive=True)
l = symbols('l', real=True, positive=True)
p = self.symbol
p_scaled = p.subs({xi: l * xi, eta: l * eta})
ratio = simplify(p_scaled / p)
# If ratio == l**m with no (xi, eta) left, it's homogeneous
if ratio.has(xi, eta):
return False, None
try:
base, exp = ratio.as_base_exp()
if base == l:
return True, exp
except Exception:
pass
return False, None
def symbol_order(self, max_order=10, tol=1e-3):
"""
Estimate the homogeneity order of the pseudo-differential symbol in high-frequency asymptotics.
This method attempts to determine the leading-order behavior of the symbol p(x, ξ) or p(x, y, ξ, η)
as |ξ| → ∞ (in 1D) or |(ξ, η)| → ∞ (in 2D). The returned value represents the asymptotic growth or decay rate,
which is essential for understanding the regularity and mapping properties of the corresponding operator.
The function uses symbolic preprocessing to ensure proper factorization of frequency variables,
especially in sqrt and power expressions, to avoid erroneous order detection (e.g., due to hidden scaling).
Parameters
----------
max_order : int, optional
Maximum number of terms to consider in the series expansion. Default is 10.
tol : float, optional
Tolerance threshold for evaluating the coefficient magnitude. If the coefficient is too small,
the detected order may be discarded. Default is 1e-3.
Returns
-------
float or None
- If the symbol is homogeneous, returns its exact homogeneity degree as a float.
- Otherwise, estimates the dominant asymptotic order from leading terms in the expansion.
- Returns None if no valid order could be determined.
Notes
-----
- In 1D:
Two strategies are used:
1. Expand directly in xi at infinity.
2. Substitute xi = 1/z and expand around z = 0.
- In 2D:
- Transform the symbol into polar coordinates: (xi, eta) = rho*(cos(theta), sin(theta)).
- Expand in rho at infinity, then extract the leading term's power.
- An alternative substitution using 1/z is also tried if the first method fails.
- Preprocessing steps:
- Sqrt expressions involving frequencies are rewritten to isolate the leading variable.
- Power expressions are factored explicitly to ensure correct symbolic scaling.
- If the symbol is not homogeneous, a warning is issued, and the result should be interpreted with care.
- For non-homogeneous symbols, only the principal asymptotic term is considered.
Raises
------
NotImplementedError
If the spatial dimension is neither 1 nor 2.
"""
from sympy import (
symbols, series, simplify, sqrt, cos, sin, oo, powdenest, radsimp,
expand, expand_power_base
)
def preprocess_sqrt(expr, freq):
return expr.replace(
lambda e: e.func == sqrt and freq in e.free_symbols,
lambda e: freq * sqrt(1 + (e.args[0] - freq**2) / freq**2)
)
def preprocess_power(expr, freq):
return expr.replace(
lambda e: e.is_Pow and freq in e.free_symbols,
lambda e: freq**e.exp * (1 + e.base / freq**e.base.as_powers_dict().get(freq, 0))**e.exp
)
def validate_order(power, coeff, vars_x, tol):
if power is None:
return None
if any(v in coeff.free_symbols for v in vars_x):
print("⚠️ Coefficient depends on spatial variables; ignoring")
return None
try:
coeff_val = abs(float(coeff.evalf()))
if coeff_val < tol:
print(f"⚠️ Coefficient too small ({coeff_val:.2e} < {tol})")
return None
except Exception as e:
print(f"⚠️ Coefficient evaluation failed: {e}")
return None
return int(power) if power == int(power) else float(power)
# Homogeneity check
is_homog, degree = self.is_homogeneous()
if is_homog:
return float(degree)
else:
print("⚠️ The symbol is not homogeneous. The asymptotic order is not well defined.")
if self.dim == 1:
x = self.vars_x[0]
xi = symbols('xi', real=True, positive=True)
try:
print("1D symbol_order - method 1")
expr = preprocess_sqrt(self.symbol, xi)
s = series(expr, xi, oo, n=max_order).removeO()
lead = simplify(powdenest(s.as_leading_term(xi), force=True))
power = lead.as_powers_dict().get(xi, None)
coeff = lead / xi**power if power is not None else 0
print("lead =", lead)
print("power =", power)
print("coeff =", coeff)
order = validate_order(power, coeff, [x], tol)
if order is not None:
return order
except Exception:
pass
try:
print("1D symbol_order - method 2")
z = symbols('z', real=True, positive=True)
expr_z = preprocess_sqrt(self.symbol.subs(xi, 1/z), 1/z)
s = series(expr_z, z, 0, n=max_order).removeO()
lead = simplify(powdenest(s.as_leading_term(z), force=True))
power = lead.as_powers_dict().get(z, None)
coeff = lead / z**power if power is not None else 0
print("lead =", lead)
print("power =", power)
print("coeff =", coeff)
order = validate_order(power, coeff, [x], tol)
if order is not None:
return -order
except Exception as e:
print(f"⚠️ fallback z failed: {e}")
return None
elif self.dim == 2:
x, y = self.vars_x
xi, eta = symbols('xi eta', real=True, positive=True)
rho, theta = symbols('rho theta', real=True, positive=True)
try:
print("2D symbol_order - method 1")
p_rho = self.symbol.subs({xi: rho * cos(theta), eta: rho * sin(theta)})
p_rho = preprocess_power(preprocess_sqrt(p_rho, rho), rho)
s = series(simplify(p_rho), rho, oo, n=max_order).removeO()
lead = radsimp(simplify(powdenest(s.as_leading_term(rho), force=True)))
power = lead.as_powers_dict().get(rho, None)
coeff = lead / rho**power if power is not None else 0
print("lead =", lead)
print("power =", power)
print("coeff =", coeff)
order = validate_order(power, coeff, [x, y], tol)
if order is not None:
return order
except Exception as e:
print(f"⚠️ polar expansion failed: {e}")
try:
print("2D symbol_order - method 2")
z = symbols('z', real=True, positive=True)
xi_eta = {xi: (1/z) * cos(theta), eta: (1/z) * sin(theta)}
p_rho = preprocess_sqrt(self.symbol.subs(xi_eta), 1/z)
s = series(simplify(p_rho), z, 0, n=max_order).removeO()
lead = radsimp(simplify(powdenest(s.as_leading_term(z), force=True)))
power = lead.as_powers_dict().get(z, None)
coeff = lead / z**power if power is not None else 0
print("lead =", lead)
print("power =", power)
print("coeff =", coeff)
order = validate_order(power, coeff, [x, y], tol)
if order is not None:
return -order
except Exception as e:
print(f"⚠️ fallback z (2D) failed: {e}")
return None
else:
raise NotImplementedError("Only 1D and 2D supported.")
def asymptotic_expansion(self, order=3):
"""
Compute the asymptotic expansion of the symbol as |ξ| → ∞ (high-frequency regime).
This method expands the pseudo-differential symbol in inverse powers of the
frequency variable(s), either in 1D or 2D. It handles both polynomial and
exponential symbols by performing a series expansion in 1/|ξ| up to the specified order.
The expansion is performed directly in Cartesian coordinates for 1D symbols.
For 2D symbols, the method uses polar coordinates (ρ, θ) to perform the expansion
at infinity in ρ, then converts the result back to Cartesian coordinates.
Parameters
----------
order : int, optional
Maximum order of the asymptotic expansion. Default is 3.
Returns
-------
sympy.Expr
The asymptotic expansion of the symbol up to the given order, expressed in Cartesian coordinates.
If expansion fails, returns the original unexpanded symbol.
Notes:
- In 1D: expansion is performed directly in terms of ξ.
- In 2D: the symbol is first rewritten in polar coordinates (ρ,θ), expanded asymptotically
in ρ → ∞, then converted back to Cartesian coordinates (ξ,η).
- Handles special case when the symbol is an exponential function by expanding its argument.
- Symbolic normalization is applied early (via `simplify`) for 2D expressions to improve convergence.
- Robust to failures: catches exceptions and issues warnings instead of raising errors.
- Final expression is simplified using `powdenest` and `expand` for improved readability.
"""
p = self.symbol
if self.dim == 1:
xi = symbols('xi', real=True, positive=True)
try:
# Case: exponential function
if p.func == exp and len(p.args) == 1:
arg = p.args[0]
arg_series = series(arg, xi, oo, n=order).removeO()
expanded = series(exp(expand(arg_series)), xi, oo, n=order).removeO()
return simplify(powdenest(expanded, force=True))
else:
expanded = series(p, xi, oo, n=order).removeO()
return simplify(powdenest(expanded, force=True))
except Exception as e:
print(f"Warning: 1D expansion failed: {e}")
return p
elif self.dim == 2:
xi, eta = symbols('xi eta', real=True, positive=True)
rho, theta = symbols('rho theta', real=True, positive=True)
# Normalize before substitution
p = simplify(p)
# Substitute polar coordinates
p_polar = p.subs({
xi: rho * cos(theta),
eta: rho * sin(theta)
})
try:
# Handle exponentials
if p_polar.func == exp and len(p_polar.args) == 1:
arg = p_polar.args[0]
arg_series = series(arg, rho, oo, n=order).removeO()
expanded = series(exp(expand(arg_series)), rho, oo, n=order).removeO()
else:
expanded = series(p_polar, rho, oo, n=order).removeO()
# Convert back to Cartesian
norm = sqrt(xi**2 + eta**2)
expansion_cart = expanded.subs({
rho: norm,
cos(theta): xi / norm,
sin(theta): eta / norm
})
# Final simplifications
result = simplify(powdenest(expansion_cart, force=True))
result = expand(result)
return result
except Exception as e:
print(f"Warning: 2D expansion failed: {e}")
return p
def compose_asymptotic(self, other, order=1, mode='kn', sign_convention=None):
"""
Compose two pseudo-differential operators using an asymptotic expansion
in the chosen quantization scheme (Kohn–Nirenberg or Weyl).
Parameters
----------
other : PseudoDifferentialOperator
The operator to compose with this one.
order : int, default=1
Maximum order of the asymptotic expansion.
mode : {'kn', 'weyl'}, default='kn'
Quantization mode:
- 'kn' : Kohn–Nirenberg quantization (left-quantized)
- 'weyl' : Weyl symmetric quantization
sign_convention : {'standard', 'inverse'}, optional
Controls the phase factor convention for the KN case:
- 'standard' → (i)^(-n), gives [x, ξ] = +i (physics convention)
- 'inverse' → (i)^(+n), gives [x, ξ] = -i (mathematical adjoint convention)
If None, defaults to 'standard'.
Returns
-------
sympy.Expr
Symbolic expression for the composed symbol up to the given order.
Notes
-----
- In 1D (Kohn–Nirenberg):
(p ∘ q)(x, ξ) ~ Σₙ (1/n!) (i sgn)^n ∂_ξⁿ p(x, ξ) ∂_xⁿ q(x, ξ)
- In 1D (Weyl):
(p # q)(x, ξ) = exp[(i/2)(∂_ξ^p ∂_x^q - ∂_x^p ∂_ξ^q)] p(x, ξ) q(x, ξ)
truncated at given order.
Examples
--------
X = a*x, Y = b*ξ
X_op.compose_asymptotic(Y_op, order=3, mode='weyl')
"""
from sympy import diff, factorial, simplify, symbols
assert self.dim == other.dim, "Operator dimensions must match"
p, q = self.symbol, other.symbol
# Default sign convention
if sign_convention is None:
sign_convention = 'standard'
sign = -1 if sign_convention == 'standard' else +1
# --- 1D case ---
if self.dim == 1:
x = self.vars_x[0]
xi = symbols('xi', real=True)
result = 0
if mode == 'kn': # Kohn–Nirenberg
for n in range(order + 1):
term = (1 / factorial(n)) * diff(p, xi, n) * diff(q, x, n) * (1j) ** (sign * n)
result += term
elif mode == 'weyl': # Weyl symmetric composition
# Weyl star product: exp((i/2)(∂_ξ^p ∂_x^q - ∂_x^p ∂_ξ^q))
result = 0
for n in range(order + 1):
for k in range(n + 1):
# k derivatives acting as (∂_ξ^k p)(∂_x^(n−k) q)
coeff = (1 / (factorial(k) * factorial(n - k))) * ((1j / 2) ** n) * ((-1) ** (n - k))
term = coeff * diff(p, xi, k, x, n - k, evaluate=True) * diff(q, x, k, xi, n - k, evaluate=True)
result += term
else:
raise ValueError("mode must be either 'kn' or 'weyl'")
return simplify(result)
# --- 2D case ---
elif self.dim == 2:
x, y = self.vars_x
xi, eta = symbols('xi eta', real=True)
result = 0
if mode == 'kn':
for n in range(order + 1):
for i in range(n + 1):
j = n - i
term = (1 / (factorial(i) * factorial(j))) * \
diff(p, xi, i, eta, j) * diff(q, x, i, y, j) * (1j) ** (sign * n)
result += term
elif mode == 'weyl':
for n in range(order + 1):
for i in range(n + 1):
j = n - i
coeff = (1 / (factorial(i) * factorial(j))) * ((1j / 2) ** n) * ((-1) ** (n - i))
term = coeff * diff(p, xi, i, eta, j, x, 0, y, 0) * diff(q, x, i, y, j, xi, 0, eta, 0)
result += term
else:
raise ValueError("mode must be either 'kn' or 'weyl'")
return simplify(result)
else:
raise NotImplementedError("Only 1D and 2D cases are implemented")
def commutator_symbolic(self, other, order=1, mode='kn', sign_convention=None):
"""
Compute the symbolic commutator [A, B] = A∘B − B∘A of two pseudo-differential operators
using formal asymptotic expansion of their composition symbols.
This method computes the asymptotic expansion of the commutator's symbol up to a given
order, based on the symbolic calculus of pseudo-differential operators in the
Kohn–Nirenberg quantization. The result is a purely symbolic sympy expression that
captures the leading-order noncommutativity of the operators.
Parameters
----------
other : PseudoDifferentialOperator
The pseudo-differential operator B to commute with this operator A.
order : int, default=1
Maximum order of the asymptotic expansion.
- order=1 yields the leading term proportional to the Poisson bracket {p, q}.
- Higher orders include correction terms involving higher mixed derivatives.
Returns
-------
sympy.Expr
Symbolic expression for the asymptotic expansion of the commutator symbol
σ([A,B]) = σ(A∘B − B∘A).
"""
assert self.dim == other.dim, "Operator dimensions must match"
p, q = self.symbol, other.symbol
pq = self.compose_asymptotic(other, order=order, mode=mode, sign_convention=sign_convention)
qp = other.compose_asymptotic(self, order=order, mode=mode, sign_convention=sign_convention)
comm_symbol = simplify(pq-qp)
return comm_symbol
def right_inverse_asymptotic(self, order=1):
"""
Construct a formal right inverse R of the pseudo-differential operator P such that
the composition P ∘ R equals the identity plus a smoothing operator of order -order.
This method computes an asymptotic expansion for the right inverse using recursive
corrections based on derivatives of the symbol p(x, ξ) and lower-order terms of R.
Parameters
----------
order : int
Number of terms to include in the asymptotic expansion. Higher values improve
approximation at the cost of complexity and computational effort.
Returns
-------
sympy.Expr
The symbolic expression representing the formal right inverse R(x, ξ), which satisfies:
P ∘ R = Id + O(⟨ξ⟩^{-order}), where ⟨ξ⟩ = (1 + |ξ|²)^{1/2}.
Notes
-----
- In 1D: The recursion involves spatial derivatives of R and derivatives of p with respect to ξ.
- In 2D: The multi-index generalization is used with mixed derivatives in ξ and η.
- The construction relies on the non-vanishing of the principal symbol p to ensure invertibility.
- Each term in the expansion corresponds to higher-order corrections involving commutators
between the operator P and the current approximation of R.
"""
p = self.symbol
if self.dim == 1:
x = self.vars_x[0]
xi = symbols('xi', real=True)
r = 1 / p.subs(xi, xi) # r0
R = r
for n in range(1, order + 1):
term = 0
for k in range(1, n + 1):
coeff = (1j)**(-k) / factorial(k)
inner = diff(p, xi, k) * diff(R, x, k)
term += coeff * inner
R = R - r * term
elif self.dim == 2:
x, y = self.vars_x
xi, eta = symbols('xi eta', real=True)
r = 1 / p.subs({xi: xi, eta: eta})
R = r
for n in range(1, order + 1):
term = 0
for k1 in range(n + 1):
for k2 in range(n + 1 - k1):
if k1 + k2 == 0: continue
coeff = (1j)**(-(k1 + k2)) / (factorial(k1) * factorial(k2))
dp = diff(p, xi, k1, eta, k2)
dR = diff(R, x, k1, y, k2)
term += coeff * dp * dR
R = R - r * term
return R
def left_inverse_asymptotic(self, order=1):
"""
Construct a formal left inverse L such that the composition L ∘ P equals the identity
operator up to terms of order ξ^{-order}. This expansion is performed asymptotically
at infinity in the frequency variable(s).
The left inverse is built iteratively using symbolic differentiation and the
method of asymptotic expansions for pseudo-differential operators. It ensures that:
L(P(x,ξ),x,D) ∘ P(x,D) = Id + smoothing operator of order -order
Parameters
----------
order : int, optional
Maximum number of terms in the asymptotic expansion (default is 1). Higher values
yield more accurate inverses at the cost of increased computational complexity.
Returns
-------
sympy.Expr
Symbolic expression representing the principal symbol of the formal left inverse
operator L(x,ξ). This expression depends on spatial variables and frequencies,
and includes correction terms up to the specified order.
Notes
-----
- In 1D: Uses recursive application of the Leibniz formula for symbols.
- In 2D: Generalizes to multi-indices for mixed derivatives in (x,y) and (ξ,η).
- Each term involves combinations of derivatives of the original symbol p(x,ξ) and
previously computed terms of the inverse.
- Coefficients include powers of 1j (i) and factorial normalization for derivative terms.
"""
p = self.symbol
if self.dim == 1:
x = self.vars_x[0]
xi = symbols('xi', real=True)
l = 1 / p.subs(xi, xi)
L = l
for n in range(1, order + 1):
term = 0
for k in range(1, n + 1):
coeff = (1j)**(-k) / factorial(k)
inner = diff(L, xi, k) * diff(p, x, k)
term += coeff * inner
L = L - term * l
elif self.dim == 2:
x, y = self.vars_x