Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

from math import atan,log10,pi import matplotlib.pyplot as plt from openpyxl import…

  1. User

    from math import atan,log10,pi import matplotlib.pyplot as plt from openpyxl import Workbook from openpyxl.styles import Font, Alignment, Border, Side from openpyxl.utils import get_column_letter

    исходные данные

    f = 1300 hr = 40 hbs1 = 49 hbs2 = 35 hms = 1.7 fi = 30

    константы

    w = 15 b = 40

    Модель Уолфиша-Икегами

    def los(f, d): return(42.6 + 26 * log10(d) + 20 * log10(f))

    def nlos(f, d, hms, hbs, kf, hr, fi): delta_hms = hr - hms delta_hbs = hbs - hr kd = 18 if hbs >= hr else 18 - 15 * delta_hbs / hr ka = (54 if hbs > hr else 54 - 0.8 * delta_hbs if d >= 0.5 else 54 - 1.5 * delta_hbs * d) Lbsh = -18 * log10(1 + delta_hbs) if hbs > hr else 0 Lmsd = Lbsh + ka + kd * log10(d) + kf * log10(f) - 9 * log10(b) Lori = ( -10 + 0.354 * w if 0 <= fi < 35 else 2.5 + 0.075 * (fi - 35) if 35 <= fi < 55 else 4.0 + 0.114 * (fi - 55) if 55 <= fi <= 90 else 0 ) Lrts = -16.9 - 10 * log10(w) + 10 * log10(f) + 20 * log10(delta_hms) + Lori Lo = 32.44 + 20 * log10(d) + 20 * log10(f) Lnlos = Lo + max(0, Lrts + Lmsd) return Lnlos

    Модель Кся-Бертони

    def bertoni(f, d, hms, hbs, w, b): c = 3e8 lam = c / f delta_hbs = hr - hbs delta_hms = hms - hr x = w / 2 teta = atan(delta_hms / x) r=((delta_hms2)+(x2))**0.5 Ldb= -10 * ((log10(lam / ((4 * pi) * d))) ** 2) - 10 * log10((lam / ((4 * (pi) ** 2) * r)) * (((1 / teta) - (1 / ((2 * pi) + teta))) ** 2)) - 10 * log10((2.35 ** 2) * (((delta_hbs / d) * ((b / lam) ** 0.5)) ** 1.8)) return Ldb

    meters=list(range(200,1600,100))

    los_set, nlos_hbs1_middletown, nlos_hbs1_largetown, nlos_hbs2_middletown, nlos_hbs2_largetown, bertoni_hbs1=[],[],[],[],[],[]

    for el in meters: los_set.append(los(f, el)) nlos_hbs1_middletown.append(nlos(f, el, hms, hbs1, (-4+(0.7*((f/925))-1)), hr, fi)) nlos_hbs1_largetown.append(nlos(f, el, hms, hbs1, (-4+(1.5*((f/925))-1)), hr, fi)) nlos_hbs2_middletown.append(nlos(f, el, hms, hbs2, (-4+(0.7*((f/925))-1)), hr, fi)) nlos_hbs2_largetown.append(nlos(f, el, hms, hbs2, (-4+(1.5*((f/925))-1)), hr, fi)) bertoni_hbs1.append(bertoni(f, el, hms, hbs2, w, b))

    def plot(): plt.figure(figsize=(8, 7)) plt.plot(meters,los_set,meters,nlos_hbs1_middletown,meters,nlos_hbs1_largetown,meters,nlos_hbs2_middletown,meters,nlos_hbs2_largetown,meters,bertoni_hbs1) plt.grid(True) plt.gca().legend(('зона прямой видимости', 'вне зоны прямой видимости, высота {} м, город средних размеров'.format(hbs1), 'вне зоны прямой видимости, высота {} м, город с плотной застройкой'.format(hbs1), 'вне зоны прямой видимости, высота {} м, город средних размеров'.format(hbs2), 'вне зоны прямой видимости, высота {} м, город с плотной застройкой'.format(hbs2), 'Модель Кся-Бертони. Высота м'),loc="lower center",bbox_to_anchor=(0.5, -0.4)) plt.xlim(200,1500) plt.xticks(meters) plt.xlabel("расстояние x, м") plt.ylabel("L (потери сигнала), дБ") plt.title("Модели Уолфиша-Икегами и Кся-Бертони") plt.subplots_adjust(bottom=0.262,top=0.934) plt.show()

    def toFixed(numObj, digits=3): return float(f"{numObj:.{digits}f}")

    def save_to_xlsx(filename="pract3.xlsx"): workbook = Workbook() sheet = workbook.active sheet.title = "Потери сигнала"

    headers = [
        "Расстояние (м)", 
        "Зона прямой видимости", 
        'Вне зоны, {} м, средний город'.format(hbs1), 
        "Вне зоны, {} м, плотная застройка".format(hbs1), 
        "Вне зоны, {} м, средний город".format(hbs2), 
        "Вне зоны, {} м, плотная застройка".format(hbs2), 
        "Модель Кся-Бертони"
    ]
    sheet.append(headers)
    
    for i in range(len(meters)):
        sheet.append([
            meters[i],
            toFixed(los_set[i]),
            toFixed(nlos_hbs1_middletown[i]),
            toFixed(nlos_hbs1_largetown[i]),
            toFixed(nlos_hbs2_middletown[i]),
            toFixed(nlos_hbs2_largetown[i]),
            toFixed(bertoni_hbs1[i])
        ])
    
    for column_cells in sheet.columns:
        max_length = 0
        column = column_cells[0].column
        for cell in column_cells:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(cell.value)
            except:
                pass
        adjusted_width = (max_length + 2)
        sheet.column_dimensions[get_column_letter(column)].width = adjusted_width
    
    thin_border = Border(
        left=Side(style='thin'),
        right=Side(style='thin'),
        top=Side(style='thin'),
        bottom=Side(style='thin')
    )
    
    for row in sheet.iter_rows():
        for cell in row:
            cell.alignment = Alignment(horizontal="center", vertical="center")
            cell.border = thin_border
    
    for cell in sheet[1]:
        cell.font = Font(bold=True)
    
    workbook.save(filename)
    

    plot() save_to_xlsx()

    Добавь красивый интерфейс к программе с помощью customtkinter. Чтобы можно было вводить исходные данные. Добавь кнопки рисования графика и сохранения расчета в файл.

  2. Assistant

    To create a user-friendly interface for your signal loss modeling program, we'll use customtkinter, a modern and customizable version of the standard tkinter library. The GUI will allow users to input the necessary parameters, plot the graph, and save the results to an Excel file with the click of a button.

    Here's a step-by-step guide along with the complete code:

    1. Install Required Libraries

      Ensure you have the necessary libraries installed. You can install any missing libraries using pip:

      pip install customtkinter matplotlib openpyxl
      
    2. Understanding the GUI Components

      • Input Fields: Users can input the following parameters:
        • Frequency (f)
        • Receiver height (hr)
        • Base station heights (hbs1 and hbs2)
        • Mobile station height (hms)
        • Incident angle (fi)
        • w (constant)
        • b (constant)
      • Buttons:
        • Plot Graph: Generates and displays the plot based on input parameters.
        • Save to Excel: Saves the calculated data to an Excel file.
      • Validation: Ensures that users enter valid numerical values.
    3. Complete Code with customtkinter Interface

      import customtkinter as ctk
      from math import atan, log10, pi
      import matplotlib.pyplot as plt
      from openpyxl import Workbook
      from openpyxl.styles import Font, Alignment, Border, Side
      from openpyxl.utils import get_column_letter
      from tkinter import messagebox
      
      # Initialize appearance
      ctk.set_appearance_mode("System")  # Modes: "System" (default), "Dark", "Light"
      ctk.set_default_color_theme("blue")  # Themes: "blue" (default), "green", "dark-blue"
      
      class SignalLossApp(ctk.CTk):
          def __init__(self):
              super().__init__()
              self.title("Signal Loss Modeling")
              self.geometry("600x500")
              self.resizable(False, False)
      
              # Create frames
              self.input_frame = ctk.CTkFrame(self, padding=20)
              self.input_frame.pack(pady=10, fill="x", expand=True)
      
              self.button_frame = ctk.CTkFrame(self, padding=20)
              self.button_frame.pack(pady=10, fill="x", expand=True)
      
              # Input fields
              self.inputs = {}
              input_labels = [
                  ("Frequency (Hz)", "f", 1300),
                  ("Receiver Height (m)", "hr", 40),
                  ("Base Station Height 1 (m)", "hbs1", 49),
                  ("Base Station Height 2 (m)", "hbs2", 35),
                  ("Mobile Station Height (m)", "hms", 1.7),
                  ("Incident Angle (degrees)", "fi", 30),
                  ("w (constant)", "w", 15),
                  ("b (constant)", "b", 40),
              ]
      
              for i, (label, key, default) in enumerate(input_labels):
                  row = i // 2
                  col = i % 2
                  l = ctk.CTkLabel(self.input_frame, text=label)
                  l.grid(row=i, column=0, padx=5, pady=5, sticky="w")
                  entry = ctk.CTkEntry(self.input_frame)
                  entry.insert(0, str(default))
                  entry.grid(row=i, column=1, padx=5, pady=5, sticky="ew")
                  self.inputs[key] = entry
      
              # Configure grid weights
              self.input_frame.columnconfigure(0, weight=1)
              self.input_frame.columnconfigure(1, weight=2)
      
              # Buttons
              plot_button = ctk.CTkButton(self.button_frame, text="Plot Graph", command=self.plot)
              plot_button.pack(side="left", padx=20, pady=10, fill="x", expand=True)
      
              save_button = ctk.CTkButton(self.button_frame, text="Save to Excel", command=self.save_to_xlsx)
              save_button.pack(side="right", padx=20, pady=10, fill="x", expand=True)
      
          def get_inputs(self):
              try:
                  f = float(self.inputs["f"].get())
                  hr = float(self.inputs["hr"].get())
                  hbs1 = float(self.inputs["hbs1"].get())
                  hbs2 = float(self.inputs["hbs2"].get())
                  hms = float(self.inputs["hms"].get())
                  fi = float(self.inputs["fi"].get())
                  w = float(self.inputs["w"].get())
                  b = float(self.inputs["b"].get())
                  return f, hr, hbs1, hbs2, hms, fi, w, b
              except ValueError:
                  messagebox.showerror("Input Error", "Please enter valid numerical values.")
                  return None
      
          # Signal Loss Models
          def los(self, f, d):
              return 42.6 + 26 * log10(d) + 20 * log10(f)
      
          def nlos(self, f, d, hms, hbs, kf, hr, fi):
              delta_hms = hr - hms
              delta_hbs = hbs - hr
              kd = 18 if hbs >= hr else 18 - 15 * delta_hbs / hr
              if hbs > hr:
                  Lbsh = -18 * log10(1 + delta_hbs)
              else:
                  Lbsh = 0
              if d >= 0.5:
                  ka = 54 if hbs > hr else 54 - 0.8 * delta_hbs
              else:
                  ka = 54 if hbs > hr else 54 - 1.5 * delta_hbs * d
              Lmsd = Lbsh + ka + kd * log10(d) + kf * log10(f) - 9 * log10(b)
              if 0 <= fi < 35:
                  Lori = -10 + 0.354 * w
              elif 35 <= fi < 55:
                  Lori = 2.5 + 0.075 * (fi - 35)
              elif 55 <= fi <= 90:
                  Lori = 4.0 + 0.114 * (fi - 55)
              else:
                  Lori = 0
              delta_hms_nonzero = max(delta_hms, 1e-6)  # Prevent log10(0)
              Lrts = -16.9 - 10 * log10(w) + 10 * log10(f) + 20 * log10(delta_hms_nonzero) + Lori
              Lo = 32.44 + 20 * log10(d) + 20 * log10(f)
              Lnlos = Lo + max(0, Lrts + Lmsd)
              return Lnlos
      
          def bertoni(self, f, d, hms, hbs, w, b):
              c = 3e8
              lam = c / f
              delta_hbs = hr - hbs
              delta_hms = hms - hr
              x = w / 2
              teta = atan(delta_hms / x)
              r = ((delta_hms ** 2) + (x ** 2)) ** 0.5
              try:
                  Ldb = -10 * ((log10(lam / ((4 * pi) * d))) ** 2)
                  Ldb += -10 * log10((lam / ((4 * (pi) ** 2) * r)) * (((1 / teta) - (1 / ((2 * pi) + teta))) ** 2))
                  Ldb += -10 * log10((2.35 ** 2) * (((delta_hbs / d) * ((b / lam) ** 0.5)) ** 1.8))
              except ValueError:
                  Ldb = 0  # Handle log of negative or zero
              return Ldb
      
          def plot(self):
              inputs = self.get_inputs()
              if not inputs:
                  return
              f, hr, hbs1, hbs2, hms, fi, w, b = inputs
      
              # Constants
              meters = list(range(200, 1600, 100))
      
              los_set, nlos_hbs1_middletown, nlos_hbs1_largetown, nlos_hbs2_middletown, nlos_hbs2_largetown, bertoni_hbs1 = [], [], [], [], [], []
      
              for el in meters:
                  los_set.append(self.los(f, el))
                  kf_middletown = -4 + (0.7 * ((f / 925)) - 1)
                  kf_largetown = -4 + (1.5 * ((f / 925)) - 1)
                  nlos_hbs1_middletown.append(self.nlos(f, el, hms, hbs1, kf_middletown, hr, fi))
                  nlos_hbs1_largetown.append(self.nlos(f, el, hms, hbs1, kf_largetown, hr, fi))
                  nlos_hbs2_middletown.append(self.nlos(f, el, hms, hbs2, kf_middletown, hr, fi))
                  nlos_hbs2_largetown.append(self.nlos(f, el, hms, hbs2, kf_largetown, hr, fi))
                  bertoni_hbs1.append(self.bertoni(f, el, hms, hbs1, w, b))
      
              # Plotting
              plt.figure(figsize=(10, 8))
              plt.plot(meters, los_set, marker='o', label='Зона прямой видимости')
              plt.plot(meters, nlos_hbs1_middletown, marker='o', label=f'Вне зоны прямой видимости, высота {hbs1} м, город средних размеров')
              plt.plot(meters, nlos_hbs1_largetown, marker='o', label=f'Вне зоны прямой видимости, высота {hbs1} м, город с плотной застройкой')
              plt.plot(meters, nlos_hbs2_middletown, marker='o', label=f'Вне зоны прямой видимости, высота {hbs2} м, город средних размеров')
              plt.plot(meters, nlos_hbs2_largetown, marker='o', label=f'Вне зоны прямой видимости, высота {hbs2} м, город с плотной застройкой')
              plt.plot(meters, bertoni_hbs1, marker='o', label='Модель Кся-Бертони')
      
              plt.grid(True)
              plt.legend(loc="upper left", bbox_to_anchor=(1, 1))
              plt.xlim(200, 1500)
              plt.xticks(meters)
              plt.xlabel("Расстояние x, м")
              plt.ylabel("L (потери сигнала), дБ")
              plt.title("Модели Уолфиша-Икегами и Кся-Бертони")
              plt.tight_layout()
              plt.show()
      
              # Store data for saving
              self.current_data = {
                  "meters": meters,
                  "los_set": los_set,
                  "nlos_hbs1_middletown": nlos_hbs1_middletown,
                  "nlos_hbs1_largetown": nlos_hbs1_largetown,
                  "nlos_hbs2_middletown": nlos_hbs2_middletown,
                  "nlos_hbs2_largetown": nlos_hbs2_largetown,
                  "bertoni_hbs1": bertoni_hbs1
              }
      
          def toFixed(self, numObj, digits=3):
              return float(f"{numObj:.{digits}f}")
      
          def save_to_xlsx(self, filename="pract3.xlsx"):
              if not hasattr(self, 'current_data'):
                  messagebox.showwarning("No Data", "Please plot the graph before saving.")
                  return
              workbook = Workbook()
              sheet = workbook.active
              sheet.title = "Потери сигнала"
      
              headers = [
                  "Расстояние (м)", 
                  "Зона прямой видимости", 
                  f"Вне зоны, {self.inputs['hbs1'].get()} м, средний город", 
                  f"Вне зоны, {self.inputs['hbs1'].get()} м, плотная застройка", 
                  f"Вне зоны, {self.inputs['hbs2'].get()} м, средний город", 
                  f"Вне зоны, {self.inputs['hbs2'].get()} м, плотная застройка", 
                  "Модель Кся-Бертони"
              ]
              sheet.append(headers)
      
              for i in range(len(self.current_data["meters"])):
                  sheet.append([
                      self.current_data["meters"][i],
                      self.toFixed(self.current_data["los_set"][i]),
                      self.toFixed(self.current_data["nlos_hbs1_middletown"][i]),
                      self.toFixed(self.current_data["nlos_hbs1_largetown"][i]),
                      self.toFixed(self.current_data["nlos_hbs2_middletown"][i]),
                      self.toFixed(self.current_data["nlos_hbs2_largetown"][i]),
                      self.toFixed(self.current_data["bertoni_hbs1"][i])
                  ])
      
              # Adjust column widths
              for column_cells in sheet.columns:
                  max_length = 0
                  column = column_cells[0].column
                  for cell in column_cells:
                      try:
                          cell_length = len(str(cell.value))
                          if cell_length > max_length:
                              max_length = cell_length
                      except:
                          pass
                  adjusted_width = (max_length + 2)
                  sheet.column_dimensions[get_column_letter(column)].width = adjusted_width
      
              # Add borders and alignment
              thin_border = Border(
                  left=Side(style='thin'),
                  right=Side(style='thin'),
                  top=Side(style='thin'),
                  bottom=Side(style='thin')
              )
      
              for row in sheet.iter_rows():
                  for cell in row:
                      cell.alignment = Alignment(horizontal="center", vertical="center")
                      cell.border = thin_border
      
              # Bold header
              for cell in sheet[1]:
                  cell.font = Font(bold=True)
      
              try:
                  workbook.save(filename)
                  messagebox.showinfo("Success", f"Data saved to {filename} successfully.")
              except Exception as e:
                  messagebox.showerror("Save Error", f"An error occurred while saving:\n{e}")
      
      if __name__ == "__main__":
          app = SignalLossApp()
          app.mainloop()
      
    4. Explanation of the Code

      • Class SignalLossApp: Inherits from ctk.CTk and sets up the main window.

      • Input Frame:

        • Contains labeled input fields for all the necessary parameters.
        • Uses a grid layout to organize labels and entry widgets.
      • Button Frame:

        • Contains two buttons: "Plot Graph" and "Save to Excel".
        • Each button is linked to its respective method (plot and save_to_xlsx).
      • get_inputs Method:

        • Retrieves and validates the input values from the user.
        • Displays an error message if invalid inputs are detected.
      • Signal Loss Models (los, nlos, bertoni):

        • Implement the mathematical models for signal loss based on the input parameters.
      • plot Method:

        • Retrieves the input values.
        • Calculates the signal loss using both models across a range of distances.
        • Plots the results using matplotlib.
        • Stores the current data for later saving.
      • save_to_xlsx Method:

        • Checks if there's data to save (i.e., after plotting).
        • Writes the data to an Excel file with appropriate formatting.
        • Informs the user upon successful save or if any errors occur.
    5. Running the Application

      Save the code to a Python file, for example, signal_loss_app.py, and run it using:

      python signal_loss_app.py
      

      You'll see a window where you can input all required parameters. After entering the values:

      • Click "Plot Graph" to visualize the signal loss models.
      • Click "Save to Excel" to save the results to an Excel file named pract3.xlsx.
    6. Enhancements and Error Handling

      • Validation: The application checks for valid numerical inputs and alerts the user if any invalid data is entered.
      • Dynamic Labels: The labels in the Excel file reflect the inputted base station heights.
      • Responsive Layout: The GUI uses padding and grid configurations to ensure a clean layout.
      • User Feedback: Informative messages guide the user, especially when saving data or encountering errors.
    7. Customization

      You can further customize the GUI by:

      • Changing themes using ctk.set_default_color_theme.
      • Adjusting window size and adding more descriptive labels or tooltips.
      • Allowing users to specify the Excel filename and location.

    This setup provides an interactive and user-friendly way to work with your signal loss models, making computations and data management more accessible.