40 Commits

Author SHA1 Message Date
c5dc320989 2-port SOLT cal
Some checks failed
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Failing after -56s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-07-08 00:02:03 -06:00
452dddc19c functional 1 port calibration 2025-07-07 23:22:36 -06:00
3c02a4b388 allow downselecting measurements 2025-07-07 22:49:49 -06:00
339dbe255e smash some functions together
Some checks failed
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Failing after -1m4s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-07-07 22:28:21 -06:00
81143a72c4 bettah port handling
Some checks failed
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Failing after -58s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-07-07 22:15:48 -06:00
f021780971 working 2-port capture 2025-07-07 20:13:59 -06:00
6f947a28fa add really basic usage file for developing vna class outside of gui 2025-07-07 20:04:54 -06:00
581131f1e0 document and rearrange some stuff 2025-07-07 20:04:16 -06:00
adf6e40752 change default IP to what I have configured on my pluto (revert later) 2025-07-07 19:43:15 -06:00
411f96dd87 only define default ip once 2025-07-07 19:39:16 -06:00
b4e4b689ea Add basic switch control for white-wired pluto io shield
Some checks failed
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Failing after -53s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-07-07 19:36:59 -06:00
2012c37ccb add image of my janky cal standard
Some checks failed
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Failing after -1m6s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-26 22:00:08 -06:00
5184c05bb5 README formatting
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -1m0s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-26 21:37:41 -06:00
8d7f87c9e6 add links to sister projects
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -1m2s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-26 21:08:56 -06:00
776c9cc491 typing and defaults
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -48s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-26 21:06:15 -06:00
994080e574 start a pickle-less cal read/write 2025-06-26 21:06:15 -06:00
b6cb1ecde7 DAC updates 2025-06-26 21:06:15 -06:00
383fe3ceea slight power cal improvement 2025-06-26 21:06:15 -06:00
9912e318a8 add help links 2025-06-26 21:06:15 -06:00
d8b1a56c99 rename config path 2025-06-26 21:06:15 -06:00
505b374e8f Update README.md
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -1m0s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-26 08:35:30 -06:00
c73533b156 Update README.md
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -41s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-26 08:13:33 -06:00
594c72f2bf Update README.md
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -1m1s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-04 14:14:59 -06:00
43d9486edf Update README.md
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -1m1s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-04 14:10:29 -06:00
27f7277c45 Update README.md
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in -32s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-06-04 13:55:14 -06:00
1a76c4e7ab IO control on pluto appears to be working
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in 1m27s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-03-09 01:54:05 -07:00
67ddbb0f90 use tabs for plots 2025-03-08 23:11:01 -07:00
97497e640e disable some plots that are annoying me 2025-03-08 23:05:35 -07:00
e78cf5595a fix import issue when running gui entry point 2025-03-08 23:02:02 -07:00
086f348084 add pypi link
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in 16s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-01-17 00:37:30 -07:00
8f61cd85d0 fix vswr plots for S11 > 0dB
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in 21s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Successful in 25s
2025-01-17 00:34:29 -07:00
80fd25e7e4 add really rudimentary 1-port calibration support 2025-01-17 00:34:01 -07:00
30fb1190bb accept a raw IP
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in 19s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-01-16 23:44:04 -07:00
fa80af8447 adjustable ip address at runtime 2025-01-16 23:39:19 -07:00
926a6abf1f split plots into separate file 2025-01-16 23:19:41 -07:00
2285bb78c1 minor config stuf 2025-01-16 23:17:40 -07:00
894d980a64 update README.md 2025-01-16 23:12:29 -07:00
9a922762fa basic config file stuff 2025-01-16 23:12:18 -07:00
26682f1741 remove simulation
All checks were successful
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Build distribution 📦 (push) Successful in 18s
Publish Python 🐍 distribution 📦 to PyPI and TestPyPI / Publish Python 🐍 distribution 📦 to PyPI (push) Has been skipped
2025-01-16 22:12:31 -07:00
f1f6c0d45b rearrange readme 2025-01-16 21:55:46 -07:00
10 changed files with 1265 additions and 257 deletions

View File

@ -1,5 +1,9 @@
# Charon VNA # Charon VNA
<!-- ![PyPi Downloads](https://img.shields.io/pypi/dm/charon-vna) -->
<!-- ![Last Commit](https://img.shields.io/gitea/last-commit/brendanhaines/charon-vna?gitea_url=https%3A%2F%2Fgit.brendanhaines.com) -->
<!-- ![Workflow Status](https://git.brendanhaines.com/brendanhaines/charon-vna/actions/workflows/python_publish.yml/badge.svg) -->
Named after [Pluto's moon](https://en.wikipedia.org/wiki/Charon_(moon)), Charon uses the [ADI Pluto SDR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/adalm-pluto.html) as a vector network analyzer. The basic usage is as a 1 port VNA but this can be extended to arbitrarily many ports with the addition of a couple RF switches. Named after [Pluto's moon](https://en.wikipedia.org/wiki/Charon_(moon)), Charon uses the [ADI Pluto SDR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/adalm-pluto.html) as a vector network analyzer. The basic usage is as a 1 port VNA but this can be extended to arbitrarily many ports with the addition of a couple RF switches.
## Installation ## Installation
@ -7,7 +11,38 @@ Named after [Pluto's moon](https://en.wikipedia.org/wiki/Charon_(moon)), Charon
1. Install LibIIO. This is a dependency of [PyADI-IIO](https://wiki.analog.com/resources/tools-software/linux-software/pyadi-iio). 1. Install LibIIO. This is a dependency of [PyADI-IIO](https://wiki.analog.com/resources/tools-software/linux-software/pyadi-iio).
On Ubuntu 22.04 just run `sudo apt-get install -y libiio-dev` On Ubuntu 22.04 just run `sudo apt-get install -y libiio-dev`
2. `pip install charon-vna` 2. Charon releases are published on [PyPi](https://pypi.org/project/charon-vna/). Install using pip:
`pip install charon-vna`
## Hardware Setup
You need a few things:
- [Analog Devices Pluto SDR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/adalm-pluto.html)
- Any variant of the Pluto *should* work too such as the [Pluto+](https://github.com/plutoplus/plutoplus?tab=readme-ov-file) however I have only tested with the basic flavor
- Note that you _must_ have two receive ports which means revision C or later of the basic Pluto
- Directional couplers (1 per port up to 4 ports)
- I have been using [AAMCS-UDC-0.5G-18G-10dB-Sf](http://www.aa-mcs.com/wp-content/uploads/documents/AAMCS-UDC-0.5G-18G-10dB-Sf.pdf)
- [Cerberus RF switch](https://git.brendanhaines.com/brendanhaines/cerberus_sp4t) + [Pluto IO Shield](https://git.brendanhaines.com/brendanhaines/pluto_io_shield)
- Optional. Without this you'll be limited to S11 and uncalibrated S21 measurements (with required re-cabling)
- There's nothing special about this particular board, if you want more than 4 ports you can make your own pretty easily. You just need 3 SPxT switches. Note that these switches will see tons of cycles so avoid mechanical switches
- SMA cables
- Calibration standard
- Ideally something with s-parameters measured on a better VNA
- I have used a basic SMA load and two modified SMA jacks with decent results
![calibration standard](img/calibration_standard.jpg)
### Pluto Configuration
Most of my testing is with Pluto firmware [v0.39](https://github.com/analogdevicesinc/plutosdr-fw/releases/tag/v0.39) though this may work with other firmware versions. I had issues with the Pluto sometimes seeing no signal which resolved when I upgraded from v0.35. Instructions for upgrading firmware are on the [Analog Devices wiki](https://wiki.analog.com/university/tools/pluto/users/firmware).
We need two receive channels on the SDR. If you have a Pluto+ that should already be configured and you can skip this step.
Analog devices has a [guide](https://wiki.analog.com/university/tools/pluto/users/customizing#updating_to_the_ad9364) for enabling the second channel. Ideally this should be set as `ad9361` to enable a wider band of operation in addition to the second channel, however the critical setting is enabling 2r2t. SSH into the Pluto and run the following:
```bash
fw_setenv attr_name compatible
fw_setenv attr_val ad9361
fw_setenv mode 2r2t
```
## Usage ## Usage
@ -19,6 +54,7 @@ It will also be accessible over a socket to enable test automation with external
TBD TBD
### Power Calibration ### Power Calibration
I include a default output power lookup table. This is derived from two TX channels of two Pluto SDRs and does not include any of the loss of a coupler or Charon switch board. I include a default output power lookup table. This is derived from two TX channels of two Pluto SDRs and does not include any of the loss of a coupler or Charon switch board.
Absolute output power is generally not well calibrated for VNAs anyway and has negligible impact on most measurements so this is probably sufficient for most users. If you're trying to run a power sweep this may be insufficient. Absolute output power is generally not well calibrated for VNAs anyway and has negligible impact on most measurements so this is probably sufficient for most users. If you're trying to run a power sweep this may be insufficient.
@ -27,22 +63,16 @@ If you have an RF power meter you can generate your own power calibration.
Note that unlike the main calibration, power calibration frequencies do not need to match the measurement frequencies. Values are interpolated. Note that unlike the main calibration, power calibration frequencies do not need to match the measurement frequencies. Values are interpolated.
## Hardware ## References
You need a few things: #### Pluto Default Connection Settings
- [Analog Devices Pluto SDR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/adalm-pluto.html).
Any variant of the Pluto *should* work too such as the [Pluto+](https://github.com/plutoplus/plutoplus?tab=readme-ov-file) however I have only tested with the basic flavor.
- Directional couplers (1 per port up to 4 ports).
I have been using [AAMCS-UDC-0.5G-18G-10dB-Sf](http://www.aa-mcs.com/wp-content/uploads/documents/AAMCS-UDC-0.5G-18G-10dB-Sf.pdf)
- Charon switch board - coming soon.
Without this, you'll be limited to S11 and uncalibrated S21 measurements (with required re-cabling).
There's nothing special about this particular board, if you want more than 4 ports you can make your own pretty easily. You just need 3 SPxT switches. Note that these switches will see tons of cycles so avoid mechanical switches.
- SMA cables
### Pluto Configuration - user: `root`
- password: `analog`
- ip: `192.168.2.1`
Most of my testing is with Pluto firmware [v0.39](https://github.com/analogdevicesinc/plutosdr-fw/releases/tag/v0.39) though this may work with other firmware versions. Instructions for upgrading firmware are on the [Analog Devices wiki](https://wiki.analog.com/university/tools/pluto/users/firmware). ## Alternatives
We need two receive channels on the SDR. If you have a Pluto+ that should already be configured and you can skip this step. - [NanoVNA](https://nanovna.com/). 2-ports. 50 kHz - 2.7 GHz. Degraded performance above 1.5 GHz. S11 and S21 only.
- [pluto-network-analyzer](https://github.com/fromconcepttocircuit/pluto-network-analyzer). 2-ports. 100 MHz - 3 GHz. S11 and S21 only. Uses a [wideband RF bridge](https://www.60dbm.com/product/rf-bridge-1-3000-mhz/) instead of a coupler
Analog devices has a [guide](https://wiki.analog.com/university/tools/pluto/users/customizing#updating_to_the_ad9364) for enabling the second channel. Ideally this should be set as `ad9361` to enable a wider band of operation in addition to the second channel, however the critical setting is enabling 2r2t. - [LibreVNA](https://github.com/jankae/LibreVNA). 2-ports. 100 KHz - 6 GHz. I've never used this but it is almost certainly faster than Charon. Not sure how the performance compares. $700 on [AliExpress](https://www.aliexpress.us/item/3256802242049773.html?gatewayAdapt=glo2usa4itemAdapt)

View File

@ -0,0 +1,505 @@
{
"frequency": [
80000000.0,
80841683.36673346,
81683366.73346694,
82525050.1002004,
83366733.46693386,
84208416.83366734,
85050100.2004008,
85891783.56713426,
86733466.93386774,
87575150.3006012,
88416833.66733468,
89258517.03406814,
90100200.4008016,
90941883.76753508,
91783567.13426854,
92625250.501002,
93466933.86773548,
94308617.23446894,
95150300.6012024,
95991983.96793588,
96833667.33466934,
97675350.70140281,
98517034.06813627,
99358717.43486974,
100200400.8016032,
101042084.16833667,
101883767.53507014,
102725450.90180361,
103567134.26853707,
104408817.63527054,
105250501.00200401,
106092184.36873747,
106933867.73547095,
107775551.10220441,
108617234.46893787,
109458917.83567134,
110300601.20240481,
111142284.56913827,
111983967.93587175,
112825651.30260521,
113667334.66933867,
114509018.03607213,
115350701.40280561,
116192384.76953909,
117034068.13627255,
117875751.50300601,
118717434.86973947,
119559118.23647295,
120400801.60320641,
121242484.96993989,
122084168.33667335,
122925851.70340681,
123767535.07014027,
124609218.43687375,
125450901.80360723,
126292585.17034069,
127134268.53707415,
127975951.90380761,
128817635.27054109,
129659318.63727455,
130501002.00400802,
131342685.37074149,
132184368.73747495,
133026052.10420841,
133867735.47094189,
134709418.83767536,
135551102.20440882,
136392785.5711423,
137234468.93787575,
138076152.30460924,
138917835.67134267,
139759519.03807616,
140601202.40480962,
141442885.7715431,
142284569.13827655,
143126252.50501,
143967935.8717435,
144809619.23847696,
145651302.60521042,
146492985.97194389,
147334669.33867735,
148176352.70541084,
149018036.07214427,
149859719.43887776,
150701402.80561122,
151543086.17234468,
152384769.53907818,
153226452.9058116,
154068136.2725451,
154909819.63927856,
155751503.00601202,
156593186.3727455,
157434869.73947895,
158276553.10621244,
159118236.4729459,
159959919.83967936,
160801603.20641282,
161643286.57314628,
162484969.93987978,
163326653.30661324,
164168336.6733467,
165010020.04008016,
165851703.40681362,
166693386.7735471,
167535070.14028054,
168376753.50701404,
169218436.8737475,
170060120.24048096,
170901803.60721445,
171743486.97394788,
172585170.34068137,
173426853.70741484,
174268537.0741483,
175110220.4408818,
175951903.80761522,
176793587.1743487,
177635270.54108217,
178476953.90781564,
179318637.2745491,
180160320.64128256,
181002004.00801605,
181843687.37474948,
182685370.74148297,
183527054.10821643,
184368737.4749499,
185210420.8416834,
186052104.20841682,
186893787.5751503,
187735470.94188377,
188577154.30861723,
189418837.67535073,
190260521.04208416,
191102204.40881765,
191943887.7755511,
192785571.14228457,
193627254.50901806,
194468937.8757515,
195310621.242485,
196152304.60921845,
196993987.9759519,
197835671.34268537,
198677354.70941883,
199519038.07615232,
200360721.44288576,
201202404.80961925,
202044088.1763527,
202885771.54308617,
203727454.90981966,
204569138.2765531,
205410821.6432866,
206252505.01002005,
207094188.3767535,
207935871.743487,
208777555.11022043,
209619238.47695392,
210460921.8436874,
211302605.21042085,
212144288.5771543,
212985971.94388777,
213827655.31062126,
214669338.67735472,
215511022.04408818,
216352705.41082165,
217194388.7775551,
218036072.14428857,
218877755.51102206,
219719438.87775552,
220561122.24448898,
221402805.61122245,
222244488.9779559,
223086172.3446894,
223927855.71142286,
224769539.07815632,
225611222.44488978,
226452905.81162325,
227294589.1783567,
228136272.5450902,
228977955.91182366,
229819639.27855712,
230661322.64529058,
231503006.01202404,
232344689.37875754,
233186372.745491,
234028056.11222446,
234869739.47895792,
235711422.84569138,
236553106.21242484,
237394789.57915834,
238236472.9458918,
239078156.31262526,
239919839.67935872,
240761523.04609218,
241603206.41282564,
242444889.77955914,
243286573.1462926,
244128256.51302606,
244969939.87975952,
245811623.24649298,
246653306.61322647,
247494989.97995993,
248336673.3466934,
249178356.71342686,
250020040.08016032,
250861723.44689378,
251703406.81362727,
252545090.18036073,
253386773.5470942,
254228456.91382766,
255070140.28056112,
255911823.6472946,
256753507.01402807,
257595190.38076153,
258436873.747495,
259278557.11422846,
260120240.48096192,
260961923.8476954,
261803607.21442887,
262645290.58116233,
263486973.9478958,
264328657.31462926,
265170340.68136275,
266012024.0480962,
266853707.41482967,
267695390.78156313,
268537074.1482966,
269378757.51503,
270220440.8817636,
271062124.248497,
271903807.61523044,
272745490.98196393,
273587174.3486974,
274428857.71543086,
275270541.08216435,
276112224.44889784,
276953907.8156313,
277795591.1823647,
278637274.5490982,
279478957.9158317,
280320641.2825651,
281162324.6492986,
282004008.0160321,
282845691.38276553,
283687374.74949896,
284529058.1162325,
285370741.48296595,
286212424.8496994,
287054108.21643287,
287895791.58316636,
288737474.9498998,
289579158.3166333,
290420841.6833668,
291262525.0501002,
292104208.41683364,
292945891.78356713,
293787575.1503006,
294629258.51703405,
295470941.88376755,
296312625.25050104,
297154308.61723447,
297995991.98396796,
298837675.35070145,
299679358.7174349,
300521042.0841683,
301362725.4509018,
302204408.8176353,
303046092.1843687,
303887775.5511022,
304729458.9178357,
305571142.28456914,
306412825.6513026,
307254509.0180361,
308096192.38476956,
308937875.751503,
309779559.1182365,
310621242.48497,
311462925.8517034,
312304609.2184369,
313146292.5851704,
313987975.9519038,
314829659.31863725,
315671342.68537074,
316513026.05210423,
317354709.41883767,
318196392.78557116,
319038076.15230465,
319879759.5190381,
320721442.8857715,
321563126.25250506,
322404809.6192385,
323246492.9859719,
324088176.3527054,
324929859.7194389,
325771543.08617234,
326613226.45290583,
327454909.8196393,
328296593.18637276,
329138276.5531062,
329979959.9198397,
330821643.2865732,
331663326.6533066,
332505010.0200401,
333346693.3867736,
334188376.753507,
335030060.12024045,
335871743.486974,
336713426.85370743,
337555110.22044086,
338396793.58717436,
339238476.95390785,
340080160.3206413,
340921843.6873748,
341763527.05410826,
342605210.4208417,
343446893.7875751,
344288577.1543086,
345130260.5210421,
345971943.88777554,
346813627.25450903,
347655310.6212425,
348496993.98797596,
349338677.35470945,
350180360.7214429,
351022044.08817637,
351863727.45490986,
352705410.8216433,
353547094.1883768,
354388777.5551102,
355230460.9218437,
356072144.28857714,
356913827.65531063,
357755511.0220441,
358597194.38877755,
359438877.75551105,
360280561.1222445,
361122244.48897797,
361963927.85571146,
362805611.2224449,
363647294.5891784,
364488977.9559118,
365330661.3226453,
366172344.6893788,
367014028.05611223,
367855711.4228457,
368697394.78957915,
369539078.15631264,
370380761.5230461,
371222444.88977957,
372064128.25651306,
372905811.6232465,
373747494.98998,
374589178.3567134,
375430861.7234469,
376272545.0901804,
377114228.4569138,
377955911.8236473,
378797595.19038075,
379639278.55711424,
380480961.92384773,
381322645.29058117,
382164328.65731466,
383006012.0240481,
383847695.3907816,
384689378.7575151,
385531062.1242485,
386372745.490982,
387214428.8577154,
388056112.2244489,
388897795.59118235,
389739478.95791584,
390581162.32464933,
391422845.69138277,
392264529.05811626,
393106212.4248497,
393947895.7915832,
394789579.1583167,
395631262.5250501,
396472945.8917836,
397314629.258517,
398156312.6252505,
398997995.991984,
399839679.35871744,
400681362.72545093,
401523046.09218436,
402364729.45891786,
403206412.8256513,
404048096.1923848,
404889779.5591183,
405731462.9258517,
406573146.2925852,
407414829.6593186,
408256513.0260521,
409098196.3927856,
409939879.75951904,
410781563.12625253,
411623246.49298596,
412464929.85971946,
413306613.22645295,
414148296.5931864,
414989979.95991987,
415831663.3266533,
416673346.6933868,
417515030.0601203,
418356713.4268537,
419198396.7935872,
420040080.16032064,
420881763.52705413,
421723446.89378756,
422565130.26052105,
423406813.62725455,
424248496.993988,
425090180.36072147,
425931863.7274549,
426773547.0941884,
427615230.4609219,
428456913.8276553,
429298597.1943888,
430140280.56112224,
430981963.92785573,
431823647.2945892,
432665330.66132265,
433507014.02805614,
434348697.3947896,
435190380.76152307,
436032064.12825656,
436873747.49499,
437715430.8617235,
438557114.2284569,
439398797.5951904,
440240480.96192384,
441082164.3286573,
441923847.6953908,
442765531.06212425,
443607214.42885774,
444448897.7955912,
445290581.16232467,
446132264.52905816,
446973947.8957916,
447815631.2625251,
448657314.6292585,
449498997.995992,
450340681.3627255,
451182364.7294589,
452024048.0961924,
452865731.46292585,
453707414.82965934,
454549098.1963928,
455390781.56312627,
456232464.92985976,
457074148.2965932,
457915831.6633267,
458757515.0300601,
459599198.3967936,
460440881.7635271,
461282565.1302605,
462124248.496994,
462965931.86372745,
463807615.23046094,
464649298.59719443,
465490981.96392787,
466332665.33066136,
467174348.6973948,
468016032.0641283,
468857715.4308618,
469699398.7975952,
470541082.1643287,
471382765.5310621,
472224448.8977956,
473066132.26452905,
473907815.63126254,
474749498.99799603,
475591182.36472946,
476432865.73146296,
477274549.0981964,
478116232.4649299,
478957915.83166337,
479799599.1983968,
480641282.5651303,
481482965.9318637,
482324649.2985972,
483166332.6653307,
484008016.03206414,
484849699.39879763,
485691382.76553106,
486533066.13226455,
487374749.498998,
488216432.8657315,
489058116.23246497,
489899799.5991984,
490741482.9659319,
491583166.3326653,
492424849.6993988,
493266533.0661323,
494108216.43286574,
494949899.79959923,
495791583.16633266,
496633266.53306615,
497474949.89979964,
498316633.2665331,
499158316.63326657,
500000000.0
],
"power": -5
}

View File

@ -0,0 +1,25 @@
import json
import subprocess
import numpy as np
from charon_vna.gui import PATH_CONFIG_DEFAULT
config = dict(
frequency=np.linspace(80e6, 500e6, 500).tolist(),
power=-5,
)
with open(PATH_CONFIG_DEFAULT, "w") as f:
json.dump(config, f)
# autoformat
subprocess.run(
[
"python",
"-m",
"json.tool",
PATH_CONFIG_DEFAULT.resolve().as_posix(),
PATH_CONFIG_DEFAULT.resolve().as_posix(),
]
)

View File

@ -1,167 +1,63 @@
# %% imports # %% imports
import json
import pickle
import re
import sys import sys
import webbrowser
from pathlib import Path from pathlib import Path
from typing import Callable, List, Literal, Tuple from typing import List
import matplotlib as mpl import matplotlib as mpl
import numpy as np import numpy as np
import skrf as rf
import xarray as xr import xarray as xr
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
from matplotlib.lines import Line2D
from matplotlib.ticker import EngFormatter
from numpy import typing as npt from numpy import typing as npt
from PySide6.QtGui import QAction, QKeySequence from PySide6.QtGui import QAction, QKeySequence
from PySide6.QtWidgets import ( from PySide6.QtWidgets import (
QApplication, QApplication,
QFileDialog, QFileDialog,
QInputDialog, QInputDialog,
QLineEdit,
QMainWindow, QMainWindow,
QMenu, QMenu,
QProgressBar, QProgressBar,
QTabWidget,
QVBoxLayout, QVBoxLayout,
QWidget, QWidget,
) )
from skrf import plotting as rf_plt
from vna import Charon
from charon_vna.util import db20, s2vswr from charon_vna.plots import PlotWidget
from charon_vna.util import net2s, s2net
from charon_vna.vna import Charon
# %% # %%
DEFAULT_CONFIG = dict( PATH_CONFIG_DEFAULT = Path(__file__).parent / "config_default.json"
frequency=np.arange(1e9, 2e9, 11), # Hz
power=-5, # dB
)
CONFIG_SUFFIX = ".json" CONFIG_SUFFIX = ".json"
class PlotWidget(QWidget):
traces: List[Tuple[int | str]]
lines: List[Line2D]
def __init__(self, type_: str = "logmag"):
super().__init__()
self.traces = [(1, 1)]
layout = QVBoxLayout()
self.setLayout(layout)
self.fig = plt.Figure(figsize=(5, 4), dpi=100, tight_layout=True)
self.ax = self.fig.add_subplot(111)
self.set_plot_type(type_)
self.lines = [
self.ax.plot([np.nan], [np.nan], label="$S_{" + str(m) + str(n) + "}$")[0] for m, n in self.traces
]
self.ax.legend(loc="upper right")
canvas = FigureCanvasQTAgg(self.fig)
layout.addWidget(canvas)
# toolbar = QToolBar("Toolbar")
# toolbar.addAction("blah")
# self.addToolBar(toolbar)
def set_plot_type(
self,
type_: Literal["logmag", "phase", "vswr", "smith"],
sweep_type: Literal["frequency", "time"] = "frequency",
) -> None:
if sweep_type != "frequency":
raise NotImplementedError("Only frequency sweeps are currently supported")
if type_ == "logmag":
self.setup_logmag()
elif type_ == "phase":
self.setup_phase()
elif type_ == "vswr":
self.setup_vswr()
elif type_ == "smith":
self.setup_smith()
else:
raise ValueError(f"Unknown plot type: {type_}")
self._plot_type = type_
def update_plot(self, data: xr.DataArray):
if self._plot_type == "logmag":
self.update_logmag(data)
elif self._plot_type == "phase":
self.update_phase(data)
elif self._plot_type == "vswr":
self.update_vswr(data)
elif self._plot_type == "smith":
self.update_smith(data)
def setup_rect(self) -> None:
self.ax.grid(True)
self.ax.xaxis.set_major_formatter(EngFormatter())
self.ax.set_xlabel("Frequency [Hz]")
def update_rect(self, data: xr.DataArray, func: Callable[[npt.ArrayLike], npt.ArrayLike]) -> None:
self.ax.set_xlim(data["frequency"].min().data, data["frequency"].max().data)
for ii, (m, n) in enumerate(self.traces):
self.lines[ii].set_xdata(data["frequency"])
self.lines[ii].set_ydata(func(data.sel(m=m, n=n)))
self.fig.canvas.draw()
def setup_logmag(self, ylim: List[float] = [-30, 30]) -> None:
self.setup_rect()
self.ax.set_ylim(ylim)
self.ax.set_ylabel("Amplitude [dB]")
def update_logmag(self, data: xr.DataArray) -> None:
self.update_rect(data, db20)
def setup_phase(self) -> None:
self.setup_rect()
self.ax.set_ylim(-200, 200)
self.ax.set_ylabel("Phase [deg]")
def update_phase(self, data: xr.DataArray):
self.update_rect(data, lambda s: np.angle(s, deg=True))
def setup_vswr(self) -> None:
self.setup_rect()
self.ax.set_yticks(np.arange(1, 11))
self.ax.set_ylim(1, 10)
self.ax.set_ylabel("VSWR")
def update_vswr(self, data: xr.DataArray) -> None:
self.update_rect(data, s2vswr)
def setup_smith(self) -> None:
self.ax.grid(False)
self.ax.set_xlim(-1, 1)
self.ax.set_ylim(-1, 1)
self.ax.set_aspect("equal")
rf_plt.smith(ax=self.ax, smithR=1, chart_type="z", draw_vswr=None)
def update_smith(self, data: xr.DataArray) -> None:
for ii, (m, n) in enumerate(self.traces):
sel = data.sel(m=m, n=n)
self.lines[ii].set_xdata(sel.real)
self.lines[ii].set_ydata(sel.imag)
self.fig.canvas.draw()
# Subclass QMainWindow to customize your application's main window
class MainWindow(QMainWindow): class MainWindow(QMainWindow):
config_path: Path | None config_path: Path | None
# device: Charon # device: Charon
plots: List[PlotWidget] plots: List[PlotWidget]
def __init__(self): def __init__(self, ip: str | None = None):
super().__init__() super().__init__()
self.config_path = None self.config_path = PATH_CONFIG_DEFAULT
self._frequency = np.linspace(1e9, 2e9, 101) # TODO: read frequency from config with open(self.config_path, "r") as f:
config = json.load(f)
self._frequency = config["frequency"]
self.vna = Charon("ip:192.168.3.1", frequency=DEFAULT_CONFIG["frequency"]) vna_kwargs = dict(
frequency=self._frequency,
)
if ip is not None:
vna_kwargs["ip"] = ip
self.vna = Charon(**vna_kwargs)
self.active_port = 0
self.vna.set_switches(a=self.active_port, b=self.active_port)
mpl.use("QtAgg") mpl.use("QtAgg")
@ -197,16 +93,28 @@ class MainWindow(QMainWindow):
action_trigger.triggered.connect(self.capture) action_trigger.triggered.connect(self.capture)
action_trigger.setShortcut("Ctrl+T") action_trigger.setShortcut("Ctrl+T")
menu_stimulus.addAction(action_trigger) menu_stimulus.addAction(action_trigger)
action_p0 = QAction("Switch &Port", self)
action_p0.triggered.connect(self.toggle_port)
menu_stimulus.addAction(action_p0)
menu_calibration = QMenu("&Calibration") menu_calibration = QMenu("&Calibration")
menubar.addMenu(menu_calibration) menubar.addMenu(menu_calibration)
action_cal_solt = QAction("&SOLT", self)
action_cal_solt.triggered.connect(self.calibrate_solt)
menu_calibration.addAction(action_cal_solt)
menu_simulation = QMenu("Si&mulation") menu_help = QMenu("&Help")
menubar.addMenu(menu_simulation) menubar.addMenu(menu_help)
action_generate_data = QAction("&Generate data", self) action_open_homepage = QAction("&Documentation", self)
menu_file.addAction(action_generate_data) action_open_homepage.triggered.connect(
action_generate_data.triggered.connect(self.generate_sim_data) lambda: webbrowser.open("https://git.brendanhaines.com/brendanhaines/charon_vna")
action_generate_data.setShortcut(QKeySequence("Ctrl+G")) )
menu_help.addAction(action_open_homepage)
action_report_issue = QAction("&Report an Issue", self)
action_report_issue.triggered.connect(
lambda: webbrowser.open("https://git.brendanhaines.com/brendanhaines/charon_vna/issues")
)
menu_help.addAction(action_report_issue)
# Content # Content
window_layout = QVBoxLayout() window_layout = QVBoxLayout()
@ -216,19 +124,20 @@ class MainWindow(QMainWindow):
prog_sweep.setMaximum(100) prog_sweep.setMaximum(100)
prog_sweep.setFormat("%v / %m") prog_sweep.setFormat("%v / %m")
# prog_sweep.setTextVisible(False) # prog_sweep.setTextVisible(False)
prog_sweep.setValue(50) prog_sweep.setValue(0)
window_layout.addWidget(prog_sweep) window_layout.addWidget(prog_sweep)
self.prog_sweep = prog_sweep self.prog_sweep = prog_sweep
# window_widget.se plot_widget = QTabWidget()
plot_layout = QVBoxLayout()
# TODO: handle plots properly
self.plots = [] self.plots = []
for type_ in ["logmag", "phase", "vswr", "smith"]: for type_ in [
"logmag",
"phase",
"vswr",
"smith",
]:
self.plots.append(PlotWidget(type_=type_)) self.plots.append(PlotWidget(type_=type_))
plot_layout.addWidget(self.plots[-1]) plot_widget.addTab(self.plots[-1], type_)
plot_widget = QWidget()
plot_widget.setLayout(plot_layout)
window_layout.addWidget(plot_widget) window_layout.addWidget(plot_widget)
# Set the central widget of the Window. # Set the central widget of the Window.
@ -236,18 +145,25 @@ class MainWindow(QMainWindow):
widget.setLayout(window_layout) widget.setLayout(window_layout)
self.setCentralWidget(widget) self.setCentralWidget(widget)
def toggle_port(self):
self.active_port = int(not self.active_port)
print(f"Activating port {self.active_port}")
self.vna.set_switches(a=self.active_port, b=self.active_port)
def saveas_config(self) -> None: def saveas_config(self) -> None:
print("Prompting for save path...") print("Prompting for save path...")
dialog = QFileDialog(self) dialog = QFileDialog(self)
dialog.setNameFilter(f"*{CONFIG_SUFFIX}")
dialog.setDefaultSuffix(CONFIG_SUFFIX) dialog.setDefaultSuffix(CONFIG_SUFFIX)
dialog.setAcceptMode(QFileDialog.AcceptMode.AcceptSave) dialog.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
if dialog.exec(): if dialog.exec():
config_path = Path(dialog.selectedFiles()[0]) config_path = Path(dialog.selectedFiles()[0])
print(config_path)
if config_path.suffix != CONFIG_SUFFIX: if config_path.suffix != CONFIG_SUFFIX:
raise ValueError( raise ValueError(
f"{config_path.name} is not a valid configuration file. Must have extension {CONFIG_SUFFIX}" f"{config_path.name} is not a valid configuration file. Must have extension {CONFIG_SUFFIX}"
) )
if config_path == PATH_CONFIG_DEFAULT:
raise ValueError(f"Cannot overwrite default configuration file at {PATH_CONFIG_DEFAULT}")
self.config_path = config_path self.config_path = config_path
print(f"Config path is now {self.config_path.resolve()}") print(f"Config path is now {self.config_path.resolve()}")
@ -271,7 +187,7 @@ class MainWindow(QMainWindow):
self.load_config(self.config_path) self.load_config(self.config_path)
def save_config(self) -> None: def save_config(self) -> None:
if self.config_path is None: if self.config_path == PATH_CONFIG_DEFAULT:
self.saveas_config() self.saveas_config()
else: else:
print(f"Saving config to {self.config_path.resolve()}") print(f"Saving config to {self.config_path.resolve()}")
@ -281,34 +197,26 @@ class MainWindow(QMainWindow):
print(f"Loading config from {path}...") print(f"Loading config from {path}...")
# TODO: load config # TODO: load config
def progress_callback(self, done: int, total: int):
self.prog_sweep.setMaximum(total)
self.prog_sweep.setValue(done)
def capture(self) -> None: def capture(self) -> None:
def callback(done: int, total: int): s = self.vna.vna_capture(self._frequency, self.progress_callback)
self.prog_sweep.setMaximum(total)
self.prog_sweep.setValue(done)
s = self.vna.vna_capture(self._frequency, callback) if self.vna.calibration is not None:
s_calibrated = self.vna.calibration.apply_cal(s2net(s))
data = xr.DataArray( data = net2s(s_calibrated)
[[s]], else:
dims=["m", "n", "frequency"], data = xr.DataArray(
coords=dict( [[s]],
frequency=s.coords["frequency"], dims=["m", "n", "frequency"],
m=[1], coords=dict(
n=[1], frequency=s.coords["frequency"],
), m=[1],
) n=[1],
),
for plot in self.plots: )
plot.update_plot(data)
def generate_sim_data(self) -> None:
coords = {"frequency": self._frequency, "m": [1], "n": [1]}
shape = tuple(len(v) for v in coords.values())
data = xr.DataArray(
((-1 + 2 * np.random.rand(*shape)) + 1j * (-1 + 2 * np.random.rand(*shape))) / np.sqrt(2),
dims=list(coords.keys()),
coords=coords,
)
for plot in self.plots: for plot in self.plots:
plot.update_plot(data) plot.update_plot(data)
@ -327,11 +235,54 @@ class MainWindow(QMainWindow):
# Currently does not support zero span # Currently does not support zero span
self._frequency = frequency self._frequency = frequency
def calibrate_solt(self):
if len(self.vna.ports) > 1:
raise NotImplementedError
calfile = Path(__file__).parent / "cal.pkl"
if calfile.exists():
# don't re-cal while debugging because that's slooooooow
with open(calfile, "rb") as f:
calibration = pickle.load(f)
else:
s = dict()
for net in ["short", "open", "load"]:
input(f"Connect {net} standard and press ENTER...")
s[net] = self.vna.vna_capture(self._frequency, self.progress_callback)
ideal = rf.media.DefinedGammaZ0(frequency=rf.media.Frequency.from_f(self._frequency, unit="Hz"))
calibration = rf.calibration.OnePort(
[s2net(s["short"]), s2net(s["open"]), s2net(s["load"])],
[ideal.short(), ideal.open(), ideal.load(0)],
)
# TODO: don't use pickles for calibration. They're fragile
with open(calfile, "wb") as f:
pickle.dump(calibration, f)
self.vna.calibration = calibration
def main() -> None: def main() -> None:
app = QApplication(sys.argv) app = QApplication(sys.argv)
window = MainWindow() try:
window = MainWindow()
except Exception as e:
if e.args[0] == "No device found":
dialog = QInputDialog()
text, ok = dialog.getText(
None,
"Pluto IP Address",
"Enter Pluto IP Address",
QLineEdit.Normal,
Charon.DEFAULT_IP,
)
match = re.match(r"(\d{1,3}\.){3}\d{1,3}", text)
if not match:
raise ValueError(f"Invalid IP address: {text}")
window = MainWindow(ip=text)
else:
raise e
window.show() window.show()
app.exec() app.exec()

View File

@ -1,11 +1,94 @@
import json
import shutil
import zipfile
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List
import skrf as rf import skrf as rf
from util import net2s
# scikit-rf has no way to save files aside from touchstone and pickle # scikit-rf has no way to save Calibration objects aside from pickle
def cal2zarr(cal: rf.calibration.Calibration, outpath: Path): def cal2zip(cal: rf.calibration.Calibration, path: Path | str) -> None:
ideals = [net2s(net) for net in cal.ideals] path = Path(path)
measured = [net2s(net) for net in cal.measured] cal_type = cal.__class__
# s.to_zarr(outpath) measured: List[rf.network.Network] = cal.measured
ideals: List[rf.network.Network] = cal.ideals
if cal_type not in [rf.calibration.OnePort]:
raise NotImplementedError(f"Calibration {cal_type.__name__} serialization not implemented")
assert len(ideals) == len(measured) # this should have already been asserted when cal was instantiated
with TemporaryDirectory() as temp:
dir_temp = Path(temp)
with zipfile.ZipFile(dir_temp / "archive.zip", "w") as archive:
# create a configuration file
filename_config = dir_temp / "config.json"
with open(filename_config, "w") as f:
json.dump(
dict(
cal_type=cal_type.__name__,
num_standards=len(measured),
),
f,
)
archive.write(filename_config, str(filename_config.relative_to(dir_temp)))
# add standard data
dir_ideals = dir_temp / "ideals"
dir_ideals.mkdir()
for ii, ideal in enumerate(ideals):
filename = dir_ideals / f"{ii}.s2p"
ideal.write_touchstone(filename)
archive.write(filename, str(filename.relative_to(dir_temp)))
# add test data
dir_measured = dir_temp / "measured"
dir_measured.mkdir()
for ii, meas in enumerate(measured):
filename = dir_measured / f"{ii}.s2p"
meas.write_touchstone(filename)
archive.write(filename, str(filename.relative_to(dir_temp)))
print("Wrote calibration to file")
archive.printdir()
shutil.move(dir_temp / "archive.zip", path)
def zip2cal(path: Path | str):
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"Calibration file {path} does not exist")
with zipfile.ZipFile(path) as archive:
archive.printdir()
config = json.loads(archive.read("config.json"))
print(config)
ideals = list()
measured = list()
with TemporaryDirectory() as temp:
dir_temp = Path(temp)
for ii in range(config["num_standards"]):
with open(dir_temp / f"{ii}.s2p", "wb") as f:
f.write(archive.read(f"ideals/{ii}.s2p"))
ideals.append(rf.network.Network(dir_temp / f"{ii}.s2p"))
with open(dir_temp / f"{ii}.s2p", "wb") as f:
f.write(archive.read(f"measured/{ii}.s2p"))
measured.append(rf.network.Network(dir_temp / f"{ii}.s2p"))
cal_type = config["cal_type"]
CalClass = getattr(rf.calibration, cal_type)
if not issubclass(CalClass, rf.calibration.Calibration):
raise ValueError()
calibration = CalClass(measured=measured, ideals=ideals)
return calibration

129
charon_vna/plots.py Normal file
View File

@ -0,0 +1,129 @@
# %% imports
from typing import Callable, List, Literal, Tuple
import numpy as np
import xarray as xr
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
from matplotlib.lines import Line2D
from matplotlib.ticker import EngFormatter
from numpy import typing as npt
from PySide6.QtWidgets import QVBoxLayout, QWidget
from skrf import plotting as rf_plt
from charon_vna.util import db20, s2vswr
__all__ = ("PlotWidget",)
# %%
class PlotWidget(QWidget):
traces: List[Tuple[int | str]]
lines: List[Line2D]
def __init__(self, type_: str = "logmag"):
super().__init__()
self.traces = [(1, 1)]
layout = QVBoxLayout()
self.setLayout(layout)
self.fig = plt.Figure(figsize=(5, 4), dpi=100, tight_layout=True)
self.ax = self.fig.add_subplot(111)
self.set_plot_type(type_)
self.lines = [
self.ax.plot([np.nan], [np.nan], label="$S_{" + str(m) + str(n) + "}$")[0] for m, n in self.traces
]
self.ax.legend(loc="upper right")
canvas = FigureCanvasQTAgg(self.fig)
layout.addWidget(canvas)
# toolbar = QToolBar("Toolbar")
# toolbar.addAction("blah")
# self.addToolBar(toolbar)
def set_plot_type(
self,
type_: Literal["logmag", "phase", "vswr", "smith"],
sweep_type: Literal["frequency", "time"] = "frequency",
) -> None:
if sweep_type != "frequency":
raise NotImplementedError("Only frequency sweeps are currently supported")
if type_ == "logmag":
self.setup_logmag()
elif type_ == "phase":
self.setup_phase()
elif type_ == "vswr":
self.setup_vswr()
elif type_ == "smith":
self.setup_smith()
else:
raise ValueError(f"Unknown plot type: {type_}")
self._plot_type = type_
def update_plot(self, data: xr.DataArray):
if self._plot_type == "logmag":
self.update_logmag(data)
elif self._plot_type == "phase":
self.update_phase(data)
elif self._plot_type == "vswr":
self.update_vswr(data)
elif self._plot_type == "smith":
self.update_smith(data)
def setup_rect(self) -> None:
self.ax.grid(True)
self.ax.xaxis.set_major_formatter(EngFormatter())
self.ax.set_xlabel("Frequency [Hz]")
def update_rect(self, data: xr.DataArray, func: Callable[[npt.ArrayLike], npt.ArrayLike]) -> None:
self.ax.set_xlim(data["frequency"].min().data, data["frequency"].max().data)
for ii, (m, n) in enumerate(self.traces):
self.lines[ii].set_xdata(data["frequency"])
self.lines[ii].set_ydata(func(data.sel(m=m, n=n)))
self.fig.canvas.draw()
def setup_logmag(self, ylim: List[float] = [-30, 30]) -> None:
self.setup_rect()
self.ax.set_ylim(ylim)
self.ax.set_ylabel("Amplitude [dB]")
def update_logmag(self, data: xr.DataArray) -> None:
self.update_rect(data, db20)
def setup_phase(self) -> None:
self.setup_rect()
self.ax.set_ylim(-200, 200)
self.ax.set_ylabel("Phase [deg]")
def update_phase(self, data: xr.DataArray):
self.update_rect(data, lambda s: np.angle(s, deg=True))
def setup_vswr(self) -> None:
self.setup_rect()
self.ax.set_yticks(np.arange(1, 11))
self.ax.set_ylim(1, 10)
self.ax.set_ylabel("VSWR")
def update_vswr(self, data: xr.DataArray) -> None:
self.update_rect(data, s2vswr)
def setup_smith(self) -> None:
self.ax.grid(False)
self.ax.set_xlim(-1, 1)
self.ax.set_ylim(-1, 1)
self.ax.set_aspect("equal")
rf_plt.smith(ax=self.ax, smithR=1, chart_type="z", draw_vswr=None)
def update_smith(self, data: xr.DataArray) -> None:
for ii, (m, n) in enumerate(self.traces):
sel = data.sel(m=m, n=n)
self.lines[ii].set_xdata(sel.real)
self.lines[ii].set_ydata(sel.imag)
self.fig.canvas.draw()

View File

@ -47,7 +47,7 @@ def db20(v: npt.ArrayLike) -> npt.ArrayLike:
def s2vswr(s: npt.ArrayLike) -> npt.ArrayLike: def s2vswr(s: npt.ArrayLike) -> npt.ArrayLike:
return (1 + np.abs(s)) / (1 - np.abs(s)) return np.abs((1 + np.abs(s)) / (1 - np.abs(s)))
def minmax(x): def minmax(x):

View File

@ -1,11 +1,12 @@
# %% imports # %% imports
import copy import copy
import pickle
from enum import IntEnum, unique
from pathlib import Path from pathlib import Path
from typing import Any, Callable, Dict, Tuple from typing import Any, Callable, Dict, List, Literal, Tuple
import adi import adi
import iio
# import iio
import numpy as np import numpy as np
import skrf as rf import skrf as rf
import xarray as xr import xarray as xr
@ -13,7 +14,8 @@ from matplotlib import pyplot as plt
from matplotlib.ticker import EngFormatter from matplotlib.ticker import EngFormatter
from numpy import typing as npt from numpy import typing as npt
from scipy import signal from scipy import signal
from util import HAM_BANDS, db20, net2s, s2net
from charon_vna.util import HAM_BANDS, db20, net2s, s2net
dir_ = Path(__file__).parent dir_ = Path(__file__).parent
@ -33,19 +35,72 @@ def generate_tone(f: float, fs: float, N: int = 1024, scale: int = 2**14):
return iq return iq
@unique
class AD9361Register(IntEnum):
AUXDAC1_WORD = 0x018
AUXDAC2_WORD = 0x019
AUXDAC1_CONFIG = 0x01A
AUXDAC2_CONFIG = 0x01B
AUXADC_CLOCK_DIVIDER = 0x01C
AUXADC_CONFIG = 0x01D
AUXADC_WORD_MSB = 0x01E
AUXADC_WORD_LSB = 0x01F
AUTO_GPIO = 0x020
AGC_GAIN_LOCK_DELAY = 0x021
AGC_ATTACK_DELAY = 0x022
AUXDAC_ENABLE_CONTROL = 0x023
RX_LOAD_SYNTH_DELAY = 0x024
TX_LOAD_SYNTH_DELAY = 0x025
EXTERNAL_LNA_CONTROL = 0x026
GPO_FORCE_AND_INIT = 0x027
GPO0_RX_DELAY = 0x028
GPO1_RX_DELAY = 0x029
GPO2_RX_DELAY = 0x02A
GPO3_RX_DELAY = 0x02B
GPO0_TX_DELAY = 0x02C
GPO1_TX_DELAY = 0x02D
GPO2_TX_DELAY = 0x02E
GPO3_TX_DELAY = 0x02F
AUXDAC1_RX_DELAY = 0x030
AUXDAC1_TX_DELAY = 0x031
AUXDAC2_RX_DELAY = 0x032
AUXDAC2_TX_DELAY = 0x033
@unique
class AD9361DacVref(IntEnum):
VREF_1V0 = 0b00
VREF_1V5 = 0b01
VREF_2V0 = 0b10
VREF_2V5 = 0b11
@unique
class AD9361DacStepFactor(IntEnum):
FACTOR_2 = 0b0
FACTOR_1 = 0b1
class Charon: class Charon:
FREQUENCY_OFFSET = 1e6 FREQUENCY_OFFSET = 1e6
DEFAULT_IP = "192.168.3.1"
calibration: rf.calibration.Calibration | None = None
def __init__( def __init__(
self, self,
uri: str = "192.168.2.1", ip: str = DEFAULT_IP,
frequency: npt.ArrayLike = np.linspace(1e9, 2e9, 3), frequency: npt.ArrayLike = np.linspace(1e9, 2e9, 3),
ports: Tuple[int] = (1,), ports: Tuple[int] | int = 1,
): ):
if isinstance(ports, int):
ports = (np.arange(ports) + 1).tolist()
ports = tuple(ports)
self.ports = ports self.ports = ports
self.frequency = frequency self.frequency = frequency
# everything RF # everything RF
uri = f"ip:{ip}"
self.sdr = adi.ad9361(uri=uri) self.sdr = adi.ad9361(uri=uri)
for attr, expected in [ for attr, expected in [
("adi,2rx-2tx-mode-enable", True), ("adi,2rx-2tx-mode-enable", True),
@ -77,15 +132,22 @@ class Charon:
self.sdr.rx_hardwaregain_chan1 = 10 self.sdr.rx_hardwaregain_chan1 = 10
self.sdr.tx_hardwaregain_chan0 = -10 self.sdr.tx_hardwaregain_chan0 = -10
# # switch control # switch control
# ctx = iio.Context(uri) ctx = iio.Context(uri)
# self.ctrl = ctx.find_device("ad9361-phy") self.ctrl = ctx.find_device("ad9361-phy")
# # raw ad9361 register accesss: # raw ad9361 register accesss:
# # https://ez.analog.com/linux-software-drivers/f/q-a/120853/control-fmcomms3-s-gpo-with-python # https://ez.analog.com/linux-software-drivers/f/q-a/120853/control-fmcomms3-s-gpo-with-python
# # https://www.analog.com/media/cn/technical-documentation/user-guides/ad9364_register_map_reference_manual_ug-672.pdf # noqa: E501 # https://www.analog.com/media/cn/technical-documentation/user-guides/ad9364_register_map_reference_manual_ug-672.pdf # noqa: E501
# self.ctrl.reg_write(0x26, 0x90) # bit 7: AuxDAC Manual, bit 4: GPO Manual self.ctrl.reg_write(AD9361Register.EXTERNAL_LNA_CONTROL, 0x90) # bit 7: AuxDAC Manual, bit 4: GPO Manual
# self._set_gpo(self.ports[0] - 1) self.ctrl.reg_write(AD9361Register.AUXDAC_ENABLE_CONTROL, 0x3F)
# # TODO: init AuxDAC
# initialize switch control outputs
self._set_gpo(0b0000)
self._set_dac_code(value=0, channel=1)
self._set_dac_code(value=0, channel=2)
# set default switch state
self.set_switches(a=self.ports[0] - 1, b=self.ports[0] - 1)
def get_config(self) -> Dict[str, Any]: def get_config(self) -> Dict[str, Any]:
config = dict() config = dict()
@ -110,28 +172,80 @@ class Charon:
return config return config
def _get_gpo(self) -> int: def _get_gpo(self) -> int:
return (self.ctrl.reg_read(0x27) >> 4) & 0x0F return (self.ctrl.reg_read(AD9361Register.GPO_FORCE_AND_INIT) >> 4) & 0x0F
def _set_gpo(self, value: int) -> None: def _set_gpo(self, value: int) -> None:
self.ctrl.reg_write(0x27, (value & 0x0F) << 4) # bits 7-4: GPO3-0 self.ctrl.reg_write(AD9361Register.GPO_FORCE_AND_INIT, (value & 0x0F) << 4) # bits 7-4: GPO3-0
def _get_dac_code(self, channel: Literal[1, 2]) -> Tuple[float, AD9361DacVref, AD9361DacStepFactor]:
word = self.ctrl.reg_read(AD9361Register.__getitem__(f"AUXDAC{channel}_WORD"))
config = self.ctrl.reg_read(AD9361Register.__getitem__(f"AUXDAC{channel}_CONFIG"))
value = (word << 2) + (config & 0x3)
vref = AD9361DacVref((config >> 2) & 0x3)
step_factor = AD9361DacStepFactor((config >> 4) & 0x1)
return (value, vref, step_factor)
def _set_dac_code(
self,
value: int,
channel: Literal[1, 2],
vref: AD9361DacVref = AD9361DacVref.VREF_1V0,
step_factor: AD9361DacStepFactor = AD9361DacStepFactor.FACTOR_2,
) -> None:
if channel not in [1, 2]:
raise ValueError(f"Invalid channel {channel}. Must be 1 or 2")
if value > 0x3FF or value < 0:
raise ValueError("Invalid value for 10 bit DAC. Must be between 0 and 0x3FF (inclusive)")
vref = AD9361DacVref(vref)
step_factor = AD9361DacStepFactor(step_factor)
# https://www.analog.com/media/cn/technical-documentation/user-guides/ad9364_register_map_reference_manual_ug-672.pdf
# page 13
# vout = 0.97 * vref + (0.000738 + 9e-6 * (vref * 1.6 - 2)) * auxdac_word[9:0] * step_factor - 0.3572 * step_factor + 0.05
# vout ~= (vref - 0.3572 * step_factor) + 0.000738 * auxdac_word[9:0] * step_factor
# which gives a 1.5V swing with step_factor == 2 and 0.75V swing with step_factor == 1
# vref basically just changes the minimum voltage with negligible impact on output scaling
self.ctrl.reg_write(
AD9361Register.__getitem__(f"AUXDAC{channel}_WORD"),
(value >> 2) & 0xFF,
)
self.ctrl.reg_write(
AD9361Register.__getitem__(f"AUXDAC{channel}_CONFIG"),
(value & 0x3) | (vref.value << 2) | (step_factor << 4),
)
def set_switches(self, b: int, a: int, excitation: int | None = None):
if excitation is None:
excitation = a
val = 0
val |= int(bool(excitation)) << 0 # exc = GPO0
val |= int(bool(a)) << 2 # a = GPO2
val |= int(bool(b)) << 1 # b = GPO1
self._set_gpo(val)
def set_output_power(self, power: float): def set_output_power(self, power: float):
# FIXME: this is a hack because I don't want to go through re-calibration pout = xr.DataArray(
if power == 5: [-15, -10, -5, 0, 5],
tx_gain = -1 dims=["tx_gain"],
elif power == 0: coords=dict(
tx_gain = -7 # TODO: correct over frequency
elif power == -5: frequency=1e9, # FIXME: I'm not sure at what frequency I generated this table
tx_gain = -12 tx_channel=0,
elif power == -10: tx_gain=[-22, -17, -12, -7, -1],
tx_gain = -17 ),
elif power == -15: )
tx_gain = -22
else: tx_gain_idx = np.abs(pout - power).argmin(dim="tx_gain")
raise NotImplementedError() tx_gain = pout.coords["tx_gain"][tx_gain_idx]
# # TODO: correct over frequency
# tx_gain_idx = np.abs(pout.sel(tx_channel=0) - power).argmin(dim="tx_gain")
# tx_gain = pout.coords["tx_gain"][tx_gain_idx]
self.sdr.tx_hardwaregain_chan0 = float(tx_gain) self.sdr.tx_hardwaregain_chan0 = float(tx_gain)
def set_output(self, frequency: float, power: float): def set_output(self, frequency: float, power: float):
@ -192,47 +306,147 @@ class Charon:
return np.mean(data[1] / data[0]) return np.mean(data[1] / data[0])
def sweep_b_over_a(self): def capture(
self,
callback: Callable[int, int] | None = None,
*,
measurements: List[Tuple[int, int]] = None,
):
if measurements is None:
measurements = [(m, n) for n in self.ports for m in self.ports]
measurements = list(measurements)
s = xr.DataArray( s = xr.DataArray(
np.zeros( np.zeros(
len(self.frequency), [len(self.frequency), len(self.ports), len(self.ports)],
dtype=np.complex128, dtype=np.complex128,
), ),
dims=["frequency"], dims=["frequency", "m", "n"],
coords=dict( coords=dict(
frequency=self.frequency, frequency=self.frequency,
m=list(self.ports),
n=list(self.ports),
), ),
) )
for frequency in self.frequency:
s.loc[dict(frequency=frequency)] = self.get_b_over_a(frequency=frequency)
return s
def vna_capture(self, frequency: npt.ArrayLike, callback: Callable[int, int] | None): total_count = len(measurements) * len(s.frequency)
s = xr.DataArray( count = 0
np.empty(len(frequency), dtype=np.complex128),
dims=["frequency"], for m in s.m.data:
coords=dict( for n in s.n.data:
frequency=frequency, if (m, n) in measurements:
), self.set_switches(b=m - 1, a=n - 1)
)
for ff, freq in enumerate(s.frequency.data): for ff, freq in enumerate(s.frequency.data):
if callback is not None: if callback is not None:
callback(ff, len(s.frequency)) # report progress during sweep
self.set_output(frequency=freq, power=-5) callback(count, total_count)
self.sdr.rx_destroy_buffer()
self.sdr.rx_lo = int(freq) self.set_output(frequency=freq, power=-5)
self.sdr.rx_enabled_channels = [0, 1] self.sdr.rx_destroy_buffer()
self.sdr.gain_control_mode_chan0 = "manual" self.sdr.rx_lo = int(freq)
self.sdr.gain_control_mode_chan1 = "manual" self.sdr.rx_enabled_channels = [0, 1]
self.sdr.rx_hardwaregain_chan0 = 40 self.sdr.gain_control_mode_chan0 = "manual"
self.sdr.rx_hardwaregain_chan1 = 40 self.sdr.gain_control_mode_chan1 = "manual"
rx = self.sdr.rx() self.sdr.rx_hardwaregain_chan0 = 40
s.loc[dict(frequency=freq)] = np.mean(rx[1] / rx[0]) self.sdr.rx_hardwaregain_chan1 = 40
rx = self.sdr.rx()
s.loc[dict(frequency=freq, m=m, n=n)] = np.mean(rx[1] / rx[0])
count += 1
if callback is not None: if callback is not None:
callback(len(s.frequency), len(s.frequency)) # mark capture as complete
callback(total_count, total_count)
return s return s
def calibrate_sol(self, prompt: Callable[[str], None] | None = None, **kwargs) -> None:
if len(self.ports) != 1:
raise ValueError(
f"SOL calibration needs only one port but {len(self.ports)} ports are enabled. "
"Did you mean to use SOLT?"
)
if prompt is None:
prompt = lambda s: input(f"{s}\nENTER to continue...")
ideal = rf.media.DefinedGammaZ0(frequency=rf.media.Frequency.from_f(self.frequency, unit="Hz"))
ideals = [ideal.short(), ideal.open(), ideal.load(0)]
names = ["short", "open", "load"]
measured = list()
for name in names:
prompt(f"Connect standard {name} to port {self.ports[0]}")
measured.append(self.capture(**kwargs))
cal = rf.OnePort(measured=[s2net(m) for m in measured], ideals=ideals)
self.calibration = cal
def calibrate_solt(self, prompt: Callable[[str], None] | None = None, **kwargs) -> None:
if len(self.ports) < 2:
raise ValueError(
f"SOLT calibration needs at least two ports but {len(self.ports)} ports are enabled. "
"Did you mean to use SOL?"
)
if len(self.ports) > 2:
raise NotImplementedError("SOLT calibration with more than two ports not yet supported")
if prompt is None:
prompt = lambda s: input(f"{s}\nENTER to continue...")
ideal = rf.media.DefinedGammaZ0(frequency=rf.media.Frequency.from_f(self.frequency, unit="Hz"))
ideals = [ideal.short(), ideal.open(), ideal.load(0)]
ideals = [rf.two_port_reflect(id, id) for id in ideals]
thru = np.zeros((len(self.frequency), 2, 2), dtype=np.complex128)
thru[:, 0, 1] = 1
thru[:, 1, 0] = 1
thru = rf.Network(frequency=self.frequency, f_unit="Hz", s=thru)
ideals.append(thru)
names_1p = ["short", "open", "load"]
names_2p = ["thru"]
measured = list()
for name in names_1p:
measured_param = list()
for port in self.ports:
prompt(f"Connect standard {name} to port {port}")
measured_param.append(self.capture(measurements=[(port, port)], **kwargs).sel(m=port, n=port))
measured.append(rf.two_port_reflect(*[s2net(m) for m in measured_param]))
for name in names_2p:
prompt(f"Connect standard {name} between ports {self.ports[0]} and {self.ports[1]}")
measured.append(s2net(self.capture(**kwargs)))
cal = rf.SOLT(measured=measured, ideals=ideals)
self.calibration = cal
def save_calibration(self, path: Path | str):
path = Path(path)
if path.suffix.lower() == ".pkl":
with open(str(path), "wb") as f:
pickle.dump(self.calibration, f)
else:
raise NotImplementedError(f"Unknown calibration file extension: {path.suffix}")
def load_calibration(self, path: Path | str):
path = Path(path)
if path.suffix.lower() == ".pkl":
with open(str(path), "rb") as f:
cal = pickle.load(f)
if not isinstance(cal, rf.calibration.Calibration):
raise ValueError(f"Expected {rf.calibration.Calibration}, got {type(cal)}")
self.calibration = cal
else:
raise NotImplementedError(f"Unknown calibration file extension: {path.suffix}")
# %% # %%
if __name__ == "__main__": if __name__ == "__main__":

71
charon_vna/vna_dev.py Normal file
View File

@ -0,0 +1,71 @@
# %% imports
import numpy as np
from matplotlib import pyplot as plt
from charon_vna.util import db20, net2s, s2net
from charon_vna.vna import Charon
# %%
frequency = np.linspace(80e6, 280e6, 301)
# %%
vna = Charon(frequency=frequency, ports=2)
# %%
s = vna.capture()
# %%
for m in s.m.data:
for n in s.n.data:
plt.plot(s.frequency, db20(s.sel(m=m, n=n)), label="$S_{" + str(m) + str(n) + "}$")
plt.grid(True)
plt.legend()
plt.show()
# %%
vna.calibrate_sol()
# %%
vna.calibrate_solt()
# %%
vna.save_calibration("./calibration.pkl")
# %%
vna.load_calibration("./calibration.pkl")
# %%
s2 = net2s(vna.calibration.apply_cal(s2net(s)))
# s2.coords["m"] = s.m
# s2.coords["n"] = s.n
for m in s.m.data:
for n in s.n.data:
plt.plot(s.frequency, db20(s.sel(m=m, n=n)), label="$S_{" + str(m) + str(n) + "}$ (uncalibrated)")
plt.plot(s2.frequency, db20(s2.sel(m=m, n=n)), label="$S_{" + str(m) + str(n) + "}$ (calibrated)")
plt.grid(True)
plt.legend()
plt.ylabel("Magnitude [dB]")
# plt.ylim(-30, 5)
plt.show()
for m in s.m.data:
for n in s.n.data:
if m != n:
plt.plot(
s.frequency,
np.angle(s.sel(m=m, n=n), deg=True),
label="$S_{" + str(m) + str(n) + "}$ (uncalibrated)",
)
plt.plot(
s2.frequency,
np.angle(s2.sel(m=m, n=n), deg=True),
label="$S_{" + str(m) + str(n) + "}$ (calibrated)",
)
plt.grid(True)
plt.legend()
plt.ylabel("Phase [deg]")
plt.show()
# %%

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 KiB