front.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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):
  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. # radius = abs(g[1] - g[0] / g[2]) / 2
  131. # x = ((g[1] + g[0] / g[2]) / 2).real
  132. # y = ((g[1] + g[0] / g[2]) / 2).imag
  133. st.pyplot(fig)
  134. def run(calc_function):
  135. def is_float(element) -> bool:
  136. try:
  137. float(element)
  138. val = float(element)
  139. if math.isnan(val) or math.isinf(val):
  140. raise ValueError
  141. return True
  142. except ValueError:
  143. return False
  144. # to utf-8
  145. def read_data(data):
  146. for x in range(len(data)):
  147. if type(data[x]) == bytes:
  148. try:
  149. data[x] = data[x].decode('utf-8-sig', 'ignore')
  150. except:
  151. return 'Not an utf-8-sig line №: ' + str(x)
  152. return 'data read, but not parsed'
  153. # for Touchstone .snp format
  154. def parse_heading(data):
  155. nonlocal data_format_snp
  156. if data_format_snp:
  157. for x in range(len(data)):
  158. if data[x][0] == '#':
  159. line = data[x].split()
  160. if len(line) == 6:
  161. repr_map = {"RI": 0, "MA": 1, "DB": 2}
  162. para_map = {"S": 0, "Z": 1}
  163. hz_map = {"GHz": 10**9, "MHz": 10 **6, "KHz": 10**3, "Hz": 1}
  164. hz, measurement_parameter, data_representation, _r, ref_resistance = line[1:]
  165. try:
  166. return hz_map[hz], para_map[measurement_parameter], repr_map[data_representation], int(ref_resistance)
  167. except:
  168. break
  169. break
  170. return 1, 0, 0, 50
  171. # check if line has comments
  172. # first is a comment line according to .snp documentation,
  173. # others detects comments in various languages
  174. def check_line_comments(line):
  175. if len(line) < 2 or line[0] == '!' or line[0] == '#' or line[0] == '%' or line[0] == '/':
  176. return None
  177. else:
  178. # generally we expect these chars as separators
  179. line = line.replace(';', ' ').replace(',', ' ')
  180. if '!' in line:
  181. line = line[:line.find('!')]
  182. return line
  183. # unpack a few first lines of the file to get number of ports
  184. def count_columns(data):
  185. return_status = 'data parsed'
  186. column_count = 0
  187. for x in range(len(data)):
  188. line = check_line_comments(data[x])
  189. if line is None:
  190. continue
  191. line = line.split()
  192. # always at least 3 values for single data point
  193. if len(line) < 3:
  194. return_status = 'Can\'t parse line № ' + \
  195. str(x) + ',\n not enough arguments (less than 3)'
  196. break
  197. column_count = len(line)
  198. break
  199. return column_count, return_status
  200. def prepare_snp(data, number):
  201. prepared_data = []
  202. return_status = 'data read, but not parsed'
  203. for x in range(len(data)):
  204. line = check_line_comments(data[x])
  205. if line is None:
  206. continue
  207. splitted_line = line.split()
  208. if number * 2 + 1 == len(splitted_line):
  209. prepared_data.append(line)
  210. elif number * 2 == len(splitted_line):
  211. prepared_data[-1] += line
  212. else:
  213. return_status = "Parsing error for .snp format on line №" + str(x)
  214. return prepared_data, return_status
  215. def unpack_data(data, first_column, column_count, ref_resistance, ace_preview_markers):
  216. nonlocal select_measurement_parameter
  217. nonlocal select_data_representation
  218. f, r, i = [], [], []
  219. return_status = 'data parsed'
  220. for x in range(len(data)):
  221. line = check_line_comments(data[x])
  222. if line is None:
  223. continue
  224. line = line.split()
  225. if column_count != len(line):
  226. return_status = "Wrong number of parameters on line № " + str(x)
  227. break
  228. # 1: process according to data_placement
  229. a, b, c = None, None, None
  230. try:
  231. a = line[0]
  232. b = line[first_column]
  233. c = line[first_column+1]
  234. except:
  235. return_status = 'Can\'t parse line №: ' + \
  236. str(x) + ',\n not enough arguments'
  237. break
  238. if not ((is_float(a)) or (is_float(b)) or (is_float(c))):
  239. return_status = 'Wrong data type, expected number. Error on line: ' + \
  240. str(x)
  241. break
  242. # mark as processed
  243. for y in (a,b,c):
  244. ace_preview_markers.append(
  245. {"startRow": x,"startCol": 0,
  246. "endRow": x,"endCol": data[x].find(y)+len(y),
  247. "className": "ace_stack","type": "text"})
  248. a, b, c = (float(x) for x in (a, b, c))
  249. f.append(a) # frequency
  250. # 2: process according to data_representation
  251. if select_data_representation == 'Frequency, real, imaginary':
  252. # std format
  253. r.append(b) # Re
  254. i.append(c) # Im
  255. elif select_data_representation == 'Frequency, magnitude, angle':
  256. r.append(b*np.cos(np.deg2rad(c)))
  257. i.append(b*np.sin(np.deg2rad(c)))
  258. elif select_data_representation == 'Frequency, db, angle':
  259. b = 10**(b/20)
  260. r.append(b*np.cos(np.deg2rad(c)))
  261. i.append(b*np.sin(np.deg2rad(c)))
  262. else:
  263. return_status = 'Wrong data format'
  264. break
  265. # 3: process according to measurement_parameter
  266. if select_measurement_parameter == 'Z':
  267. # normalization
  268. r[-1] = r[-1]/ref_resistance
  269. i[-1] = i[-1]/ref_resistance
  270. # translate to S
  271. try:
  272. # center_x + 1j*center_y, radius
  273. p1, r1 = r[-1] / (1 + r[-1]) + 0j, 1 / (1 + r[-1]) #real
  274. p2, r2 = 1 + 1j * (1 / i[-1]), 1 / i[-1] #imag
  275. d = abs(p2-p1)
  276. q = (r1**2 - r2**2 + d**2) / (2 * d)
  277. h = (r1**2 - q**2)**0.5
  278. p = p1 + q * (p2 - p1) / d
  279. intersect = [
  280. (p.real + h * (p2.imag - p1.imag) / d,
  281. p.imag - h * (p2.real - p1.real) / d),
  282. (p.real - h * (p2.imag - p1.imag) / d,
  283. p.imag + h * (p2.real - p1.real) / d)]
  284. intersect = [x+1j*y for x,y in intersect]
  285. intersect_shift = [p-(1+0j) for p in intersect]
  286. intersect_shift = abs(np.array(intersect_shift))
  287. p=intersect[0]
  288. if intersect_shift[0]<intersect_shift[1]:
  289. p=intersect[1]
  290. r[-1] = p.real
  291. i[-1] = p.imag
  292. except:
  293. r.pop()
  294. i.pop()
  295. f.pop()
  296. if len(f) < 3 or len(f) != len(r) or len(f) != len(i):
  297. return_status = 'Choosen data range is too small, add more points'
  298. elif max(abs(np.array(r)+ 1j* np.array(i))) > 2:
  299. return_status = 'Your data points have an abnormality:\
  300. they are too far outside the unit cirlce.\
  301. Make sure the format is correct'
  302. return f, r, i, return_status
  303. # make accessible a specific range of numerical data choosen with interactive plot
  304. # percent, line id, line id
  305. interval_range, interval_start, interval_end = None, None, None
  306. # info
  307. with st.expander("Info"):
  308. # streamlit.markdown does not support footnotes
  309. try:
  310. with open('./source/frontend/info.md') as f:
  311. st.markdown(f.read())
  312. except:
  313. st.write('Wrong start directory, see readme')
  314. # file upload button
  315. uploaded_file = st.file_uploader('Upload a file from your vector analizer. \
  316. Make sure the file format is .snp or it has a similar inner structure.' )
  317. # check .snp
  318. data_format_snp = False
  319. data_format_snp_number = 0
  320. if uploaded_file is None:
  321. st.write("DEMO: ")
  322. # display DEMO
  323. data_format_snp = True
  324. try:
  325. with open('./resource/data/8_default_demo.s1p') as f:
  326. data = f.readlines()
  327. except:
  328. # 'streamlit run' call in the wrong directory. Display smaller demo:
  329. data =['# Hz S MA R 50\n\
  330. 11415403125 0.37010744 92.47802\n\
  331. 11416090625 0.33831283 92.906929\n\
  332. 11416778125 0.3069371 94.03318']
  333. else:
  334. data = uploaded_file.readlines()
  335. if uploaded_file.name[-4:-2]=='.s' and uploaded_file.name[-1]== 'p':
  336. data_format_snp = True
  337. data_format_snp_number = int(uploaded_file.name[-2])
  338. validator_status = '...'
  339. ace_preview_markers = []
  340. column_count = 0
  341. # data loaded
  342. circle_params = []
  343. if len(data) > 0:
  344. validator_status = read_data(data)
  345. if validator_status == 'data read, but not parsed':
  346. hz, select_measurement_parameter, select_data_representation, input_ref_resistance = parse_heading(data)
  347. col1, col2 = st.columns([1,2])
  348. with col1.expander("Processing options"):
  349. select_measurement_parameter = st.selectbox('Measurement parameter',
  350. ['S', 'Z'],
  351. select_measurement_parameter)
  352. select_data_representation = st.selectbox('Data representation',
  353. ['Frequency, real, imaginary',
  354. 'Frequency, magnitude, angle',
  355. 'Frequency, db, angle'],
  356. select_data_representation)
  357. if select_measurement_parameter=='Z':
  358. input_ref_resistance = st.number_input(
  359. "Reference resistance:", min_value=0, value=input_ref_resistance)
  360. input_start_line = int(st.number_input(
  361. "First line for processing:", min_value=1, max_value=len(data)))
  362. input_end_line = int(st.number_input(
  363. "Last line for processing:", min_value=1, max_value=len(data), value=len(data)))
  364. data = data[input_start_line-1:input_end_line]
  365. # Ace editor to show choosen data columns and rows
  366. with col2.expander("File preview"):
  367. # st.button(copy selection)
  368. # So little 'official' functionality in libs and lack of documentation
  369. # therefore beware: css hacks
  370. # yellow ~ ace_step
  371. # light yellow ~ ace_highlight-marker
  372. # green ~ ace_stack
  373. # red ~ ace_error-marker
  374. # no more good colors included in streamlit_ace for marking
  375. # st.markdown('''<style>
  376. # .choosen_option_1
  377. # {
  378. # color: rgb(49, 51, 63);
  379. # }</style>''', unsafe_allow_html=True)
  380. # markdown injection does not seems to work, since ace is in a different .html accessible via iframe
  381. # markers format:
  382. #[{"startRow": 2,"startCol": 0,"endRow": 2,"endCol": 3,"className": "ace_error-marker","type": "text"}]
  383. # add marking for choosen data lines TODO
  384. ace_preview_markers.append({
  385. "startRow": input_start_line - 1,
  386. "startCol": 0,
  387. "endRow": input_end_line,
  388. "endCol": 0,
  389. "className": "ace_highlight-marker",
  390. "type": "text"
  391. })
  392. ace_text_value = ''.join(data).strip()
  393. st_ace(value=ace_text_value,
  394. readonly=True,
  395. auto_update=True,
  396. placeholder="Your file is empty",
  397. markers=ace_preview_markers,
  398. height="300px")
  399. if data_format_snp and data_format_snp_number >= 3:
  400. data, validator_status = prepare_snp(data, data_format_snp_number)
  401. if validator_status == "data read, but not parsed":
  402. column_count, validator_status = count_columns(data)
  403. f, r, i = [], [], []
  404. if validator_status == "data parsed":
  405. input_ports_pair = 1
  406. if column_count > 3:
  407. pair_count = (column_count - 1) // 2
  408. input_ports_pair_id = st.number_input(
  409. "Choosen pair of ports with network parameters:",
  410. min_value = 1,
  411. max_value = pair_count,
  412. value = 1) - 1
  413. ports_count = round(pair_count **0.5)
  414. st.write(select_measurement_parameter +
  415. str(input_ports_pair_id // ports_count + 1) +
  416. str(input_ports_pair_id % ports_count + 1))
  417. f, r, i, validator_status = unpack_data(
  418. data,(input_ports_pair - 1) * 2 + 1, column_count, input_ref_resistance,
  419. ace_preview_markers)
  420. f = [x * hz for x in f] # to hz
  421. st.write("Use range slider to choose best suitable data interval")
  422. interval_range, interval_start, interval_end = plot_interact_abs_from_f(f, r, i, interval_range)
  423. f_cut, r_cut, i_cut = [], [], []
  424. if validator_status == "data parsed":
  425. f_cut, r_cut, i_cut = (x[interval_start:interval_end]
  426. for x in (f, r, i))
  427. with st.expander("Selected data interval as .s1p"):
  428. st_ace(value="# Hz S RI R 50\n" +
  429. ''.join(f'{f_cut[x]} {r_cut[x]} {i_cut[x]}\n' for x in range(len(f_cut))),
  430. readonly=True,
  431. auto_update=True,
  432. placeholder="Selection is empty",
  433. height="150px")
  434. if len(f_cut) < 3:
  435. validator_status = "Choosen interval is too small, add more points"
  436. st.write("Status: " + validator_status)
  437. if validator_status == "data parsed":
  438. col1, col2 = st.columns(2)
  439. check_coupling_loss = col1.checkbox(
  440. 'Apply correction for coupling loss')
  441. if check_coupling_loss:
  442. col1.write("Option: Lossy coupling")
  443. else:
  444. col1.write("Option: Cable attenuation")
  445. select_autoformat = col2.checkbox("Autoformat output", value=True)
  446. precision = None
  447. if not select_autoformat:
  448. precision = col2.slider("Precision", min_value=0, max_value=7, value = 4)
  449. precision = '0.'+str(precision)+'f'
  450. Q0, sigmaQ0, QL, sigmaQL, circle_params = calc_function(
  451. f_cut, r_cut, i_cut, check_coupling_loss)
  452. if Q0 <= 0 or QL <= 0:
  453. st.write("Negative Q detected, fitting may be inaccurate!")
  454. if select_autoformat:
  455. st.latex(
  456. r'Q_0 =' +
  457. f'{sigfig.round(Q0, uncertainty=sigmaQ0, style="PDG")}, '
  458. + r'\;\;\varepsilon_{Q_0} =' +
  459. f'{sigfig.round(sigmaQ0 / Q0, sigfigs=1, style="PDG")}')
  460. st.latex(
  461. r'Q_L =' +
  462. f'{sigfig.round(QL, uncertainty=sigmaQL, style="PDG")}, '
  463. + r'\;\;\varepsilon_{Q_L} =' +
  464. f'{sigfig.round(sigmaQL / QL, sigfigs=1, style="PDG")}')
  465. else:
  466. st.latex(
  467. r'Q_0 =' +
  468. f'{format(Q0, precision)} \pm ' + f'{format(sigmaQ0, precision)}, '
  469. + r'\;\;\varepsilon_{Q_0} =' +
  470. f'{format(sigmaQ0 / Q0, precision)}')
  471. st.latex(
  472. r'Q_L =' +
  473. f'{format(QL, precision)} \pm ' + f'{format(sigmaQL, precision)}, '
  474. + r'\;\;\varepsilon_{Q_L} =' +
  475. f'{format(sigmaQL / QL, precision)}')
  476. with st.expander("Show static abs(S) plot"):
  477. plot_abs_vs_f(f_cut, r_cut, i_cut)
  478. plot_smith(r, i, circle_params, r_cut, i_cut, st.checkbox("Show excluded points", value=True))