front.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import math
  2. import streamlit as st
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. XLIM = [-1.1, 1.1]
  6. YLIM = [-1.1, 1.1]
  7. def round_up(x, n=7):
  8. if x == 0:
  9. return 0
  10. deg = math.floor(math.log(abs(x), 10))
  11. return (10 ** deg) * round(x / (10 ** deg), n - 1)
  12. def circle(ax, x, y, radius, color='#1946BA'):
  13. from matplotlib.patches import Ellipse
  14. drawn_circle = Ellipse((x, y), radius * 2, radius * 2, clip_on=False,
  15. zorder=2, linewidth=2, edgecolor=color, facecolor=(0, 0, 0, .0125))
  16. ax.add_artist(drawn_circle)
  17. def plot_data(r, i, g):
  18. fig = plt.figure(figsize=(10, 10))
  19. ax = fig.add_subplot()
  20. major_ticks = np.arange(-1.0, 1.1, 0.25)
  21. minor_ticks = np.arange(-1.1, 1.1, 0.05)
  22. ax.set_xticks(major_ticks)
  23. ax.set_xticks(minor_ticks, minor=True)
  24. ax.set_yticks(major_ticks)
  25. ax.set_yticks(minor_ticks, minor=True)
  26. ax.grid(which='major', color='grey', linewidth=1.5)
  27. ax.grid(which='minor', color='grey', linewidth=0.5, linestyle=':')
  28. plt.xlabel(r'$Re(\Gamma)$', color='gray', fontsize=16, fontname="Cambria")
  29. plt.ylabel('$Im(\Gamma)$', color='gray', fontsize=16, fontname="Cambria")
  30. plt.title('Smith chart', fontsize=24, fontname="Cambria")
  31. # circle approximation
  32. radius = abs(g[1] - g[0] / g[2]) / 2
  33. x = ((g[1] + g[0] / g[2]) / 2).real
  34. y = ((g[1] + g[0] / g[2]) / 2).imag
  35. circle(ax, x, y, radius, color='#FF8400')
  36. #
  37. # unit circle
  38. circle(ax, 0, 0, 1)
  39. #
  40. # data
  41. ax.plot(r, i, '+', ms=10, mew=2, color='#1946BA')
  42. #
  43. ax.set_xlim(XLIM)
  44. ax.set_ylim(YLIM)
  45. st.pyplot(fig)
  46. from streamlit_echarts import st_echarts, JsCode
  47. interval_range = (0,100)
  48. interval_start,interval_end=0,0
  49. def plot_interact_abs_from_f(f,r,i):
  50. abs_S = list((r[n] ** 2 + i[n] ** 2)**0.5 for n in range(len(r)))
  51. global interval_range,interval_start,interval_end
  52. # echarts for datazoom https://discuss.streamlit.io/t/streamlit-echarts/3655
  53. # datazoom https://echarts.apache.org/examples/en/editor.html?c=line-draggable&lang=ts
  54. # axis pointer values https://echarts.apache.org/en/option.html#axisPointer
  55. options = {
  56. "xAxis": {
  57. "type": "category",
  58. "data": f,
  59. },
  60. "yAxis": {
  61. "type": "value",
  62. "name":"abs(S)",
  63. },
  64. "series": [{"data": abs_S, "type": "line", "name":"abs(S)"}],
  65. "dataZoom": [{"type": "slider", "start": 0, "end": 100}],
  66. "tooltip": {
  67. "trigger":"axis",
  68. "axisPointer": {
  69. "type": 'cross',
  70. # "label": {
  71. # "show":"true",
  72. # "formatter": JsCode(
  73. # "function(info){return info.value;};"
  74. # ).js_code
  75. # }
  76. }
  77. },
  78. "toolbox":{
  79. "feature": {
  80. "dataView": { "show": "true", "readOnly": "true" },
  81. "restore": { "show": "true" },
  82. }
  83. },
  84. }
  85. events = {
  86. "dataZoom": "function(params) { return [params.start, params.end] }",
  87. }
  88. interval_range = st_echarts(
  89. options=options, events=events, height="500px", key="render_basic_bar_events"
  90. )
  91. if interval_range is None:
  92. interval_range = (0, 100)
  93. n=len(f)
  94. interval_start,interval_end=(int(n*interval_range[id]*0.01) for id in (0,1))
  95. def plot_ref_from_f(f, r, i):
  96. fig = plt.figure(figsize=(10, 10))
  97. abs_S = list((r[n] ** 2 + i[n] ** 2)**0.5 for n in range(len(r)))
  98. xlim = [min(f) - abs(max(f) - min(f)) * 0.1, max(f) + abs(max(f) - min(f)) * 0.1]
  99. ylim = [min(abs_S) - abs(max(abs_S) - min(abs_S)) * 0.5, max(abs_S) + abs(max(abs_S) - min(abs_S)) * 0.5]
  100. ax = fig.add_subplot()
  101. ax.set_xlim(xlim)
  102. ax.set_ylim(ylim)
  103. ax.grid(which='major', color='k', linewidth=1)
  104. ax.grid(which='minor', color='grey', linestyle=':', linewidth=0.5)
  105. plt.xlabel(r'$f,\; 1/c$', color='gray', fontsize=16, fontname="Cambria")
  106. plt.ylabel('$|\Gamma|$', color='gray', fontsize=16, fontname="Cambria")
  107. plt.title('Modulus of reflection coefficient from frequency', fontsize=24, fontname="Cambria")
  108. ax.plot(f, abs_S, '+', ms=10, mew=2, color='#1946BA')
  109. st.pyplot(fig)
  110. def run(calc_function):
  111. global interval_range,interval_start, interval_end
  112. data = []
  113. uploaded_file = st.file_uploader('Upload a csv')
  114. if uploaded_file is not None:
  115. data = uploaded_file.readlines()
  116. col1, col2 = st.columns(2)
  117. select_data_format = col1.selectbox('Choose data format from a list',
  118. ['Frequency, Re(S11), Im(S11)', 'Frequency, Re(Zin), Im(Zin)'])
  119. select_separator = col2.selectbox('Choose separator', ['" "', '","', '";"'])
  120. select_coupling_losses = st.checkbox('Apply corrections for coupling losses (lossy coupling)')
  121. def is_float(element) -> bool:
  122. try:
  123. float(element)
  124. val = float(element)
  125. if math.isnan(val) or math.isinf(val):
  126. raise ValueError
  127. return True
  128. except ValueError:
  129. return False
  130. def unpack_data(data):
  131. nonlocal select_separator
  132. nonlocal select_data_format
  133. f, r, i = [], [], []
  134. if select_data_format == 'Frequency, Re(S11), Im(S11)':
  135. for x in range(len(data)):
  136. # print(select_separator)
  137. select_separator = select_separator.replace('\"', '')
  138. if type(data[x])==bytes:
  139. # print('f')
  140. try:
  141. data[x]=data[x].decode('utf-8-sig', 'ignore')
  142. except:
  143. return f, r, i, 'Not an utf-8-sig line №: ' + str(x)
  144. if select_separator == " ":
  145. tru = data[x].split()
  146. else:
  147. data[x] = data[x].replace(select_separator, ' ')
  148. tru = data[x].split()
  149. if len(tru) != 3:
  150. return f, r, i, 'Can\'t parse line №: ' + str(x)
  151. a, b, c = (y for y in tru)
  152. if not ((is_float(a)) or (is_float(b)) or (is_float(c))):
  153. return f, r, i, 'Your data isn\'t numerical type. Error on line: ' + str(x)
  154. f.append(float(a)) # frequency
  155. r.append(float(b)) # Re of S11
  156. i.append(float(c)) # Im of S11
  157. else:
  158. return f, r, i, 'Wrong data format'
  159. return f, r, i, 'data parsed'
  160. validator_status = '...'
  161. # calculate
  162. circle_params = []
  163. if len(data) > 0:
  164. f, r, i, validator_status = unpack_data(data)
  165. plot_interact_abs_from_f(f, r, i)
  166. f_cut=f[interval_start:interval_end]
  167. r_cut=r[interval_start:interval_end]
  168. i_cut=i[interval_start:interval_end]
  169. if validator_status == 'data parsed':
  170. Q0, sigmaQ0, QL, sigmaQl, circle_params = calc_function(f_cut, r_cut, i_cut, select_coupling_losses)
  171. # Q0 = round_up(Q0)
  172. # sigmaQ0 = round_up(sigmaQ0)
  173. # QL = round_up(QL)
  174. # sigmaQl = round_up(sigmaQl)
  175. if select_coupling_losses:
  176. st.write("Lossy coupling")
  177. else:
  178. st.write("Cable attenuation")
  179. out_precision='0.7f'
  180. st.latex(r'Q_0 =' + f'{format(Q0, out_precision)} \pm {format(sigmaQ0, out_precision)}, ' +
  181. r'\;\;\varepsilon_{Q_0} =' + f'{format(sigmaQ0 / Q0, out_precision)}')
  182. st.latex(r'Q_L =' + f'{format(QL, out_precision)} \pm {format(sigmaQl, out_precision)}, ' +
  183. r'\;\;\varepsilon_{Q_L} =' + f'{format(sigmaQl / QL, out_precision)}')
  184. st.write("Status: " + validator_status)
  185. if len(data) > 0:
  186. f, r, i, validator_status = unpack_data(data)
  187. if validator_status == 'data parsed':
  188. plot_ref_from_f(f_cut, r_cut, i_cut)
  189. plot_data(r_cut, i_cut, circle_params)