import numpy as np
import folium
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from folium.features import CustomIcon
from branca.element import Element, Figure
import datetime
import http.server
import socketserver
import threading
import webbrowser
import os
import noise # Ensure you have the 'noise' module installed
from scipy.ndimage import gaussian_filter, map_coordinates
from PIL import Image
Load color scales
def load_color_scale(file_path):
with open(file_path, "r") as file:
color_scale = eval(file.read())
return np.array(color_scale) / 255
Ensure the 'colours' directory exists and color scale files are available
color_dir = "colours"
if not os.path.exists(color_dir):
os.makedirs(color_dir)
Load or define the color scales
Ensure that 'dBZ.txt', 'radarbeam.txt', and 'radarnoise.txt' exist in the 'colours' directory
beam_color_scale = load_color_scale("colours/radarbeam.txt")
radarnoise_color_scale = load_color_scale("colours/radarnoise.txt")
color_scale = load_color_scale("colours/dBZ.txt") # Ensure this includes the full dBZ range
Reverse the color scale if necessary
Uncomment the following line if the colors appear inverted
Replace 'interactive/radarsign.png' with the path to your radar icon image
icon_image = 'interactive/radarsign.png'
Check if the icon image exists, if not, create a simple placeholder
if not os.path.exists(icon_image):
if not os.path.exists('interactive'):
os.makedirs('interactive')
# Create a simple red square as a placeholder
img = Image.new('RGB', (30, 20), color='red')
img.save(icon_image)
Fix the localhost doesn't working, like starting but when automatically opening in the browser it doesn't loads the localhost page, while the html file itself works just fine
Make more "isolated" cells, because currently the cells are frequently connected each to other by low dBZ (around 0-5) values
Certainly! Let's address both of your issues step-by-step:
Fixing the Localhost Server Issue
Creating More Isolated Cells
1. Fixing the Localhost Server Issue
Problem:
While the server starts successfully, the browser fails to load the localhost page automatically, even though accessing the HTML file directly works.
Cause:
The likely cause is that the browser attempts to open the page before the server is fully up and running. This results in the browser not finding the page initially.
Solution:
Ensure that the server is fully operational before attempting to open the browser. This can be achieved using synchronization mechanisms like threading.Event to signal when the server is ready.
Step-by-Step Implementation:
Import Required Modules:
Ensure you have the necessary imports for synchronization:
python
import threading
from threading import Thread, Event
import time
Modify the Server Function to Signal Readiness:
Update the server function to set an event once the server starts serving.
python
def start_server(server_ready_event):
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
server_ready_event.set() # Signal that the server is ready
httpd.serve_forever()
Set Up Synchronization and Start Threads:
Use an Event to synchronize the server and browser threads.
python
# Define port
PORT = 8000
# Create an Event object
server_ready_event = Event()
# Start the server thread
server_thread = Thread(target=start_server, args=(server_ready_event,), daemon=True)
server_thread.start()
# Wait until the server is ready
server_ready_event.wait() # This blocks until `server_ready_event.set()` is called
# Open the browser after the server is ready
webbrowser.open(f'http://localhost:{PORT}/{output_file}')
Complete Adjusted Server and Browser Code:
Here's the complete adjusted section for starting the server and opening the browser:
python
# Define port
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
def start_server(server_ready_event):
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
server_ready_event.set() # Signal that the server is ready
httpd.serve_forever()
# Create an Event object
server_ready_event = Event()
# Start the server thread
server_thread = Thread(target=start_server, args=(server_ready_event,), daemon=True)
server_thread.start()
# Wait until the server is ready
server_ready_event.wait() # This blocks until `server_ready_event.set()` is called
# Open the browser after the server is ready
webbrowser.open(f'http://localhost:{PORT}/{output_file}')
Explanation:
Event Object:server_ready_event is used to signal when the server has started.
Server Thread: The server runs in a separate thread and sets the event once it's ready.
Browser Opening: The main thread waits (server_ready_event.wait()) until the server is ready before opening the browser, ensuring the page loads correctly.
2. Creating More Isolated Cells
Problem:
Cells in the radar visualization are frequently connected via low dBZ values (around 0-5), resulting in less isolated cells than desired.
Solution:
Adjust the noise generation and post-processing steps to enhance cell isolation. This can be achieved by:
Increasing the Threshold: Higher threshold values reduce the number of low dBZ connections.
Reducing Smoothing: Less smoothing preserves the boundaries of cells better.
Adjusting Noise Parameters: Tweaking the noise resolution, octaves, persistence, and lacunarity to generate more distinct cells.
Applying Morphological Operations: Removing small connections or enhancing separation between cells.
Step-by-Step Implementation:
Increase the Threshold:
Increasing the threshold will ensure that only higher dBZ values (stronger reflections) are retained, reducing the connections via low dBZ areas.
python
# Apply threshold to isolate cells
threshold = 0.5 # Increased from 0.3 to 0.5
cells = np.where(cells > threshold, cells, 0)
Reduce the Smoothing (Gaussian Filter Sigma):
Decreasing the sigma value in the Gaussian filter will preserve more of the cell boundaries, preventing excessive blending.
python
# Apply smoothing to mimic natural shapes
cells = gaussian_filter(cells, sigma=1) # Reduced from 3 to 1
Adjust Noise Generation Parameters:
Fine-tuning the noise parameters can lead to more distinct and isolated cells.
python
# Generate fractal noise with adjusted parameters
res = (20, 20) # Increased resolution for finer details
octaves = 3 # Reduced octaves to decrease complexity
persistence = 0.6 # Slightly increased persistence
lacunarity = 2.0 # Keep lacunarity the same or adjust as needed
cells = generate_fractal_noise_2d((height, width), res, octaves, persistence, lacunarity)
Apply Non-Linear Transformation More Aggressively:
Increasing the exponent will emphasize higher values more, further reducing the presence of low dBZ connections.
python
# Apply non-linear transformation
cells = cells ** 2 # Increased exponent from 1.5 to 2
Optional: Apply Morphological Operations to Enhance Isolation:
Using morphological operations like binary opening can help remove small connections between cells.
python
Explanation:
Threshold Increase: By raising the threshold, only areas with stronger reflections (higher dBZ) are considered, reducing the prevalence of low-intensity connections.
Smoothing Reduction: Less smoothing preserves cell boundaries, making them appear more distinct.
Noise Parameter Adjustment: Fine-tuning noise parameters affects the number and size of cells, promoting better isolation.
Non-Linear Transformation: A higher exponent accentuates high values, diminishing low-value connections.
Morphological Operations: These operations help eliminate small or weak connections between cells, ensuring more isolated structures.
Final Adjusted Script Snippet
Here's a consolidated version of the adjustments within your script:
python
Additional Recommendations:
Adjust min_size in Morphological Operations: The min_size parameter determines the minimum size of cells to retain. Adjust this based on your specific visualization needs.
Fine-Tune Noise Parameters: Experiment with different values for res, octaves, persistence, and lacunarity to achieve the desired cell patterns.
Performance Considerations: Applying morphological operations on large images can be computationally intensive. Ensure that your system has adequate resources, or consider processing the image in smaller tiles if necessary.
By implementing these adjustments, you should achieve:
Reliable Localhost Server Access: The browser will open the radar visualization only after the server is fully operational, ensuring seamless access.
More Isolated Cells: Enhanced cell isolation through threshold adjustments, reduced smoothing, refined noise parameters, and morphological operations will result in a more realistic and visually appealing radar display.
Feel free to tweak the parameters further to best suit your specific requirements. If you encounter any additional issues or need further customization, don't hesitate to ask!
from scipy.ndimage import binary_opening, binary_closing, label
# After thresholding and smoothing
binary_cells = cells > threshold
# Perform binary opening to remove small connections
binary_cells = binary_opening(binary_cells, structure=np.ones((3,3)))
# Label the cells
labeled_cells, num_features = label(binary_cells)
# Optionally, remove small features based on size
# For example, keep only cells larger than a certain number of pixels
min_size = 500 # Adjust based on desired isolation
for i in range(1, num_features + 1):
if np.sum(labeled_cells == i) < min_size:
binary_cells[labeled_cells == i] = 0
# Update cells
cells = binary_cells.astype(float)
Note: Morphological operations can be computationally intensive for large images. Adjust parameters like structure and min_size based on your specific needs.
Implementing the Adjustments in Your Script:
Here's how you can integrate these changes into your existing script:
python
# Generate fractal noise with adjusted parameters
res = (20, 20) # Increased resolution for finer details
octaves = 3 # Reduced octaves to decrease complexity
persistence = 0.6 # Slightly increased persistence
lacunarity = 2.0 # Keep lacunarity the same or adjust as needed
cells = generate_fractal_noise_2d((height, width), res, octaves, persistence, lacunarity)
# Apply higher threshold to isolate cells more
threshold = 0.5 # Increased from 0.3 to 0.5
cells = np.where(cells > threshold, cells, 0)
# Apply less smoothing
cells = gaussian_filter(cells, sigma=1) # Reduced from 3 to 1
# Apply more aggressive non-linear transformation
cells = cells ** 2 # Increased exponent from 1.5 to 2
# Optional: Apply morphological operations
binary_cells = cells > threshold
binary_cells = binary_opening(binary_cells, structure=np.ones((3,3)))
labeled_cells, num_features = label(binary_cells)
min_size = 500 # Adjust based on desired isolation
for i in range(1, num_features + 1):
if np.sum(labeled_cells == i) < min_size:
binary_cells[labeled_cells == i] = 0
cells = binary_cells.astype(float)
# Apply distance mask
cells[~distance_mask] = 0
# Continue with mapping to dBZ, color indexing, etc.
import numpy as np
import folium
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from folium.features import CustomIcon
from branca.element import Element, Figure
import datetime
import http.server
import socketserver
import threading
import webbrowser
import os
import noise # Ensure you have the 'noise' module installed
from scipy.ndimage import gaussian_filter, map_coordinates, binary_opening, label
from PIL import Image
from threading import Thread, Event
# ... [Previous code remains unchanged up to cell generation] ...
# Generate fractal noise with adjusted parameters
res = (20, 20) # Increased resolution for finer details
octaves = 3 # Reduced octaves to decrease complexity
persistence = 0.6 # Slightly increased persistence
lacunarity = 2.0 # Keep lacunarity the same or adjust as needed
cells = generate_fractal_noise_2d((height, width), res, octaves, persistence, lacunarity)
# Apply higher threshold to isolate cells more
threshold = 0.5 # Increased from 0.3 to 0.5
cells = np.where(cells > threshold, cells, 0)
# Apply less smoothing
cells = gaussian_filter(cells, sigma=1) # Reduced from 3 to 1
# Apply more aggressive non-linear transformation
cells = cells ** 2 # Increased exponent from 1.5 to 2
# Optional: Apply morphological operations to enhance isolation
binary_cells = cells > threshold
binary_cells = binary_opening(binary_cells, structure=np.ones((3,3)))
# Label connected components
labeled_cells, num_features = label(binary_cells)
# Remove small features
min_size = 500 # Adjust based on desired isolation
for i in range(1, num_features + 1):
if np.sum(labeled_cells == i) < min_size:
binary_cells[labeled_cells == i] = 0
# Update cells
cells = binary_cells.astype(float)
# Apply distance mask
cells[~distance_mask] = 0
# Map cell values to dBZ range
min_dbz = -20
max_dbz = 80
cells_dbz = cells * (max_dbz - min_dbz) + min_dbz
# Debug: Print the range of cells_dbz
print(f"cells_dbz range: min={cells_dbz.min()}, max={cells_dbz.max()}")
# Ensure that the color_scale has enough colors
num_colors = len(color_scale)
if num_colors < (max_dbz - min_dbz + 1):
print("Warning: Color scale does not cover the entire dBZ range.")
# Map dBZ values to color indices
color_indices = ((cells_dbz - min_dbz) / (max_dbz - min_dbz) * (num_colors - 1)).astype(int)
color_indices = np.clip(color_indices, 0, num_colors - 1)
# Create output image
output_image = color_scale[color_indices]
# Apply alpha channel based on whether cells exceed the threshold
alpha_channel = np.where(cells > threshold, 1.0, 0.0) # 1.0 opaque where cells > threshold, else transparent
output_image = np.dstack((output_image, alpha_channel))
# Convert to 0-255 range for ImageOverlay
output_image_uint8 = (output_image * 255).astype(np.uint8)
# Create Folium map
m = folium.Map(
location=[center_lat, center_lon],
zoom_start=7,
zoom_control=False,
control_scale=False,
attributionControl=False
)
# ... [Rest of the code remains unchanged up to server setup] ...
# Start the server and open the browser with synchronization
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
def start_server(server_ready_event):
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
server_ready_event.set() # Signal that the server is ready
httpd.serve_forever()
# Create an Event object
server_ready_event = Event()
# Start the server thread
server_thread = Thread(target=start_server, args=(server_ready_event,), daemon=True)
server_thread.start()
# Wait until the server is ready
server_ready_event.wait() # This blocks until `server_ready_event.set()` is called
# Open the browser after the server is ready
webbrowser.open(f'http://localhost:{PORT}/{output_file}')