front.py 21 KB

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