ProjectsProjeler / SW-01
Web app · Python engine in the browserWeb uygulaması · tarayıcıda Python motoru
ElectroField
An applied electromagnetics workbench. You change ε, μ, σ, the frequency or the geometry, and a Python engine recomputes the result, writes the derivation out with the numbers in it, and then checks the answer with a second method that does not share code with the first.
Uygulamalı elektromanyetik için bir çalışma ortamı. ε, μ, σ, frekans ya da geometriyi değiştiriyorsunuz; Python motoru sonucu yeniden hesaplıyor, türetmeyi sayılar yerine konmuş halde yazıyor ve sonra cevabı, ilkiyle kod paylaşmayan ikinci bir yöntemle kontrol ediyor.
Why I built it
Electromagnetics was the first course where I could follow every step of a solution and still not trust the final number. A sign error in a reflection coefficient or a wrong branch of a complex square root gives an answer that looks perfectly reasonable. The textbooks (Ulaby & Ravaioli, and Cheng) give the method, but when I changed one parameter on my own I had no way to tell whether my new answer was right.
So I started writing small Python functions for each topic, and every time I wrote one I also wrote a second way to get the same number. Over time those functions turned into an engine, and the engine needed an interface, which became ElectroField.
Architecture
The project has three layers, and I kept them strictly separate:
- engine/ is plain Python with NumPy and SciPy. It knows nothing about the web. Each solver returns the numerical result, the derivation steps as LaTeX strings with the values substituted, and the result of the cross-check. Physical constants come from SciPy's CODATA tables, not from numbers I typed in.
- The server is a thin FastAPI app for local development. It only turns HTTP requests into engine calls.
- The frontend is ES modules without a framework. Plotly draws the fields and the Smith chart, KaTeX renders the derivations.
The chapters follow the course order: vectors and coordinate systems, electrostatics, magnetostatics, Maxwell's equations, plane waves in lossy media, reflection and transmission, transmission lines, and waveguides and antennas.
Verification: every number is computed twice
This is the part I care about most. A result counts as verified only if a second method agrees with it within a tolerance. If they disagree, the page says so next to the number instead of hiding it. Some examples of the pairs:
| Quantity | Method A | Method B (check) |
|---|---|---|
| α, β in a lossy medium | Closed-form expressions | Real and imaginary parts of γ = √(jωμ(σ + jωε)) |
| Zin of a line | Z0(ZL + jZ0tan βl)/(Z0 + jZLtan βl) | ABCD-matrix cascade of short sections |
| Plane-wave fields | Phasor solution | Put the fields back into Maxwell's equations, check the residual |
| Reflection at an interface | Γ and τ from impedances | Power balance: |Γ|² + transmitted power ratio = 1 |
On top of that there are 439 pytest tests. Many of them test limiting cases instead of single numbers, for example that a lossy medium with σ → 0 gives the lossless result, or that a quarter-wave line turns a short into an open. A separate verification report compares 30 reference problems with the site's numbers and can be downloaded as CSV.
# run the full suite
python -m pytest -q -p no:anyio tests
Python in the browser with Pyodide
I didn't want two engines, one in Python for the tests and one in JavaScript for the web page, because the two would drift apart and the tests would stop meaning anything. Pyodide solved that: it is CPython compiled to WebAssembly, and it can load NumPy and SciPy. The exact same engine/ package runs on the server and in the visitor's browser.
The cost is the first load, which downloads about 30 MB. After that the browser caches it and the app works without a server, which also means it can be hosted on GitHub Pages for free. I think that trade-off is worth it for a study tool, but it is the first thing I would look at if the app had many mobile users.
The assistant
ElectroField has a built-in tutor that works offline and only uses numbers the engine already computed. There is also an optional assistant that uses Claude with tool use: the model does not calculate anything itself, it chooses which engine solver to call and with which parameters, and the answer it shows comes from the engine. I designed it this way because a language model doing arithmetic on complex impedances is exactly the kind of "reasonable looking but wrong" answer the project was built to avoid.
What I learned
- Writing the check is often harder than writing the solver, and it is where most of my bugs were found.
- Complex square roots need care: the principal branch is not always the physical one, and the sign of α decides whether a wave decays or grows.
- Separating the engine from the interface early saved me later. Because the engine had no web code in it, adding the browser version was mostly a packaging job.
- Units and constants should come from one place. I stopped typing 8.854e-12 by hand very quickly.
Neden yaptım
Elektromanyetik, bir çözümün her adımını takip edip yine de sonuçtaki sayıya güvenemediğim ilk ders oldu. Bir yansıma katsayısındaki işaret hatası ya da karmaşık karekökte yanlış dalı seçmek, gayet mantıklı görünen bir cevap veriyor. Kitaplar (Ulaby & Ravaioli ve Cheng) yöntemi anlatıyor ama ben kendi başıma bir parametreyi değiştirdiğimde yeni cevabımın doğru olup olmadığını anlamanın bir yolu yoktu.
Bu yüzden her konu için küçük Python fonksiyonları yazmaya başladım ve her fonksiyonu yazarken aynı sayıya ulaşmanın ikinci bir yolunu da yazdım. Zamanla bu fonksiyonlar bir motora dönüştü, motorun da bir arayüze ihtiyacı oldu. ElectroField böyle ortaya çıktı.
Mimari
Proje üç katmandan oluşuyor ve bunları birbirinden kesin olarak ayrı tuttum:
- engine/ NumPy ve SciPy kullanan düz Python. Web hakkında hiçbir şey bilmiyor. Her çözücü sayısal sonucu, değerleri yerine konmuş LaTeX türetme adımlarını ve çapraz kontrolün sonucunu döndürüyor. Fiziksel sabitler elle yazdığım sayılardan değil, SciPy'ın CODATA tablolarından geliyor.
- Sunucu, yerel geliştirme için ince bir FastAPI uygulaması. Tek işi HTTP isteklerini motor çağrılarına çevirmek.
- Arayüz framework kullanmayan ES modüllerinden oluşuyor. Alanları ve Smith abağını Plotly çiziyor, türetmeleri KaTeX gösteriyor.
Bölümler ders sırasını takip ediyor: vektörler ve koordinat sistemleri, elektrostatik, manyetostatik, Maxwell denklemleri, kayıplı ortamda düzlem dalgalar, yansıma ve iletim, iletim hatları, dalga kılavuzları ve antenler.
Doğrulama: her sayı iki kez hesaplanıyor
Projede en çok önem verdiğim kısım bu. Bir sonuç, ancak ikinci bir yöntem onu belirli bir tolerans içinde doğrularsa doğrulanmış sayılıyor. İki yöntem uyuşmazsa sayfa bunu saklamak yerine sayının hemen yanında söylüyor. Birkaç örnek:
| Büyüklük | Yöntem A | Yöntem B (kontrol) |
|---|---|---|
| Kayıplı ortamda α, β | Kapalı form ifadeler | γ = √(jωμ(σ + jωε)) ifadesinin gerçel ve sanal kısımları |
| Hattın Zin değeri | Z0(ZL + jZ0tan βl)/(Z0 + jZLtan βl) | Kısa parçaların ABCD matrisleriyle art arda bağlanması |
| Düzlem dalga alanları | Fazör çözümü | Alanları Maxwell denklemlerine geri koyup artığı kontrol etmek |
| Arayüzde yansıma | Empedanslardan Γ ve τ | Güç dengesi: |Γ|² + iletilen güç oranı = 1 |
Bunun üstüne 439 pytest testi var. Bunların çoğu tek bir sayıyı değil, limit durumlarını test ediyor; örneğin σ → 0 olduğunda kayıplı ortamın kayıpsız sonucu vermesi ya da çeyrek dalga boyu hattın kısa devreyi açık devreye çevirmesi. Ayrıca 30 referans problemi sitedeki sayılarla karşılaştıran ve CSV olarak indirilebilen bir doğrulama raporu da var.
# tüm testleri çalıştır
python -m pytest -q -p no:anyio tests
Pyodide ile tarayıcıda Python
Biri testler için Python'da, diğeri web sayfası için JavaScript'te olan iki ayrı motor istemedim; çünkü ikisi zamanla birbirinden ayrışır ve testlerin bir anlamı kalmaz. Bunu Pyodide çözdü: WebAssembly'ye derlenmiş CPython ve NumPy ile SciPy'ı yükleyebiliyor. Birebir aynı engine/ paketi hem sunucuda hem de ziyaretçinin tarayıcısında çalışıyor.
Bunun bedeli ilk açılış: yaklaşık 30 MB indiriliyor. Sonrasında tarayıcı bunu önbelleğe alıyor ve uygulama sunucusuz çalışıyor; bu da sitenin GitHub Pages'te ücretsiz barındırılabilmesi demek. Bir çalışma aracı için bu takasın mantıklı olduğunu düşünüyorum, ama uygulamanın çok sayıda mobil kullanıcısı olsaydı ilk bakacağım yer burası olurdu.
Asistan
ElectroField'da çevrimdışı çalışan ve sadece motorun zaten hesapladığı sayıları kullanan bir yardımcı var. Bir de isteğe bağlı, Claude'u tool use ile kullanan bir asistan var: model kendisi hiçbir şey hesaplamıyor, sadece hangi motor çözücüsünün hangi parametrelerle çağrılacağını seçiyor; gösterilen cevap motordan geliyor. Bunu bilerek böyle tasarladım, çünkü karmaşık empedanslar üzerinde aritmetik yapan bir dil modeli, tam da bu projenin önlemek için yapıldığı "mantıklı görünen ama yanlış" cevap türünü üretir.
Ne öğrendim
- Kontrolü yazmak çoğu zaman çözücüyü yazmaktan daha zor ve hatalarımın çoğunu orada buldum.
- Karmaşık karekök dikkat istiyor: esas dal her zaman fiziksel olan dal değil ve α'nın işareti dalganın sönümlenip sönümlenmediğine karar veriyor.
- Motoru arayüzden erkenden ayırmak sonradan çok işime yaradı. Motorda hiç web kodu olmadığı için tarayıcı sürümünü eklemek büyük ölçüde bir paketleme işiydi.
- Birimler ve sabitler tek bir yerden gelmeli. 8.854e-12'yi elle yazmayı çok çabuk bıraktım.