Revise, expand and improve the following code. This is meant to be doing FTTH GPON fibre network designs. See if you can double the amount of code improving the logic.
import osmnx as ox
import simplekml
import numpy as np
import tkinter as tk
from tkinter import messagebox, ttk, filedialog
import logging
import json
import os
import geopy.distance as geo_dist
import networkx as nx

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

class NetworkDesignTool:
    def __init__(self, root):
        self.setup_ui(root)
        self.load_preferences()
        self.network_costs = {"fiber_cost_per_meter": 2.5, "trenching_cost_per_meter": 5.0, "manhole_cost": 500}

    def setup_ui(self, root):
        """Setup the GUI components."""
        root.title("Advanced GPON FTTH Network Design Tool")

        # Area Name
        tk.Label(root, text="Area Name:").grid(row=0, column=0, padx=10, pady=5, sticky='e')
        self.area_name_entry = tk.Entry(root, width=30)
        self.area_name_entry.grid(row=0, column=1, padx=10, pady=5)

        # Fiber Ratio
        tk.Label(root, text="Fiber Ratio:").grid(row=1, column=0, padx=10, pady=5, sticky='e')
        self.fiber_ratio_combobox = ttk.Combobox(root, values=["1:4", "1:8", "1:16", "1:32"], state="readonly")
        self.fiber_ratio_combobox.grid(row=1, column=1, padx=10, pady=5)
        self.fiber_ratio_combobox.current(0)

        # Deployment Option
        tk.Label(root, text="Deployment Option:").grid(row=2, column=0, padx=10, pady=5, sticky='e')
        self.deployment_option_combobox = ttk.Combobox(root, values=["underground", "overhead"], state="readonly")
        self.deployment_option_combobox.grid(row=2, column=1, padx=10, pady=5)
        self.deployment_option_combobox.current(0)

        # Fiber and Trenching Costs
        tk.Label(root, text="Fiber Cost (per meter):").grid(row=3, column=0, padx=10, pady=5, sticky='e')
        self.fiber_cost_entry = tk.Entry(root, width=10)
        self.fiber_cost_entry.grid(row=3, column=1, padx=10, pady=5)
        self.fiber_cost_entry.insert(0, "2.5")

        tk.Label(root, text="Trenching Cost (per meter):").grid(row=4, column=0, padx=10, pady=5, sticky='e')
        self.trenching_cost_entry = tk.Entry(root, width=10)
        self.trenching_cost_entry.grid(row=4, column=1, padx=10, pady=5)
        self.trenching_cost_entry.insert(0, "5.0")

        # Save Preferences
        self.save_pref_var = tk.BooleanVar()
        tk.Checkbutton(root, text="Save Preferences", variable=self.save_pref_var).grid(row=5, column=0, padx=10, pady=5, columnspan=2)

        # Run Button
        run_button = tk.Button(root, text="Run Network Design", command=self.run_network_design)
        run_button.grid(row=6, column=0, columnspan=2, pady=20)

        # Progress Bar and Logs
        self.progress = ttk.Progressbar(root, orient='horizontal', length=200, mode='determinate')
        self.progress.grid(row=7, column=0, columnspan=2, pady=10)

        self.log_output = tk.Text(root, height=10, width=50)
        self.log_output.grid(row=8, column=0, columnspan=2, padx=10, pady=10)
        self.log_output.config(state=tk.DISABLED)

    def load_preferences(self):
        """Load user preferences from a JSON file."""
        filepath = "user_preferences.json"
        if os.path.exists(filepath):
            try:
                with open(filepath, "r") as file:
                    preferences = json.load(file)
                    self.area_name_entry.insert(0, preferences.get("area_name", ""))
                    self.fiber_ratio_combobox.set(preferences.get("fiber_ratio", "1:4"))
                    self.deployment_option_combobox.set(preferences.get("deployment_option", "underground"))
            except json.JSONDecodeError as e:
                logging.error(f"Error loading preferences: {str(e)}")

    def save_preferences(self):
        """Save user preferences to a JSON file."""
        preferences = {
            "area_name": self.area_name_entry.get(),
            "fiber_ratio": self.fiber_ratio_combobox.get(),
            "deployment_option": self.deployment_option_combobox.get(),
        }
        filepath = "user_preferences.json"
        with open(filepath, "w") as file:
            json.dump(preferences, file, indent=4)

    def retrieve_data(self, area_name):
        """Retrieve road and building data from OpenStreetMap for the specified area."""
        self.log_message(f"Retrieving data for {area_name}...")
        try:
            graph = ox.graph_from_place(area_name, network_type='drive')
            buildings = ox.features_from_place(area_name, tags={'building': True})
            self.log_message(f"Nodes in graph: {len(graph.nodes)}, Buildings: {len(buildings)}")
            return graph, buildings
        except Exception as e:
            self.log_message(f"Error retrieving data: {str(e)}")
            raise

    def log_message(self, message):
        """Log messages in the output text box."""
        self.log_output.config(state=tk.NORMAL)
        self.log_output.insert(tk.END, message + "\n")
        self.log_output.config(state=tk.DISABLED)
        self.log_output.see(tk.END)

    def design_network(self, graph, buildings, fiber_ratio):
        """Design the GPON FTTH network by determining OLT and splitter placements."""
        self.log_message("Designing GPON FTTH network...")
        try:
            OLT_location = list(graph.nodes())[0]
            olt_coords = (graph.nodes[OLT_location]['y'], graph.nodes[OLT_location]['x'])
            customer_locations = [building.geometry for _, building in buildings.iterrows()]

            splitters = []
            for i in range(0, len(customer_locations), int(fiber_ratio.split(':')[1])):
                splitter_location = customer_locations[i]
                splitters.append(splitter_location)

            self.log_message(f"OLT placed at {olt_coords}, {len(customer_locations)} customer locations identified.")
            return olt_coords, splitters, customer_locations
        except Exception as e:
            self.log_message(f"Error designing network: {str(e)}")
            raise

    def calculate_distances(self, olt_location, customer_locations):
        """Calculate distances from OLT to each customer location."""
        distances = []
        for customer in customer_locations:
            customer_coords = customer.centroid.coords[0]
            distance = geo_dist.distance(olt_location, customer_coords).m
            distances.append((customer_coords, distance))
        self.log_message(f"Calculated distances for {len(customer_locations)} customers.")
        return distances

    def calculate_total_cost(self, distances, splitters):
        """Calculate total cost of the network based on fiber, trenching, and splitter costs."""
        total_cost = 0
        fiber_cost_per_meter = float(self.fiber_cost_entry.get())
        trenching_cost_per_meter = float(self.trenching_cost_entry.get())
        
        for _, distance in distances:
            total_cost += distance * (fiber_cost_per_meter + trenching_cost_per_meter)
        
        total_cost += len(splitters) * self.network_costs['manhole_cost']

        self.log_message(f"Estimated total cost: ${total_cost:.2f}")
        return total_cost

    def generate_kml(self, olt_location, splitters, customer_locations, distances, deployment_option):
        """Generate a KML file representing the GPON network."""
        self.log_message("Generating KML file...")
        try:
            kml = simplekml.Kml()

            kml.newpoint(name="OLT", coords=[(olt_location[1], olt_location[0])])

            for i, splitter in enumerate(splitters):
                splitter_coords = splitter.centroid.coords[0]
                line = kml.newlinestring(name=f"Feeder Line to Splitter {i+1}",
                                         coords=[(olt_location[1], olt_location[0]), (splitter_coords[0], splitter_coords[1])])
                line.style.linestyle.color = simplekml.Color.red
                line.style.linestyle.width = 2

            for i, (customer_coords, distance) in enumerate(distances):
                line = kml.newlinestring(name=f"Drop Line to Customer {i+1}",
                                         coords=[(splitter_coords[0], splitter_coords[1]), (customer_coords[0], customer_coords[1])])
                line.style.linestyle.color = simplekml.Color.blue if deployment_option == 'overhead' else simplekml.Color.green
                line.style.linestyle.width = 1

            kml.save("GPON_Network_Design.kml")
            self.log_message("KML file saved as GPON_Network_Design.kml.")
        except Exception as e:
            self.log_message(f"Error generating KML: {str(e)}")

    def run_network_design(self):
        """Main function to run the network design workflow."""
        area_name = self.area_name_entry.get()
        fiber_ratio = self.fiber_ratio_combobox.get()
        deployment_option = self.deployment_option_combobox.get()

        if self.save_pref_var.get():
            self.save_preferences()

        self.progress.start(10)

        try:
            graph, buildings = self.retrieve_data(area_name)
            olt_coords, splitters, customer_locations = self.design_network(graph, buildings, fiber_ratio)
            distances = self.calculate_distances(olt_coords, customer_locations)
            total_cost = self.calculate_total_cost(distances, splitters)
            self.generate_kml(olt_coords, splitters, customer_locations, distances, deployment_option)
        except Exception as e:
            self.log_message(f"Error during network design: {str(e)}")
        finally:
            self.progress.stop()

if __name__ == "__main__":
    root = tk.Tk()
    app = NetworkDesignTool(root)
    root.mainloop()