front.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. ax.set_xlim(XLIM)
  21. ax.set_ylim(YLIM)
  22. major_ticks = np.arange(-1.0, 1.1, 0.25)
  23. minor_ticks = np.arange(-1.1, 1.1, 0.05)
  24. ax.set_xticks(major_ticks)
  25. ax.set_xticks(minor_ticks, minor=True)
  26. ax.set_yticks(major_ticks)
  27. ax.set_yticks(minor_ticks, minor=True)
  28. ax.grid(which='major', color='grey', linewidth=1.5)
  29. ax.grid(which='minor', color='grey', linewidth=0.5, linestyle=':')
  30. plt.xlabel(r'$Re(\Gamma)$', color='gray', fontsize=16, fontname="Cambria")
  31. plt.ylabel('$Im(\Gamma)$', color='gray', fontsize=16, fontname="Cambria")
  32. plt.title('Smith chart', fontsize=24, fontname="Cambria")
  33. # circle approximation
  34. radius = abs(g[1] - g[0] / g[2]) / 2
  35. x = ((g[1] + g[0] / g[2]) / 2).real
  36. y = ((g[1] + g[0] / g[2]) / 2).imag
  37. circle(ax, x, y, radius, color='#FF8400')
  38. #
  39. # unit circle
  40. circle(ax, 0, 0, 1)
  41. #
  42. # data
  43. ax.plot(r, i, '+', ms=10, mew=2, color='#1946BA')
  44. #
  45. st.pyplot(fig)
  46. def plot_ref_from_f(r, i, f):
  47. fig = plt.figure(figsize=(10, 10))
  48. abs_S = list(math.sqrt(r[n] ** 2 + i[n] ** 2) for n in range(len(r)))
  49. xlim = [min(f) - abs(max(f) - min(f)) * 0.1, max(f) + abs(max(f) - min(f)) * 0.1]
  50. 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]
  51. ax = fig.add_subplot()
  52. ax.set_xlim(xlim)
  53. ax.set_ylim(ylim)
  54. ax.grid(which='major', color='k', linewidth=1)
  55. ax.grid(which='minor', color='grey', linestyle=':', linewidth=0.5)
  56. plt.xlabel(r'$f,\; 1/c$', color='gray', fontsize=16, fontname="Cambria")
  57. plt.ylabel('$|\Gamma|$', color='gray', fontsize=16, fontname="Cambria")
  58. plt.title('Modulus of reflection coefficient from frequency', fontsize=24, fontname="Cambria")
  59. ax.plot(f, abs_S, '+', ms=10, mew=2, color='#1946BA')
  60. st.pyplot(fig)
  61. def run(calc_function):
  62. data = []
  63. uploaded_file = st.file_uploader('Upload a csv')
  64. if uploaded_file is not None:
  65. data = uploaded_file.readlines()
  66. col1, col2 = st.columns(2)
  67. select_data_format = col1.selectbox('Choose data format from a list',
  68. ['Frequency, Re(S11), Im(S11)', 'Frequency, Re(Zin), Im(Zin)'])
  69. select_separator = col2.selectbox('Choose separator', ['" "', '","', '";"'])
  70. select_coupling_losses = st.checkbox('Apply corrections for coupling losses (lossy coupling)')
  71. def is_float(element) -> bool:
  72. try:
  73. float(element)
  74. val = float(element)
  75. if math.isnan(val) or math.isinf(val):
  76. raise ValueError
  77. return True
  78. except ValueError:
  79. return False
  80. def unpack_data(data):
  81. nonlocal select_separator
  82. nonlocal select_data_format
  83. f, r, i = [], [], []
  84. if select_data_format == 'Frequency, Re(S11), Im(S11)':
  85. for x in range(len(data)):
  86. # print(select_separator)
  87. select_separator = select_separator.replace('\"', '')
  88. if type(data[x])==bytes:
  89. data[x]=data[x].decode()
  90. if select_separator == " ":
  91. tru = data[x].split()
  92. else:
  93. data[x] = data[x].replace(select_separator, ' ')
  94. tru = data[x].split()
  95. if len(tru) != 3:
  96. return f, r, i, 'Bad line in your file. №:' + str(x)
  97. a, b, c = (y for y in tru)
  98. if not ((is_float(a)) or (is_float(b)) or (is_float(c))):
  99. return f, r, i, 'Bad data. Your data isn\'t numerical type. Number of bad line:' + str(x)
  100. f.append(float(a)) # frequency
  101. r.append(float(b)) # Re of S11
  102. i.append(float(c)) # Im of S11
  103. else:
  104. return f, r, i, 'Bad data format'
  105. return f, r, i, 'very nice'
  106. validator_status = 'nice'
  107. # calculate
  108. circle_params = []
  109. if len(data) > 0:
  110. f, r, i, validator_status = unpack_data(data)
  111. if validator_status == 'very nice':
  112. Q0, sigmaQ0, QL, sigmaQl, circle_params = calc_function(f, r, i)
  113. Q0 = round_up(Q0)
  114. sigmaQ0 = round_up(sigmaQ0)
  115. QL = round_up(QL)
  116. sigmaQl = round_up(sigmaQl)
  117. st.write("Cable attenuation")
  118. st.latex(r'Q_0 =' + f'{Q0} \pm {sigmaQ0}, ' + r'\;\;\varepsilon_{Q_0} =' + f'{round_up(sigmaQ0 / Q0)}')
  119. st.latex(r'Q_L =' + f'{QL} \pm {sigmaQl}, ' + r'\;\;\varepsilon_{Q_L} =' + f'{round_up(sigmaQl / QL)}')
  120. st.write("Status: " + validator_status)
  121. if len(data) > 0:
  122. f, r, i, validator_status = unpack_data(data)
  123. if validator_status == 'very nice':
  124. plot_data(r, i, circle_params)
  125. plot_ref_from_f(r, i, f)