Spaces:
Sleeping
Sleeping
| """ | |
| Utility functions for data processing and conversion | |
| """ | |
| import numpy as np | |
| import pandas as pd | |
| import re | |
| def local_to_numeric_matrix(cell_mat): | |
| """Convert cell array/DataFrame to numeric matrix""" | |
| if isinstance(cell_mat, np.ndarray): | |
| if len(cell_mat) == 0: | |
| return np.array([]) | |
| if np.issubdtype(cell_mat.dtype, np.number): | |
| return cell_mat.astype(float) | |
| # Convert to DataFrame if not already | |
| if not isinstance(cell_mat, pd.DataFrame): | |
| cell_mat = pd.DataFrame(cell_mat) | |
| mat = np.zeros(cell_mat.shape) | |
| for i in range(cell_mat.shape[0]): | |
| for j in range(cell_mat.shape[1]): | |
| mat[i, j] = _coerce_to_double(cell_mat.iloc[i, j]) | |
| return mat | |
| def local_to_numeric_vector(col): | |
| """Convert column/row of labels to numeric vector""" | |
| if isinstance(col, (list, np.ndarray, pd.Series)): | |
| if len(col) == 0: | |
| return np.array([]) | |
| vec = np.zeros(len(col)) | |
| for i, val in enumerate(col): | |
| vec[i] = _coerce_to_double(val) | |
| return vec | |
| return np.array([_coerce_to_double(col)]) | |
| def local_parse_route(route_str): | |
| """Parse route string to list of integers""" | |
| if isinstance(route_str, (list, np.ndarray)): | |
| return list(route_str) | |
| if isinstance(route_str, (int, float)): | |
| return [int(route_str)] | |
| if isinstance(route_str, str): | |
| # Extract all numbers from string | |
| numbers = re.findall(r'\d+', route_str) | |
| return [int(n) for n in numbers] | |
| return [] | |
| def local_find_coord_columns(T): | |
| """Find longitude, latitude, and id column indices""" | |
| cols = [c.lower() for c in T.columns] | |
| lonIdx = next((i for i, c in enumerate(cols) if any(x in c for x in ['lon', 'x', 'longitude'])), 0) | |
| latIdx = next((i for i, c in enumerate(cols) if any(x in c for x in ['lat', 'y', 'latitude'])), 1) | |
| idIdx = next((i for i, c in enumerate(cols) if any(x in c for x in ['id', 'node'])), 2) | |
| return lonIdx, latIdx, idIdx | |
| def _coerce_to_double(x): | |
| """Convert single value to float with safe rules""" | |
| if isinstance(x, (int, float, np.number)): | |
| return float(x) | |
| if isinstance(x, str): | |
| s = x.strip() | |
| if s == "" or s == "-" or s == "—" or s.upper() in ["NA", "N/A"]: | |
| return np.nan | |
| # Extract numeric part | |
| s = re.sub(r'[^\d\.\-eE]', '', s) | |
| try: | |
| return float(s) | |
| except ValueError: | |
| return np.nan | |
| if pd.isna(x): | |
| return np.nan | |
| return np.nan | |
| def Cost_tsp(tour, D): | |
| """Calculate TSP tour cost""" | |
| n = len(tour) | |
| cost = 0.0 | |
| for i in range(n - 1): | |
| cost += D[tour[i], tour[i + 1]] | |
| cost += D[tour[n - 1], tour[0]] | |
| return cost |