| 1 |
""" |
| 2 |
.. module:: skrf.io.csv |
| 3 |
|
| 4 |
======================================== |
| 5 |
csv (:mod:`skrf.io.csv`) |
| 6 |
======================================== |
| 7 |
|
| 8 |
Functions for reading and writing standard csv files |
| 9 |
---------------------------------------------------- |
| 10 |
|
| 11 |
.. autosummary:: |
| 12 |
:toctree: generated/ |
| 13 |
|
| 14 |
read_all_csv |
| 15 |
AgilentCSV |
| 16 |
|
| 17 |
|
| 18 |
Reading/Writing Agilent |
| 19 |
------------------------ |
| 20 |
|
| 21 |
.. autosummary:: |
| 22 |
:toctree: generated/ |
| 23 |
|
| 24 |
read_pna_csv |
| 25 |
pna_csv_2_ntwks |
| 26 |
pna_csv_2_ntwks3 |
| 27 |
pna_csv_2_df |
| 28 |
|
| 29 |
Reading/Writing R&S |
| 30 |
-------------------- |
| 31 |
|
| 32 |
.. autosummary:: |
| 33 |
:toctree: generated/ |
| 34 |
|
| 35 |
read_zva_dat |
| 36 |
read_all_zva_dat |
| 37 |
zva_dat_2_ntwks |
| 38 |
|
| 39 |
Reading/Writing Anritsu VectorStar |
| 40 |
----------------------------------- |
| 41 |
|
| 42 |
.. autosummary:: |
| 43 |
:toctree: generated/ |
| 44 |
|
| 45 |
vectorstar_csv_2_ntwks |
| 46 |
read_vectorstar_csv |
| 47 |
|
| 48 |
|
| 49 |
""" |
| 50 |
from __future__ import annotations |
| 51 |
|
| 52 |
import os |
| 53 |
from warnings import warn |
| 54 |
|
| 55 |
import numpy as np |
| 56 |
|
| 57 |
from .. import mathFunctions as mf |
| 58 |
from .. import util |
| 59 |
from ..constants import FREQ_UNITS, FrequencyUnitT |
| 60 |
from ..frequency import Frequency |
| 61 |
from ..network import Network |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
def read_pna_csv(filename, *args, **kwargs) -> tuple[str, str, np.ndarray]: |
| 67 |
r""" |
| 68 |
Reads data from a csv file written by an Agilient PNA. |
| 69 |
|
| 70 |
This function returns a triplet containing the header, comments, |
| 71 |
and data. |
| 72 |
|
| 73 |
|
| 74 |
Parameters |
| 75 |
---------- |
| 76 |
filename : str |
| 77 |
the file |
| 78 |
\*args, \*\*kwargs : |
| 79 |
|
| 80 |
Returns |
| 81 |
------- |
| 82 |
header : str |
| 83 |
The header string, which is the line following the 'BEGIN' |
| 84 |
comments : str |
| 85 |
All lines that begin with a '!' |
| 86 |
data : :class:`numpy.ndarray` |
| 87 |
An array containing the data. The meaning of which depends on |
| 88 |
the header. |
| 89 |
|
| 90 |
See Also |
| 91 |
-------- |
| 92 |
pna_csv_2_ntwks : Reads a csv file which contains s-parameter data |
| 93 |
|
| 94 |
Examples |
| 95 |
-------- |
| 96 |
>>> header, comments, data = rf.read_pna_csv('myfile.csv') |
| 97 |
""" |
| 98 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 99 |
with open(filename) as fid: |
| 100 |
begin_line = -2 |
| 101 |
end_line = -1 |
| 102 |
n_END = 0 |
| 103 |
comments = '' |
| 104 |
for k,line in enumerate(fid.readlines()): |
| 105 |
if line.startswith('!'): |
| 106 |
comments += line[1:] |
| 107 |
elif line.startswith('BEGIN') and n_END == 0: |
| 108 |
begin_line = k |
| 109 |
elif line.startswith('END'): |
| 110 |
if n_END == 0: |
| 111 |
|
| 112 |
end_line = k |
| 113 |
|
| 114 |
n_END += 1 |
| 115 |
if k == begin_line+1: |
| 116 |
header = line |
| 117 |
footer = k - end_line |
| 118 |
|
| 119 |
try: |
| 120 |
data = np.genfromtxt( |
| 121 |
filename, |
| 122 |
delimiter = ',', |
| 123 |
skip_header = begin_line + 2, |
| 124 |
skip_footer = footer - (n_END-1)*2, |
| 125 |
**kwargs |
| 126 |
) |
| 127 |
except(ValueError): |
| 128 |
|
| 129 |
data = np.genfromtxt( |
| 130 |
filename, |
| 131 |
delimiter = ',', |
| 132 |
skip_header = (begin_line + 2)*2, |
| 133 |
skip_footer = footer, |
| 134 |
**kwargs |
| 135 |
) |
| 136 |
|
| 137 |
|
| 138 |
header = header.replace('\xb0','deg').rstrip('\n').rstrip('\r') |
| 139 |
|
| 140 |
units_dict: dict[str, FrequencyUnitT] = {k.lower(): k for k in FREQ_UNITS.keys()} |
| 141 |
|
| 142 |
|
| 143 |
unit_raw = header.split(',')[0].strip('Freq')[1:-1] |
| 144 |
try: |
| 145 |
unit_tmp = unit_raw.lower() |
| 146 |
if unit_tmp in units_dict: |
| 147 |
data[:, 0] *= FREQ_UNITS[units_dict[unit_tmp]] |
| 148 |
except Exception as exc: |
| 149 |
raise ValueError(f"Could not parse frequency unit '{unit_raw}'") from exc |
| 150 |
|
| 151 |
return header, comments, data |
| 152 |
|
| 153 |
def pna_csv_2_df(filename): |
| 154 |
""" |
| 155 |
Reads data from a csv file written by an Agilient PNA as a pandas DataFrame. |
| 156 |
|
| 157 |
Parameters |
| 158 |
---------- |
| 159 |
filename : string |
| 160 |
filename |
| 161 |
|
| 162 |
Returns |
| 163 |
------- |
| 164 |
df : `pandas.DataFrame` |
| 165 |
|
| 166 |
""" |
| 167 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 168 |
from pandas import DataFrame, Index |
| 169 |
header, comments, d = read_pna_csv(filename) |
| 170 |
|
| 171 |
names = header.split(',') |
| 172 |
|
| 173 |
index = Index(d[:,0], name = names[0]) |
| 174 |
df=DataFrame({names[k]: d[:,k] for k in range(1,len(names))}, index=index) |
| 175 |
return df |
| 176 |
|
| 177 |
def pna_csv_2_ntwks2(filename, *args, **kwargs): |
| 178 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 179 |
df = pna_csv_2_df(filename, *args, **kwargs) |
| 180 |
header, comments, d = read_pna_csv(filename) |
| 181 |
ntwk_dict = {} |
| 182 |
param_set=set([k[:3] for k in df.columns]) |
| 183 |
f = df.index.values |
| 184 |
for param in param_set: |
| 185 |
try: |
| 186 |
s = mf.dbdeg_2_reim( |
| 187 |
df[f'{param} Log Mag(dB)'].values, |
| 188 |
df[f'{param} Phase(deg)'].values, |
| 189 |
) |
| 190 |
except(KeyError): |
| 191 |
s = mf.dbdeg_2_reim( |
| 192 |
df[f'{param} (REAL)'].values, |
| 193 |
df[f'{param} (IMAG)'].values, |
| 194 |
) |
| 195 |
|
| 196 |
ntwk_dict[param] = Network(f=f, s=s, name=param, comments=comments, f_unit='Hz') |
| 197 |
|
| 198 |
|
| 199 |
try: |
| 200 |
s=np.zeros((len(f),2,2), dtype=complex) |
| 201 |
s[:,0,0] = ntwk_dict['S11'].s.flatten() |
| 202 |
s[:,1,1] = ntwk_dict['S22'].s.flatten() |
| 203 |
s[:,1,0] = ntwk_dict['S21'].s.flatten() |
| 204 |
s[:,0,1] = ntwk_dict['S12'].s.flatten() |
| 205 |
name =os.path.splitext(os.path.basename(filename))[0] |
| 206 |
ntwk = Network(f=f, s=s, name=name, comments=comments) |
| 207 |
|
| 208 |
return ntwk |
| 209 |
except Exception: |
| 210 |
return ntwk_dict |
| 211 |
|
| 212 |
def pna_csv_2_ntwks3(filename): |
| 213 |
""" |
| 214 |
Read a CSV file exported from an Agilent PNA in dB/deg format. |
| 215 |
|
| 216 |
Parameters |
| 217 |
---------- |
| 218 |
filename : str |
| 219 |
full path or filename |
| 220 |
|
| 221 |
Returns |
| 222 |
------- |
| 223 |
out : n |
| 224 |
2-Port Network |
| 225 |
|
| 226 |
|
| 227 |
""" |
| 228 |
header, comments, d = read_pna_csv(filename) |
| 229 |
col_headers = pna_csv_header_split(filename) |
| 230 |
|
| 231 |
|
| 232 |
z0 = np.ones(np.shape(d)[0])*50 |
| 233 |
|
| 234 |
f = d[:,0] |
| 235 |
|
| 236 |
name = os.path.splitext(os.path.basename(filename))[0] |
| 237 |
|
| 238 |
if 'db' in header.lower() and 'deg' in header.lower(): |
| 239 |
|
| 240 |
|
| 241 |
s = np.zeros((len(f),2,2), dtype=complex) |
| 242 |
|
| 243 |
for k, h in enumerate(col_headers[1:]): |
| 244 |
if 's11' in h.lower() and 'db' in h.lower(): |
| 245 |
s[:,0,0] = mf.dbdeg_2_reim(d[:,k+1], d[:,k+2]) |
| 246 |
elif 's21' in h.lower() and 'db' in h.lower(): |
| 247 |
s[:,1,0] = mf.dbdeg_2_reim(d[:,k+1], d[:,k+2]) |
| 248 |
elif 's12' in h.lower() and 'db' in h.lower(): |
| 249 |
s[:,0,1] = mf.dbdeg_2_reim(d[:,k+1], d[:,k+2]) |
| 250 |
elif 's22' in h.lower() and 'db' in h.lower(): |
| 251 |
s[:,1,1] = mf.dbdeg_2_reim(d[:,k+1], d[:,k+2]) |
| 252 |
|
| 253 |
n = Network(f=f,s=s,z0=z0, name = name, f_unit="Hz") |
| 254 |
return n |
| 255 |
|
| 256 |
else: |
| 257 |
warn("File does not seem to be formatted properly (only dB/deg supported for now)", stacklevel=2) |
| 258 |
|
| 259 |
def read_all_csv(dir='.', contains = None): |
| 260 |
""" |
| 261 |
Read all CSV files in a directory. |
| 262 |
|
| 263 |
Parameters |
| 264 |
---------- |
| 265 |
dir : str, optional |
| 266 |
the directory to load from, default \'.\' |
| 267 |
contains : str, optional |
| 268 |
if not None, only files containing this substring will be loaded |
| 269 |
|
| 270 |
Returns |
| 271 |
------- |
| 272 |
out : dictionary |
| 273 |
dictionary containing all loaded CSV objects. keys are the |
| 274 |
filenames without extensions, and the values are the objects |
| 275 |
|
| 276 |
""" |
| 277 |
|
| 278 |
out={} |
| 279 |
for filename in os.listdir(dir): |
| 280 |
if contains is not None and contains not in filename: |
| 281 |
continue |
| 282 |
fullname = os.path.join(dir,filename) |
| 283 |
keyname = os.path.splitext(filename)[0] |
| 284 |
try: |
| 285 |
out[keyname] = pna_csv_2_ntwks3(fullname) |
| 286 |
continue |
| 287 |
except Exception: |
| 288 |
pass |
| 289 |
|
| 290 |
try: |
| 291 |
out[keyname] = Network(fullname) |
| 292 |
continue |
| 293 |
except Exception: |
| 294 |
pass |
| 295 |
|
| 296 |
return out |
| 297 |
|
| 298 |
|
| 299 |
class AgilentCSV: |
| 300 |
""" |
| 301 |
Agilent-style csv file representing either scalar traces vs frequency |
| 302 |
or complex data vs. frequency. |
| 303 |
|
| 304 |
|
| 305 |
""" |
| 306 |
def __init__(self, filename, *args, **kwargs): |
| 307 |
r""" |
| 308 |
Init. |
| 309 |
|
| 310 |
Parameters |
| 311 |
---------- |
| 312 |
filename : str |
| 313 |
filename |
| 314 |
\*args ,\*\*kwargs : |
| 315 |
passed to Network.__init__ in :func:`networks` and :func:`scalar_networks` |
| 316 |
""" |
| 317 |
self.filename = filename |
| 318 |
self.header, self.comments, self.data = self.read() |
| 319 |
self.args, self.kwargs = args, kwargs |
| 320 |
|
| 321 |
def read(self): |
| 322 |
""" |
| 323 |
Reads data from file. |
| 324 |
|
| 325 |
This function returns a triplet containing the header, comments, |
| 326 |
and data. |
| 327 |
|
| 328 |
Returns |
| 329 |
------- |
| 330 |
header : str |
| 331 |
The header string, which is the line following the 'BEGIN' |
| 332 |
comments : str |
| 333 |
All lines that begin with a '!' |
| 334 |
data : :class:`numpy.ndarray` |
| 335 |
An array containing the data. The meaning of which depends on |
| 336 |
the header. |
| 337 |
""" |
| 338 |
with open(self.filename) as fid: |
| 339 |
begin_line = -2 |
| 340 |
end_line = -1 |
| 341 |
comments = '' |
| 342 |
for k,line in enumerate(fid.readlines()): |
| 343 |
if line.startswith('!'): |
| 344 |
comments += line[1:] |
| 345 |
elif line.startswith('BEGIN'): |
| 346 |
begin_line = k |
| 347 |
elif line.startswith('END'): |
| 348 |
end_line = k |
| 349 |
|
| 350 |
if k == begin_line+1: |
| 351 |
header = line |
| 352 |
|
| 353 |
footer = k - end_line |
| 354 |
|
| 355 |
try: |
| 356 |
data = np.genfromtxt( |
| 357 |
self.filename, |
| 358 |
delimiter = ',', |
| 359 |
skip_header = begin_line + 2, |
| 360 |
skip_footer = footer, |
| 361 |
) |
| 362 |
except(ValueError): |
| 363 |
|
| 364 |
data = np.genfromtxt( |
| 365 |
self.filename, |
| 366 |
delimiter = ',', |
| 367 |
skip_header = (begin_line + 2)*2, |
| 368 |
skip_footer = footer, |
| 369 |
) |
| 370 |
|
| 371 |
|
| 372 |
header = header.replace('\xb0','deg').rstrip('\n').rstrip('\r') |
| 373 |
|
| 374 |
return header, comments, data |
| 375 |
|
| 376 |
@property |
| 377 |
def frequency(self): |
| 378 |
""" |
| 379 |
Frequency object : :class:`~skrf.frequency.Frequency`. |
| 380 |
""" |
| 381 |
d = self.data |
| 382 |
|
| 383 |
cols = self.columns |
| 384 |
try: |
| 385 |
f_unit = cols[0].split('(')[1].split(')')[0] |
| 386 |
except Exception: |
| 387 |
f_unit = 'hz' |
| 388 |
|
| 389 |
f = d[:,0] |
| 390 |
return Frequency.from_f(f, unit = f_unit) |
| 391 |
|
| 392 |
@property |
| 393 |
def n_traces(self): |
| 394 |
""" |
| 395 |
number of data traces : int |
| 396 |
""" |
| 397 |
return self.data.shape[1] - 1 |
| 398 |
|
| 399 |
@property |
| 400 |
def columns(self): |
| 401 |
""" |
| 402 |
List of column names : list of str. |
| 403 |
|
| 404 |
This function is needed because Agilent allows the delimiter |
| 405 |
of a csv file (ie `'`) to be present in the header name. ridiculous. |
| 406 |
|
| 407 |
If splitting the header fails, then a suitable list is returned of |
| 408 |
the correct length, which looks like:: |
| 409 |
|
| 410 |
['Freq(?)','filename-0','filename-1',..] |
| 411 |
""" |
| 412 |
header, d = self.header, self.data |
| 413 |
|
| 414 |
n_traces = d.shape[1] - 1 |
| 415 |
|
| 416 |
if header.count(',') == n_traces: |
| 417 |
cols = header.split(',') |
| 418 |
else: |
| 419 |
|
| 420 |
|
| 421 |
if header.count('),') == n_traces: |
| 422 |
cols = header.split('),') |
| 423 |
|
| 424 |
|
| 425 |
cols = [col + ')' for col in cols[:-1]] + [cols[-1]] |
| 426 |
else: |
| 427 |
|
| 428 |
warn('Cant decipher header, so I\'m creating one. check output. ', stacklevel=2) |
| 429 |
cols = ['Freq(?),']+['%s-%i'%(util.basename_noext(self.filename),k) \ |
| 430 |
for k in range(n_traces)] |
| 431 |
return cols |
| 432 |
|
| 433 |
@property |
| 434 |
def scalar_networks(self): |
| 435 |
""" |
| 436 |
Returns list of Networks for each column. |
| 437 |
|
| 438 |
|
| 439 |
.. note:: |
| 440 |
The data is stored in the Network's `.s` property, so its up |
| 441 |
to you to interpret results. if 'db' is in the column name then |
| 442 |
it is converted to linear before being store into `s`. |
| 443 |
|
| 444 |
|
| 445 |
Returns |
| 446 |
-------- |
| 447 |
out : list of :class:`~skrf.network.Network` objects |
| 448 |
list of Networks representing the data contained in each column |
| 449 |
|
| 450 |
""" |
| 451 |
comments = self.comments |
| 452 |
d = self.data |
| 453 |
n_traces = d.shape[1] - 1 |
| 454 |
cols = self.columns |
| 455 |
freq = self.frequency |
| 456 |
|
| 457 |
|
| 458 |
ntwk_list = [] |
| 459 |
for k in range(1,n_traces+1): |
| 460 |
s = d[:,k] |
| 461 |
if 'db' in cols[k].lower(): |
| 462 |
s = mf.db_2_mag(s) |
| 463 |
|
| 464 |
ntwk_list.append( |
| 465 |
Network( |
| 466 |
frequency = freq, s = s,comments = comments, |
| 467 |
name = cols[k], **self.kwargs) |
| 468 |
) |
| 469 |
|
| 470 |
return ntwk_list |
| 471 |
|
| 472 |
@property |
| 473 |
def networks(self): |
| 474 |
""" |
| 475 |
Reads a PNAX csv file, and returns a list of one-port Networks. |
| 476 |
|
| 477 |
|
| 478 |
.. note:: |
| 479 |
Note this only works if csv is save in Real/Imaginary format for now |
| 480 |
|
| 481 |
|
| 482 |
Parameters |
| 483 |
---------- |
| 484 |
filename : str |
| 485 |
filename |
| 486 |
|
| 487 |
Returns |
| 488 |
------- |
| 489 |
out : list of :class:`~skrf.network.Network` objects |
| 490 |
list of Networks representing the data contained in column pairs |
| 491 |
|
| 492 |
""" |
| 493 |
names = self.columns |
| 494 |
comments = self.comments |
| 495 |
d = self.data |
| 496 |
|
| 497 |
ntwk_list = [] |
| 498 |
if (self.n_traces)//2 == 0 : |
| 499 |
|
| 500 |
return self.scalar_networks |
| 501 |
else: |
| 502 |
for k in range((self.n_traces)//2): |
| 503 |
|
| 504 |
name = names[k*2+1] |
| 505 |
|
| 506 |
if 'db' in names[k].lower() and 'deg' in names[k+1].lower(): |
| 507 |
s = mf.dbdeg_2_reim(d[:,k*2+1], d[:,k*2+2]) |
| 508 |
elif 'real' in names[k].lower() and 'imag' in names[k+1].lower(): |
| 509 |
s = d[:,k*2+1]+1j*d[:,k*2+2] |
| 510 |
else: |
| 511 |
warn(f'CSV format unrecognized in "{names[k]}" or "{names[k+1]}". ' |
| 512 |
'It\'s up to you to interpret the resulting network correctly.', stacklevel=2) |
| 513 |
s = d[:,k*2+1]+1j*d[:,k*2+2] |
| 514 |
|
| 515 |
ntwk_list.append( |
| 516 |
Network(frequency = self.frequency, s=s, name=name, |
| 517 |
comments=comments, **self.kwargs) |
| 518 |
) |
| 519 |
|
| 520 |
return ntwk_list |
| 521 |
|
| 522 |
@property |
| 523 |
def dict(self): |
| 524 |
""" |
| 525 |
Dictionary representation of csv file. |
| 526 |
|
| 527 |
Returns |
| 528 |
------- |
| 529 |
dict : dict |
| 530 |
|
| 531 |
""" |
| 532 |
return { self.columns[k]:self.data[:,k] \ |
| 533 |
for k in range(self.n_traces+1)} |
| 534 |
|
| 535 |
@property |
| 536 |
def dataframe(self): |
| 537 |
""" |
| 538 |
Pandas DataFrame representation of csv file. |
| 539 |
|
| 540 |
Returns |
| 541 |
------- |
| 542 |
df : `pandas.DataFrame` |
| 543 |
|
| 544 |
""" |
| 545 |
from pandas import DataFrame, Index |
| 546 |
|
| 547 |
index = Index( |
| 548 |
self.frequency.f_scaled, |
| 549 |
name = f'Frequency({self.frequency.unit})') |
| 550 |
|
| 551 |
return DataFrame( |
| 552 |
{ self.columns[k]:self.data[:,k] \ |
| 553 |
for k in range(1,self.n_traces+1)}, |
| 554 |
index=index, |
| 555 |
) |
| 556 |
|
| 557 |
def pna_csv_header_split(filename): |
| 558 |
""" |
| 559 |
Split a Agilent csv file's header into a list |
| 560 |
|
| 561 |
This function is needed because Agilent allows the delimiter |
| 562 |
of a csv file (ie `'`) to be present in the header name. ridiculous. |
| 563 |
|
| 564 |
If splitting the header fails, then a suitable list is returned of |
| 565 |
the correct length, which looks like |
| 566 |
* ['Freq(?)','filename-0','filename-1',..] |
| 567 |
|
| 568 |
Parameters |
| 569 |
------------ |
| 570 |
filename : str |
| 571 |
csv filename |
| 572 |
|
| 573 |
Returns |
| 574 |
-------- |
| 575 |
cols : list of str's |
| 576 |
list of column names |
| 577 |
""" |
| 578 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 579 |
header, comments, d = read_pna_csv(filename) |
| 580 |
|
| 581 |
n_traces = d.shape[1] - 1 |
| 582 |
|
| 583 |
if header.count(',') == n_traces: |
| 584 |
cols = header.split(',') |
| 585 |
else: |
| 586 |
|
| 587 |
|
| 588 |
if header.count('),') == n_traces: |
| 589 |
cols = header.split('),') |
| 590 |
|
| 591 |
|
| 592 |
cols = [col + ')' for col in cols[:-1]] + [cols[-1]] |
| 593 |
else: |
| 594 |
|
| 595 |
warn('Cant decipher header, so im creating one. check output. ', stacklevel=2) |
| 596 |
cols = ['Freq(?),']+['%s-%i'%(util.basename_noext(filename),k) \ |
| 597 |
for k in range(n_traces)] |
| 598 |
return cols |
| 599 |
|
| 600 |
def pna_csv_2_ntwks(filename): |
| 601 |
""" |
| 602 |
Reads a PNAX csv file, and returns a list of one-port Networks. |
| 603 |
|
| 604 |
|
| 605 |
.. deprecated:: |
| 606 |
Use :func:`pna_csv_2_ntwks3` instead. |
| 607 |
|
| 608 |
|
| 609 |
.. note:: |
| 610 |
Note this only works if csv is save in Real/Imaginary format for now |
| 611 |
|
| 612 |
|
| 613 |
Parameters |
| 614 |
---------- |
| 615 |
filename : str |
| 616 |
filename |
| 617 |
|
| 618 |
Returns |
| 619 |
------- |
| 620 |
out : list of :class:`~skrf.network.Network` objects |
| 621 |
list of Networks representing the data contained in column pairs |
| 622 |
|
| 623 |
""" |
| 624 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 625 |
|
| 626 |
header, comments, d = read_pna_csv(filename) |
| 627 |
|
| 628 |
|
| 629 |
names = pna_csv_header_split(filename) |
| 630 |
|
| 631 |
ntwk_list = [] |
| 632 |
|
| 633 |
|
| 634 |
if (d.shape[1]-1)/2 == 0 : |
| 635 |
|
| 636 |
f = d[:,0] |
| 637 |
if 'db' in header.lower(): |
| 638 |
s = mf.db_2_mag(d[:,1]) |
| 639 |
else: |
| 640 |
raise (NotImplementedError) |
| 641 |
name = os.path.splitext(os.path.basename(filename))[0] |
| 642 |
return Network(f=f, s=s, name=name, comments=comments, f_unit='Hz') |
| 643 |
else: |
| 644 |
for k in range(int((d.shape[1]-1)/2)): |
| 645 |
f = d[:,0] |
| 646 |
name = names[k] |
| 647 |
print((names[k], names[k+1])) |
| 648 |
if 'db' in names[k].lower() and 'deg' in names[k+1].lower(): |
| 649 |
s = mf.dbdeg_2_reim(d[:,k*2+1], d[:,k*2+2]) |
| 650 |
elif 'real' in names[k].lower() and 'imag' in names[k+1].lower(): |
| 651 |
s = d[:,k*2+1]+1j*d[:,k*2+2] |
| 652 |
else: |
| 653 |
print('WARNING: csv format unrecognized. ts up to you to interpret the resultant network correctly.') |
| 654 |
s = d[:,k*2+1]+1j*d[:,k*2+2] |
| 655 |
|
| 656 |
ntwk_list.append( |
| 657 |
Network(f=f, s=s, name=name, comments=comments, f_unit='Hz') |
| 658 |
) |
| 659 |
|
| 660 |
return ntwk_list |
| 661 |
|
| 662 |
def pna_csv_2_freq(filename): |
| 663 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 664 |
header, comments, d = read_pna_csv(filename) |
| 665 |
|
| 666 |
f = d[:,0] |
| 667 |
return Frequency.from_f(f, unit = "Hz") |
| 668 |
|
| 669 |
|
| 670 |
def pna_csv_2_scalar_ntwks(filename, *args, **kwargs): |
| 671 |
""" |
| 672 |
Reads a PNAX csv file containing scalar traces, returning Networks |
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
Parameters |
| 677 |
----------- |
| 678 |
filename : str |
| 679 |
filename |
| 680 |
|
| 681 |
Returns |
| 682 |
-------- |
| 683 |
out : list of :class:`~skrf.network.Network` objects |
| 684 |
list of Networks representing the data contained in column pairs |
| 685 |
|
| 686 |
""" |
| 687 |
warn("deprecated", DeprecationWarning, stacklevel=2) |
| 688 |
header, comments, d = read_pna_csv(filename) |
| 689 |
|
| 690 |
n_traces = d.shape[1] - 1 |
| 691 |
|
| 692 |
cols = pna_csv_header_split(filename) |
| 693 |
|
| 694 |
f = d[:,0] |
| 695 |
freq = Frequency.from_f(f, unit = 'Hz') |
| 696 |
|
| 697 |
|
| 698 |
ntwk_list = [] |
| 699 |
for k in range(1,n_traces+1): |
| 700 |
s = d[:,k] |
| 701 |
if 'db' in cols[k].lower(): |
| 702 |
s = mf.db_2_mag(s) |
| 703 |
|
| 704 |
ntwk_list.append( |
| 705 |
Network( |
| 706 |
frequency = freq, s = s,comments = comments, |
| 707 |
name = cols[k], **kwargs) |
| 708 |
) |
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
return ntwk_list |
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
def read_zva_dat(filename, *args, **kwargs): |
| 718 |
r""" |
| 719 |
Reads data from a dat file written by a R&S ZVA in dB/deg or re/im format. |
| 720 |
|
| 721 |
This function returns a triplet containing header, comments and data. |
| 722 |
|
| 723 |
|
| 724 |
Parameters |
| 725 |
---------- |
| 726 |
filename : str |
| 727 |
the file |
| 728 |
\*args, \*\*kwargs : |
| 729 |
|
| 730 |
Returns |
| 731 |
------- |
| 732 |
header : str |
| 733 |
The header string, which is the line following the 'BEGIN' |
| 734 |
data : :class:`numpy.ndarray` |
| 735 |
An array containing the data. The meaning of which depends on |
| 736 |
the header. |
| 737 |
|
| 738 |
""" |
| 739 |
|
| 740 |
with open(filename) as fid: |
| 741 |
begin_line = -2 |
| 742 |
comments = '' |
| 743 |
for k,line in enumerate(fid.readlines()): |
| 744 |
if line.startswith('%'): |
| 745 |
comments += line[1:] |
| 746 |
header = line |
| 747 |
begin_line = k+1 |
| 748 |
|
| 749 |
data = np.genfromtxt( |
| 750 |
filename, |
| 751 |
delimiter = ',', |
| 752 |
skip_header = begin_line, |
| 753 |
**kwargs |
| 754 |
) |
| 755 |
|
| 756 |
return header, comments, data |
| 757 |
|
| 758 |
def zva_dat_2_ntwks(filename): |
| 759 |
""" |
| 760 |
Read a dat file exported from a R&S ZVA in dB/deg or re/im format. |
| 761 |
|
| 762 |
Parameters |
| 763 |
---------- |
| 764 |
filename : str |
| 765 |
full path or filename |
| 766 |
|
| 767 |
Returns |
| 768 |
------- |
| 769 |
out : n |
| 770 |
2-Port Network |
| 771 |
|
| 772 |
|
| 773 |
""" |
| 774 |
header, comments, d = read_zva_dat(filename) |
| 775 |
col_headers = header.split(',') |
| 776 |
|
| 777 |
|
| 778 |
z0 = np.ones(np.shape(d)[0])*50 |
| 779 |
|
| 780 |
f = d[:,0]/1e9 |
| 781 |
|
| 782 |
name = os.path.splitext(os.path.basename(filename))[0] |
| 783 |
|
| 784 |
if 're' in header.lower() and 'im' in header.lower(): |
| 785 |
|
| 786 |
|
| 787 |
s = np.zeros((len(f),2,2), dtype=complex) |
| 788 |
|
| 789 |
for k, h in enumerate(col_headers): |
| 790 |
if 's11' in h.lower() and 're' in h.lower(): |
| 791 |
s[:,0,0] = d[:,k] + 1j*d[:,k+1] |
| 792 |
elif 's21' in h.lower() and 're' in h.lower(): |
| 793 |
s[:,1,0] = d[:,k] + 1j*d[:,k+1] |
| 794 |
elif 's12' in h.lower() and 're' in h.lower(): |
| 795 |
s[:,0,1] = d[:,k+1] |
| 796 |
elif 's22' in h.lower() and 're' in h.lower(): |
| 797 |
s[:,1,1] = d[:,k+1] |
| 798 |
|
| 799 |
elif 'db' in header.lower() and "deg" not in header.lower(): |
| 800 |
|
| 801 |
|
| 802 |
s = np.zeros((len(f),2,2), dtype=complex) |
| 803 |
|
| 804 |
for k, h in enumerate(col_headers): |
| 805 |
|
| 806 |
|
| 807 |
if 's11' in h.lower() and 'db' in h.lower(): |
| 808 |
s[:,0,0] = mf.dbdeg_2_reim(d[:,k], d[:,k+2]) |
| 809 |
elif 's21' in h.lower() and 'db' in h.lower(): |
| 810 |
s[:,1,0] = mf.dbdeg_2_reim(d[:,k], d[:,k+2]) |
| 811 |
|
| 812 |
n = Network(f=f,s=s,z0=z0, name = name) |
| 813 |
return n |
| 814 |
|
| 815 |
else: |
| 816 |
warn("File does not seem to be formatted properly (dB/deg or re/im)", stacklevel=2) |
| 817 |
|
| 818 |
def read_all_zva_dat(dir='.', contains = None): |
| 819 |
""" |
| 820 |
Read all DAT files in a directory (from R&S ZVA). |
| 821 |
|
| 822 |
Parameters |
| 823 |
---------- |
| 824 |
dir : str, optional |
| 825 |
the directory to load from, default \'.\' |
| 826 |
contains : str, optional |
| 827 |
if not None, only files containing this substring will be loaded |
| 828 |
|
| 829 |
Returns |
| 830 |
------- |
| 831 |
out : dictionary |
| 832 |
dictionary containing all loaded DAT objects. keys are the |
| 833 |
filenames without extensions, and the values are the objects |
| 834 |
|
| 835 |
|
| 836 |
""" |
| 837 |
|
| 838 |
out={} |
| 839 |
for filename in os.listdir(dir): |
| 840 |
if contains is not None and contains not in filename: |
| 841 |
continue |
| 842 |
fullname = os.path.join(dir,filename) |
| 843 |
keyname = os.path.splitext(filename)[0] |
| 844 |
try: |
| 845 |
out[keyname] = zva_dat_2_ntwks(fullname) |
| 846 |
continue |
| 847 |
except Exception: |
| 848 |
pass |
| 849 |
|
| 850 |
try: |
| 851 |
out[keyname] = Network(fullname) |
| 852 |
continue |
| 853 |
except Exception: |
| 854 |
pass |
| 855 |
|
| 856 |
return out |
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
def read_vectorstar_csv(filename, *args, **kwargs): |
| 861 |
r""" |
| 862 |
Reads data from a csv file written by an Anritsu VectorStar. |
| 863 |
|
| 864 |
Parameters |
| 865 |
---------- |
| 866 |
filename : str |
| 867 |
the file |
| 868 |
\*args, \*\*kwargs : |
| 869 |
|
| 870 |
Returns |
| 871 |
------- |
| 872 |
header : str |
| 873 |
The header string, which is the line just before the data |
| 874 |
comments : str |
| 875 |
All lines that begin with a '!' |
| 876 |
data : :class:`numpy.ndarray` |
| 877 |
An array containing the data. The meaning of which depends on |
| 878 |
the header. |
| 879 |
|
| 880 |
|
| 881 |
""" |
| 882 |
with open(filename) as fid: |
| 883 |
comments = ''.join([line for line in fid if line.startswith('!')]) |
| 884 |
fid.seek(0) |
| 885 |
header = [line for line in fid if line.startswith('PNT')] |
| 886 |
fid.close() |
| 887 |
data = np.genfromtxt( |
| 888 |
filename, |
| 889 |
comments='!', |
| 890 |
delimiter =',', |
| 891 |
skip_header = 1)[1:] |
| 892 |
comments = comments.replace('\r','') |
| 893 |
comments = comments.replace('!','') |
| 894 |
|
| 895 |
return header, comments, data |
| 896 |
|
| 897 |
def vectorstar_csv_2_ntwks(filename): |
| 898 |
""" |
| 899 |
Reads a vectorstar csv file, and returns a list of one-port Networks. |
| 900 |
|
| 901 |
|
| 902 |
.. note:: |
| 903 |
Note this only works if csv is save in Real/Imaginary format for now |
| 904 |
|
| 905 |
|
| 906 |
Parameters |
| 907 |
---------- |
| 908 |
filename : str |
| 909 |
filename |
| 910 |
|
| 911 |
Returns |
| 912 |
------- |
| 913 |
out : list of :class:`~skrf.network.Network` objects |
| 914 |
list of Networks representing the data contained in column pairs |
| 915 |
|
| 916 |
""" |
| 917 |
|
| 918 |
header, comments, d = read_vectorstar_csv(filename) |
| 919 |
names = [line for line in comments.split('\n') \ |
| 920 |
if line.startswith('PARAMETER')][0].split(',')[1:] |
| 921 |
|
| 922 |
|
| 923 |
return [Network( |
| 924 |
f = d[:,k*3+1], |
| 925 |
s = d[:,k*3+2] + 1j*d[:,k*3+3], |
| 926 |
z0 = 50, |
| 927 |
name = names[k].rstrip(), |
| 928 |
comments = comments, |
| 929 |
) for k in range(d.shape[1]/3)] |