front.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import math
  2. import streamlit as st
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import sigfig
  6. from streamlit_ace import st_ace
  7. from streamlit_echarts import st_echarts, JsCode
  8. # So that you can choose an interval of points on which we apply q-calc algorithm
  9. def plot_interact_abs_from_f(f, r, i, interval_range):
  10. if interval_range is None:
  11. interval_range = (0, 100)
  12. abs_S = list(abs(np.array(r) + 1j * np.array(i)))
  13. # echarts for datazoom https://discuss.streamlit.io/t/streamlit-echarts/3655
  14. # datazoom https://echarts.apache.org/examples/en/editor.html?c=line-draggable&lang=ts
  15. # axis pointer values https://echarts.apache.org/en/option.html#axisPointer
  16. options = {
  17. "xAxis": {
  18. "type": "category",
  19. "data": f,
  20. "name": "Hz",
  21. "nameTextStyle": {"fontSize": 16},
  22. "axisLabel": {"fontSize": 16},
  23. },
  24. "yAxis": {
  25. "type": "value",
  26. "name": "abs(S)",
  27. "nameTextStyle": {"fontSize": 16},
  28. "axisLabel": {"fontSize": 16},
  29. # "axisPointer": {
  30. # "type": 'cross',
  31. # "label": {
  32. # "show":"true",
  33. # "formatter": JsCode(
  34. # "function(info){console.log(info);return 'line ' ;};"
  35. # ).js_code
  36. # }
  37. # }
  38. },
  39. "series": [{"data": abs_S, "type": "line", "name": "abs(S)"}],
  40. "height": 300,
  41. "dataZoom": [{"type": "slider", "start": interval_range[0], "end": interval_range[1], "height": 100, "bottom": 10}],
  42. "tooltip": {
  43. "trigger": "axis",
  44. "axisPointer": {
  45. "type": 'cross',
  46. # "label": {
  47. # "show":"true",
  48. # "formatter": JsCode(
  49. # "function(info){console.log(info);return 'line ' ;};"
  50. # ).js_code
  51. # }
  52. }
  53. },
  54. "toolbox": {
  55. "feature": {
  56. # "dataView": { "show": "true", "readOnly": "true" },
  57. "restore": {"show": "true"},
  58. }
  59. },
  60. }
  61. # DataZoom event is not fired on new file upload. There are no default event to fix it.
  62. events = {
  63. "dataZoom": "function(params) { return ['dataZoom', params.start, params.end] }",
  64. "restore": "function() { return ['restore'] }",
  65. }
  66. # show echart with dataZoom and update intervals based on output
  67. get_event = st_echarts(
  68. options=options, events=events, height="500px", key="render_basic_bar_events"
  69. )
  70. if not get_event is None and get_event[0] == 'dataZoom':
  71. interval_range = get_event[1:]
  72. n = len(f)
  73. interval_start, interval_end = (
  74. int(n*interval_range[id]*0.01) for id in (0, 1))
  75. return interval_range, interval_start, interval_end
  76. def circle(ax, x, y, radius, color='#1946BA'):
  77. from matplotlib.patches import Ellipse
  78. drawn_circle = Ellipse((x, y), radius * 2, radius * 2, clip_on=True,
  79. zorder=2, linewidth=2, edgecolor=color, facecolor=(0, 0, 0, .0125))
  80. ax.add_artist(drawn_circle)
  81. def plot_smith(r, i, g, r_cut, i_cut, show_excluded):
  82. fig = plt.figure(figsize=(10, 10))
  83. ax = fig.add_subplot()
  84. # major_ticks = np.arange(-1.0, 1.1, 0.25)
  85. minor_ticks = np.arange(-1.1, 1.1, 0.05)
  86. # ax.set_xticks(major_ticks)
  87. ax.set_xticks(minor_ticks, minor=True)
  88. # ax.set_yticks(major_ticks)
  89. ax.set_yticks(minor_ticks, minor=True)
  90. ax.grid(which='major', color='grey', linewidth=1.5)
  91. ax.grid(which='minor', color='grey', linewidth=0.5, linestyle=':')
  92. plt.xlabel('$Re(\Gamma)$', color='gray', fontsize=16, fontname="Cambria")
  93. plt.ylabel('$Im(\Gamma)$', color='gray', fontsize=16, fontname="Cambria")
  94. plt.title('Smith chart', fontsize=24, fontname="Cambria")
  95. # unit circle
  96. circle(ax, 0, 0, 1)
  97. # input data points
  98. if show_excluded:
  99. ax.plot(r, i, '+', ms=8, mew=2, color='#b6c7f4')
  100. # choosen data points
  101. ax.plot(r_cut, i_cut, '+', ms=8, mew=2, color='#1946BA')
  102. # circle approximation by calc
  103. radius = abs(g[1] - g[0] / g[2]) / 2
  104. x = ((g[1] + g[0] / g[2]) / 2).real
  105. y = ((g[1] + g[0] / g[2]) / 2).imag
  106. circle(ax, x, y, radius, color='#FF8400')
  107. XLIM = [-1.1, 1.1]
  108. YLIM = [-1.1, 1.1]
  109. ax.set_xlim(XLIM)
  110. ax.set_ylim(YLIM)
  111. st.pyplot(fig)
  112. # plot (abs(S))(f) chart with pyplot
  113. def plot_abs_vs_f(f, r, i, fitted_mag_s):
  114. fig = plt.figure(figsize=(10, 10))
  115. abs_S = list((r[n] ** 2 + i[n] ** 2)**0.5 for n in range(len(r)))
  116. xlim = [min(f) - abs(max(f) - min(f)) * 0.1,
  117. max(f) + abs(max(f) - min(f)) * 0.1]
  118. ylim = [min(abs_S) - abs(max(abs_S) - min(abs_S)) * 0.5,
  119. max(abs_S) + abs(max(abs_S) - min(abs_S)) * 0.5]
  120. ax = fig.add_subplot()
  121. ax.set_xlim(xlim)
  122. ax.set_ylim(ylim)
  123. ax.grid(which='major', color='k', linewidth=1)
  124. ax.grid(which='minor', color='grey', linestyle=':', linewidth=0.5)
  125. plt.xlabel(r'$f,\; 1/c$', color='gray', fontsize=16, fontname="Cambria")
  126. plt.ylabel('$|S|$', color='gray', fontsize=16, fontname="Cambria")
  127. plt.title('Abs(S) vs frequency',
  128. fontsize=24, fontname="Cambria")
  129. ax.plot(f, abs_S, '+', ms=8, mew=2, color='#1946BA')
  130. ax.plot(f, fitted_mag_s, '-',ms=8, mew=8, color='#FF8400')
  131. # radius = abs(g[1] - g[0] / g[2]) / 2
  132. # x = ((g[1] + g[0] / g[2]) / 2).real
  133. # y = ((g[1] + g[0] / g[2]) / 2).imag
  134. st.pyplot(fig)
  135. def run(calc_function):
  136. def is_float(element) -> bool:
  137. try:
  138. float(element)
  139. val = float(element)
  140. if math.isnan(val) or math.isinf(val):
  141. raise ValueError
  142. return True
  143. except ValueError:
  144. return False
  145. # to utf-8
  146. def read_data(data):
  147. for x in range(len(data)):
  148. if type(data[x]) == bytes:
  149. try:
  150. data[x] = data[x].decode('utf-8-sig', 'ignore')
  151. except:
  152. return 'Not an utf-8-sig line №: ' + str(x)
  153. return 'data read, but not parsed'
  154. # for Touchstone .snp format
  155. def parse_heading(data):
  156. nonlocal data_format_snp
  157. if data_format_snp:
  158. for x in range(len(data)):
  159. if data[x][0] == '#':
  160. line = data[x].split()
  161. if len(line) == 6:
  162. repr_map = {"RI": 0, "MA": 1, "DB": 2}
  163. para_map = {"S": 0, "Z": 1}
  164. hz_map = {"GHz": 10**9, "MHz": 10 **6, "KHz": 10**3, "Hz": 1}
  165. hz, measurement_parameter, data_representation, _r, ref_resistance = line[1:]
  166. try:
  167. return hz_map[hz], para_map[measurement_parameter], repr_map[data_representation], int(ref_resistance)
  168. except:
  169. break
  170. break
  171. return 1, 0, 0, 50
  172. # check if line has comments
  173. # first is a comment line according to .snp documentation,
  174. # others detects comments in various languages
  175. def check_line_comments(line):
  176. if len(line) < 2 or line[0] == '!' or line[0] == '#' or line[0] == '%' or line[0] == '/':
  177. return None
  178. else:
  179. # generally we expect these chars as separators
  180. line = line.replace(';', ' ').replace(',', ' ')
  181. if '!' in line:
  182. line = line[:line.find('!')]
  183. return line
  184. # unpack a few first lines of the file to get number of ports
  185. def count_columns(data):
  186. return_status = 'data parsed'
  187. column_count = 0
  188. for x in range(len(data)):
  189. line = check_line_comments(data[x])
  190. if line is None:
  191. continue
  192. line = line.split()
  193. # always at least 3 values for single data point
  194. if len(line) < 3:
  195. return_status = 'Can\'t parse line № ' + \
  196. str(x) + ',\n not enough arguments (less than 3)'
  197. break
  198. column_count = len(line)
  199. break
  200. return column_count, return_status
  201. def prepare_snp(data, number):
  202. prepared_data = []
  203. return_status = 'data read, but not parsed'
  204. for x in range(len(data)):
  205. line = check_line_comments(data[x])
  206. if line is None:
  207. continue
  208. splitted_line = line.split()
  209. if number * 2 + 1 == len(splitted_line):
  210. prepared_data.append(line)
  211. elif number * 2 == len(splitted_line):
  212. prepared_data[-1] += line
  213. else:
  214. return_status = "Parsing error for .snp format on line №" + str(x)
  215. return prepared_data, return_status
  216. def unpack_data(data, first_column, column_count, ref_resistance, ace_preview_markers):
  217. nonlocal select_measurement_parameter
  218. nonlocal select_data_representation
  219. f, r, i = [], [], []
  220. return_status = 'data parsed'
  221. for x in range(len(data)):
  222. line = check_line_comments(data[x])
  223. if line is None:
  224. continue
  225. line = line.split()
  226. if column_count != len(line):
  227. return_status = "Wrong number of parameters on line № " + str(x)
  228. break
  229. # 1: process according to data_placement
  230. a, b, c = None, None, None
  231. try:
  232. a = line[0]
  233. b = line[first_column]
  234. c = line[first_column+1]
  235. except:
  236. return_status = 'Can\'t parse line №: ' + \
  237. str(x) + ',\n not enough arguments'
  238. break
  239. if not ((is_float(a)) or (is_float(b)) or (is_float(c))):
  240. return_status = 'Wrong data type, expected number. Error on line: ' + \
  241. str(x)
  242. break
  243. # mark as processed
  244. for y in (a,b,c):
  245. ace_preview_markers.append(
  246. {"startRow": x,"startCol": 0,
  247. "endRow": x,"endCol": data[x].find(y)+len(y),
  248. "className": "ace_stack","type": "text"})
  249. a, b, c = (float(x) for x in (a, b, c))
  250. f.append(a) # frequency
  251. # 2: process according to data_representation
  252. if select_data_representation == 'Frequency, real, imaginary':
  253. # std format
  254. r.append(b) # Re
  255. i.append(c) # Im
  256. elif select_data_representation == 'Frequency, magnitude, angle':
  257. r.append(b*np.cos(np.deg2rad(c)))
  258. i.append(b*np.sin(np.deg2rad(c)))
  259. elif select_data_representation == 'Frequency, db, angle':
  260. b = 10**(b/20)
  261. r.append(b*np.cos(np.deg2rad(c)))
  262. i.append(b*np.sin(np.deg2rad(c)))
  263. else:
  264. return_status = 'Wrong data format'
  265. break
  266. # 3: process according to measurement_parameter
  267. if select_measurement_parameter == 'Z':
  268. # normalization
  269. r[-1] = r[-1]/ref_resistance
  270. i[-1] = i[-1]/ref_resistance
  271. # translate to S
  272. try:
  273. # center_x + 1j*center_y, radius
  274. p1, r1 = r[-1] / (1 + r[-1]) + 0j, 1 / (1 + r[-1]) #real
  275. p2, r2 = 1 + 1j * (1 / i[-1]), 1 / i[-1] #imag
  276. d = abs(p2-p1)
  277. q = (r1**2 - r2**2 + d**2) / (2 * d)
  278. h = (r1**2 - q**2)**0.5
  279. p = p1 + q * (p2 - p1) / d
  280. intersect = [
  281. (p.real + h * (p2.imag - p1.imag) / d,
  282. p.imag - h * (p2.real - p1.real) / d),
  283. (p.real - h * (p2.imag - p1.imag) / d,
  284. p.imag + h * (p2.real - p1.real) / d)]
  285. intersect = [x+1j*y for x,y in intersect]
  286. intersect_shift = [p-(1+0j) for p in intersect]
  287. intersect_shift = abs(np.array(intersect_shift))
  288. p=intersect[0]
  289. if intersect_shift[0]<intersect_shift[1]:
  290. p=intersect[1]
  291. r[-1] = p.real
  292. i[-1] = p.imag
  293. except:
  294. r.pop()
  295. i.pop()
  296. f.pop()
  297. if return_status == 'data parsed':
  298. if len(f) < 3 or len(f) != len(r) or len(f) != len(i):
  299. return_status = 'Choosen data range is too small, add more points'
  300. elif max(abs(np.array(r)+ 1j* np.array(i))) > 2:
  301. return_status = 'Your data points have an abnormality:\
  302. they are too far outside the unit cirlce.\
  303. Make sure the format is correct'
  304. return f, r, i, return_status
  305. # make accessible a specific range of numerical data choosen with interactive plot
  306. # percent, line id, line id
  307. interval_range, interval_start, interval_end = None, None, None
  308. # info
  309. with st.expander("Info"):
  310. # streamlit.markdown does not support footnotes
  311. try:
  312. with open('./source/frontend/info.md') as f:
  313. st.markdown(f.read())
  314. except:
  315. st.write('Wrong start directory, see readme')
  316. # file upload button
  317. uploaded_file = st.file_uploader('Upload a file from your vector analizer. \
  318. Make sure the file format is .snp or it has a similar inner structure.' )
  319. # check .snp
  320. data_format_snp = False
  321. data_format_snp_number = 0
  322. if uploaded_file is None:
  323. st.write("DEMO: ")
  324. # display DEMO
  325. data_format_snp = True
  326. try:
  327. with open('./resource/data/8_default_demo.s1p') as f:
  328. data = f.readlines()
  329. except:
  330. # 'streamlit run' call in the wrong directory. Display smaller demo:
  331. data =['# Hz S MA R 50\n\
  332. 11415403125 0.37010744 92.47802\n\
  333. 11416090625 0.33831283 92.906929\n\
  334. 11416778125 0.3069371 94.03318' ]
  335. else:
  336. data = uploaded_file.readlines()
  337. if uploaded_file.name[-4:-2]=='.s' and uploaded_file.name[-1]== 'p':
  338. data_format_snp = True
  339. data_format_snp_number = int(uploaded_file.name[-2])
  340. validator_status = '...'
  341. ace_preview_markers = []
  342. column_count = 0
  343. # data loaded
  344. circle_params = []
  345. if len(data) > 0:
  346. validator_status = read_data(data)
  347. if validator_status == 'data read, but not parsed':
  348. hz, select_measurement_parameter, select_data_representation, input_ref_resistance = parse_heading(data)
  349. col1, col2 = st.columns([1,2])
  350. ace_text_value = ''.join(data).strip()
  351. with col1.expander("Processing options"):
  352. select_measurement_parameter = st.selectbox('Measurement parameter',
  353. ['S', 'Z'],
  354. select_measurement_parameter)
  355. select_data_representation = st.selectbox('Data representation',
  356. ['Frequency, real, imaginary',
  357. 'Frequency, magnitude, angle',
  358. 'Frequency, db, angle'],
  359. select_data_representation)
  360. if select_measurement_parameter=='Z':
  361. input_ref_resistance = st.number_input(
  362. "Reference resistance:", min_value=0, value=input_ref_resistance)
  363. input_start_line = int(st.number_input(
  364. "First line for processing:", min_value=1, max_value=len(data)))
  365. input_end_line = int(st.number_input(
  366. "Last line for processing:", min_value=1, max_value=len(data), value=len(data)))
  367. data = data[input_start_line-1:input_end_line]
  368. # Ace editor to show choosen data columns and rows
  369. with col2.expander("File preview"):
  370. # st.button(copy selection)
  371. # So little 'official' functionality in libs and lack of documentation
  372. # therefore beware: css hacks
  373. # yellow ~ ace_step
  374. # light yellow ~ ace_highlight-marker
  375. # green ~ ace_stack
  376. # red ~ ace_error-marker
  377. # no more good colors included in streamlit_ace for marking
  378. # st.markdown('''<style>
  379. # .choosen_option_1
  380. # {
  381. # color: rgb(49, 51, 63);
  382. # }</style>''', unsafe_allow_html=True)
  383. # markdown injection does not seems to work, since ace is in a different .html accessible via iframe
  384. # markers format:
  385. #[{"startRow": 2,"startCol": 0,"endRow": 2,"endCol": 3,"className": "ace_error-marker","type": "text"}]
  386. # add marking for choosen data lines TODO
  387. ace_preview_markers.append({
  388. "startRow": input_start_line - 1,
  389. "startCol": 0,
  390. "endRow": input_end_line,
  391. "endCol": 0,
  392. "className": "ace_highlight-marker",
  393. "type": "text"
  394. })
  395. st_ace(value=ace_text_value,
  396. readonly=True,
  397. auto_update=True,
  398. placeholder="Your file is empty",
  399. markers=ace_preview_markers,
  400. height="300px")
  401. if data_format_snp and data_format_snp_number >= 3:
  402. data, validator_status = prepare_snp(data, data_format_snp_number)
  403. if validator_status == "data read, but not parsed":
  404. column_count, validator_status = count_columns(data)
  405. f, r, i = [], [], []
  406. if validator_status == "data parsed":
  407. input_ports_pair = 1
  408. if column_count > 3:
  409. pair_count = (column_count - 1) // 2
  410. input_ports_pair = st.number_input(
  411. "Choosen pair of ports with network parameters:",
  412. min_value=1,
  413. max_value=pair_count,
  414. value=1)
  415. input_ports_pair_id = input_ports_pair - 1
  416. ports_count = round(pair_count**0.5)
  417. st.write(select_measurement_parameter +
  418. str(input_ports_pair_id // ports_count + 1) +
  419. str(input_ports_pair_id % ports_count + 1))
  420. f, r, i, validator_status = unpack_data(data,
  421. (input_ports_pair - 1) * 2 + 1,
  422. column_count,
  423. input_ref_resistance,
  424. ace_preview_markers)
  425. f = [x * hz for x in f] # to hz
  426. st.write("Use range slider to choose best suitable data interval")
  427. interval_range, interval_start, interval_end = plot_interact_abs_from_f(f, r, i, interval_range)
  428. f_cut, r_cut, i_cut = [], [], []
  429. if validator_status == "data parsed":
  430. f_cut, r_cut, i_cut = (x[interval_start:interval_end]
  431. for x in (f, r, i))
  432. with st.expander("Selected data interval as .s1p"):
  433. st_ace(value="# Hz S RI R 50\n" +
  434. ''.join(f'{f_cut[x]} {r_cut[x]} {i_cut[x]}\n' for x in range(len(f_cut))),
  435. readonly=True,
  436. auto_update=True,
  437. placeholder="Selection is empty",
  438. height="150px")
  439. if len(f_cut) < 3:
  440. validator_status = "Choosen interval is too small, add more points"
  441. st.write("Status: " + validator_status)
  442. if validator_status == "data parsed":
  443. col1, col2 = st.columns(2)
  444. check_coupling_loss = col1.checkbox(
  445. 'Apply correction for coupling loss')
  446. if check_coupling_loss:
  447. col1.write("Option: Lossy coupling")
  448. else:
  449. col1.write("Option: Cable attenuation")
  450. select_autoformat = col2.checkbox("Autoformat output", value=True)
  451. precision = None
  452. if not select_autoformat:
  453. precision = col2.slider("Precision", min_value=0, max_value=7, value = 4)
  454. precision = '0.'+str(precision)+'f'
  455. Q0, sigmaQ0, QL, sigmaQL, circle_params, fl, fitted_mag_s = calc_function(
  456. f_cut, r_cut, i_cut, check_coupling_loss)
  457. if Q0 <= 0 or QL <= 0:
  458. st.write("Negative Q detected, fitting may be inaccurate!")
  459. if select_autoformat:
  460. st.latex(
  461. r'Q_0 =' +
  462. f'{sigfig.round(Q0, uncertainty=sigmaQ0, style="PDG")}, '
  463. + r'\;\;\varepsilon_{Q_0} =' +
  464. f'{sigfig.round(sigmaQ0 / Q0, sigfigs=1, style="PDG")}')
  465. st.latex(
  466. r'Q_L =' +
  467. f'{sigfig.round(QL, uncertainty=sigmaQL, style="PDG")}, '
  468. + r'\;\;\varepsilon_{Q_L} =' +
  469. f'{sigfig.round(sigmaQL / QL, sigfigs=1, style="PDG")}')
  470. else:
  471. st.latex(
  472. r'Q_0 =' +
  473. f'{format(Q0, precision)} \pm ' + f'{format(sigmaQ0, precision)}, '
  474. + r'\;\;\varepsilon_{Q_0} =' +
  475. f'{format(sigmaQ0 / Q0, precision)}')
  476. st.latex(
  477. r'Q_L =' +
  478. f'{format(QL, precision)} \pm ' + f'{format(sigmaQL, precision)}, '
  479. + r'\;\;\varepsilon_{Q_L} =' +
  480. f'{format(sigmaQL / QL, precision)}')
  481. st.latex(r'f_L ='+f'{fl}'+'Hz')
  482. with st.expander("Show static abs(S) plot"):
  483. plot_abs_vs_f(f_cut, r_cut, i_cut, fitted_mag_s)
  484. plot_smith(r, i, circle_params, r_cut, i_cut, st.checkbox("Show excluded points", value=True))