Files
ncc/NCC/modulo_mappale.py
luca.mustacchio@outlook.it b45a0ce26f Aggiungere i file di progetto.
2026-01-31 14:23:18 +01:00

254 lines
11 KiB
Python

# -*- coding: utf-8 -*-
from re import split
from datetime import timedelta
from datetime import datetime
import string
from geopy.geocoders import Nominatim
import osmnx as ox
import networkx as nx
import re
import os
from collections import OrderedDict
import matplotlib.pyplot as plt
"""
ripetere
"""
# G = None
separator = os.path.sep
def get_location_info(place):
# partenza: Voldomino, Luino, Comunità Montana Valli del Verbano, Varese, Lombardia, 21016, Italia
# arrivo: Muggiò, Monza e della Brianza, Lombardia, 20835, Italia
geolocator = Nominatim(user_agent="my_geocoder")
location = geolocator.geocode(place, exactly_one=True)
if location is not None:
tipo = {
"country": "stato",
"class": "regione",
"city": "capoluogo",
"county": "provincia",
"town": "comune",
"village": "paese",
}
t = tipo.get(location.raw["addresstype"], location.raw["addresstype"])
ind = re.sub(r"\d+", "", location.address)
ind = ind.split(",")
ind = [x for x in ind if x != " "]
# ind=list(reversed(ind))
# print (ind)
# appartenenza=None
return {
"nome": location.raw["name"],
"indirizzo": location.address,
"tipo": t,
"coordinate": [location.raw["lat"], location.raw["lon"]],
"id": ind,
"raw": location.raw,
}
else:
return {"errore": "Posizione non trovata"}
def crea_path(partenza_id, arrivo_id) -> str:
P = [part.replace(' ', '') for part in partenza_id]
A = [part.replace(' ', '') for part in arrivo_id]
intersezione = [part for part in P if part in A]
intersezione1 = intersezione[::-1]
path_map = separator.join(intersezione1)
if path_map == "":
path_map = P[0] + A[0]
# Inverti l'ordine delle parole
return ("Mappale" + separator + path_map + ".NCC",intersezione)
def load_or_download_graph(place, file_path):
print(f"ricerca dati {place[0]}")
# Controllo se il file è già presente nel percorso specificato
if os.path.exists(file_path):
print(f"\tCaricamento del grafo da: {file_path}")
return ox.load_graphml(file_path)
else:
print("\tDownload dei dati dalla rete...")
graph = ox.graph_from_place(place, network_type='drive')
ox.save_graphml(graph, file_path) # Salva il grafo nella cache
print(f"\tSalvato file in {file_path}")
return graph
# Se il file non è presente, prova a cercare nella cache di osmnx
# try:
# print("\tRecupero dei dati dalla cache...")
# ox.settings.use_cache = True
# graph = ox.graph_from_place(place, network_type='drive')
# ox.save_graphml(graph, file_path) # Salva il grafo nella cache
# print(f"\tSalvato file in cache {file_path}")
# return graph
# except:
def Caricamento_Mappale(partenza_dati: dict, arrivo_dati: dict):
path_map = crea_path(partenza_dati['id'], arrivo_dati['id'])
orario_corrente = datetime.now().time()
print("\tricerca delle coordinate")
# origin_coordinates = [(float(element),) for element in partenza_dati['coordinate']]
# destination_coordinates = [(float(element),) for element in arrivo_dati['coordinate']]
# print(origin_coordinates)
origin_coordinates = ox.geocode(partenza_dati['indirizzo'])
destination_coordinates = ox.geocode(arrivo_dati['indirizzo'])
print(f"\tcooridnate di partenza = {origin_coordinates}")
print(f"\tcooridnate di arrivo = {destination_coordinates}")
print("ricerca dati della mappa ...")
graph_area=(partenza_dati['indirizzo'],arrivo_dati['indirizzo'])
G = load_or_download_graph(graph_area, path_map[0])
# OSM data are sometime incomplete so we use the speed module of osmnx to add missing edge speeds and travel times
G = ox.add_edge_speeds(G)
G = ox.add_edge_travel_times(G)
orario_fine = datetime.now().time()
differenza = datetime.combine(datetime.min,
orario_fine) - datetime.combine(
datetime.min, orario_corrente)
print(f"\ttempo:{differenza}")
# Trova il percorso più breve tra i due punti
print("\tricerca del percorso più veloce...")
# In the graph, get the nodes closest to the points
origin_node = ox.nearest_nodes(G, origin_coordinates[0], origin_coordinates[1])
destination_node = ox.nearest_nodes(G, destination_coordinates[0], destination_coordinates[1])
# Get the shortest route by distance
shortest_route_by_distance = ox.shortest_path(G, origin_node, destination_node, weight='length')
# Get the shortest route by travel time
shortest_route_by_travel_time = ox.shortest_path(G, origin_node, destination_node, weight='travel_time')
# Get the travel time, in seconds
# Note here that we use "nx" (networkx), not "ox" (osmnx)
travel_time_in_seconds = nx.shortest_path_length(G, origin_node, destination_node, weight='travel_time')
#The travel time in "HOURS:MINUTES:SECONDS" format
travel_time_in_hours_minutes_seconds = str(timedelta(seconds=travel_time_in_seconds))
print("tempo di percorrenza h:m:s: ", travel_time_in_hours_minutes_seconds)
# Get the distance in meters
distance_in_meters = nx.shortest_path_length(G, origin_node, destination_node, weight='length')
distance_in_kilometers = distance_in_meters / 1000
print("distanza Km:", distance_in_kilometers)
print("caricamento mappa")
#fig, ax = ox.plot_graph(G, node_size=0, edge_linewidth=0.5, show=True, close=False, figsize=(10, 10), node_color='w')
fig, ax = ox.plot_graph_routes(G, routes=[shortest_route_by_distance, shortest_route_by_travel_time], route_colors=['r', 'y'], route_linewidth=6, node_size=1, node_color='b')
print("... fine caricamento mappa")
return
# Configura l'uso della cache
ox.settings.use_cache = True
# The place where your 2 points are located. It will be used to create a graph from the OSM data
# In this example, the 2 points are two addresses in Manhattan, so we choose "Manhattan"
# It could be a bounding box too, or an area around a point
# graph_area = nome
graph_area = ox.graph_from_place(nome, network_type="drive")
# Create the graph of the area from OSM data. It will download the data and create the graph
# G = ox.graph_from_place(graph_area, network_type='drive')
# (For a better accuracy, create a graph with lot more nodes:)
# G = ox.graph_from_place(graph_area, network_type='drive', simplify=False)
# OSM data are sometime incomplete so we use the speed module of osmnx to add missing edge speeds and travel times
# G = ox.add_edge_speeds(G)
# G = ox.add_edge_travel_times(G)
# Save graph to disk if you want to reuse it
# ox.save_graphml(G, "varese.graphml")
# Load the graph
G = ox.load_graphml(r"Mappali\varese.graphml")
# Plot the graph
fig, ax = ox.plot_graph(G,
figsize=(10, 10),
node_size=0,
edge_color="y",
edge_linewidth=0.2)
# Two pairs of (lat,lng) coordinates
# origin_coordinates = (40.70195053163349, -74.01123198479581)
# destination_coordinates = (40.87148739347057, -73.91517498611597)
def Partenza_Arrivo(partenza="via libertà 59, cugliate-fabiasco",
arrivo="via asmara, Luino"):
global G
if partenza == "":
partenza = "via libertà 59, cugliate-fabiasco"
if arrivo == "":
arrivo = "viale belforte , Varese"
print(f"partenza {partenza}, arrivo {arrivo}")
# If you want to take an address (osmx will use Nominatim service for this)
# origin_coordinates = ox.geocode("2 Broad St, New York, NY 10005")
# origin_coordinates = ox.geocode("via libertà 59, cugliate fabiasco")
# destination_coordinates = ox.geocode("luino, Varese, italy")
origin_coordinates = ox.geocode(partenza)
destination_coordinates = ox.geocode(arrivo)
# In the graph, get the nodes closest to the points
origin_node = ox.nearest_nodes(G,
Y=origin_coordinates[0],
X=origin_coordinates[1])
destination_node = ox.nearest_nodes(G,
Y=destination_coordinates[0],
X=destination_coordinates[1])
# Get the shortest route by distance
shortest_route_by_distance = ox.shortest_path(G,
origin_node,
destination_node,
weight="length")
# Plot the shortest route by distance
# fig, ax = ox.plot_graph_route(G, shortest_route_by_distance, route_color='y', route_linewidth=6, node_size=0)
# Get the shortest route by travel time
shortest_route_by_travel_time = ox.shortest_path(G,
origin_node,
destination_node,
weight="travel_time")
# Plot the shortest route by travel time
# fig, ax = ox.plot_graph_route(G, shortest_route_by_travel_time, route_color='y', route_linewidth=6, node_size=0)
# Plot the 2 routes
# fig, ax = ox.plot_graph_routes(G, routes=[shortest_route_by_distance, shortest_route_by_travel_time], route_colors=['r', 'y'], route_linewidth=6, node_size=0)
# Get the travel time, in seconds
# Note here that we use "nx" (networkx), not "ox" (osmnx)
travel_time_in_seconds = nx.shortest_path_length(G,
origin_node,
destination_node,
weight="travel_time")
print("travel time in seconds", travel_time_in_seconds)
# The travel time in "HOURS:MINUTES:SECONDS" format
travel_time_in_hours_minutes_seconds = str(
timedelta(seconds=travel_time_in_seconds))
print("travel time in hours minutes seconds",
travel_time_in_hours_minutes_seconds)
# Get the distance in meters
distance_in_meters = nx.shortest_path_length(G,
origin_node,
destination_node,
weight="length")
print("distance in meters", distance_in_meters)
# Distance in kilometers
distance_in_kilometers = distance_in_meters / 1000
print("distance in kilometers", distance_in_kilometers)