"""保留的指标导出算法。""" from shapely import STRtree from shapely.errors import GEOSException import csv import numpy as np import shapely from . import config from .gpkg import iter_geometry_batches from .gpkg import quote_identifier from .gpkg import require_columns from .raster_math import to_float def csv_text(value): if value is None: return "" return str(value).strip() def signal_level(value): number = to_float(value) if number is None: return "无采集信息" if number <= config.SIGNAL_BAD_THRESHOLD: return "较差" if number <= config.SIGNAL_NORMAL_THRESHOLD: return "一般" return "正常" def collect_intersecting_metric_features(source_conn, layer, rtree, market, fields): require_columns(source_conn, layer.table_name, fields) table = quote_identifier(layer.table_name) pk = quote_identifier(layer.pk_col) geom = quote_identifier(layer.geom_col) rtree_table = quote_identifier(rtree) field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds query = f""" select b.{pk}, b.{geom}, {field_sql} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? """ rows = [] candidates = 0 cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): candidates += len(batch_rows) intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) for index in np.flatnonzero(intersects_mask): row = batch_rows[int(index)] rows.append((dict(zip(fields, row[2:])), geometries[index])) return rows, candidates def load_building_name_index(building_info_conn, layer, rtree, bounds): geometries = [] names = [] if bounds is None: return None table = quote_identifier(layer.table_name) geom = quote_identifier(layer.geom_col) pk = quote_identifier(layer.pk_col) rtree_table = quote_identifier(rtree) minx, miny, maxx, maxy = bounds query = f""" select b."name", b.{geom} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? order by b.{pk} """ cursor = building_info_conn.execute(query, (maxx, minx, maxy, miny)) for batch_rows, batch_geometries, valid_mask in iter_geometry_batches(cursor, 1): for index in np.flatnonzero(valid_mask): name = csv_text(batch_rows[int(index)][0]) if not name: continue geometries.append(batch_geometries[index]) names.append(name) if not geometries: return None return STRtree(geometries), geometries, names def match_building_info_name(name_index, geometry): if name_index is None: return "" tree, geometries, names = name_index best_name = "" best_score = -1.0 for candidate_index in tree.query(geometry, predicate="intersects"): index = int(candidate_index) info_geometry = geometries[index] try: score = geometry.intersection(info_geometry).area except GEOSException: score = 0.0 if score > best_score: best_name = names[index] best_score = score return best_name def match_building_info_names(name_index, building_geometries): if name_index is None or not building_geometries: return [""] * len(building_geometries) tree, info_geometries, names = name_index building_array = np.asarray(building_geometries, dtype=object) info_array = np.asarray(info_geometries, dtype=object) pairs = tree.query(building_array, predicate="intersects") if pairs.shape[1] == 0: return [""] * len(building_geometries) result = np.full(len(building_geometries), "", dtype=object) names_array = np.asarray(names, dtype=object) match_counts = np.bincount(pairs[0], minlength=len(building_geometries)) single_pair_mask = match_counts[pairs[0]] == 1 single_pairs = pairs[:, single_pair_mask] result[single_pairs[0]] = names_array[single_pairs[1]] multiple_pairs = pairs[:, ~single_pair_mask] if multiple_pairs.shape[1]: try: areas = shapely.area( shapely.intersection( building_array[multiple_pairs[0]], info_array[multiple_pairs[1]], ) ) except GEOSException: return [match_building_info_name(name_index, geometry) for geometry in building_geometries] pair_positions = np.arange(multiple_pairs.shape[1]) order = np.lexsort((pair_positions, -areas, multiple_pairs[0])) ordered_sources = multiple_pairs[0][order] _, first_positions = np.unique(ordered_sources, return_index=True) best_pair_positions = order[first_positions] result[multiple_pairs[0, best_pair_positions]] = names_array[multiple_pairs[1, best_pair_positions]] return result.tolist() def write_metric_csv(output_path, headers, rows): if output_path.exists() and not config.OVERWRITE: return True with output_path.open("w", newline="", encoding=config.CSV_ENCODING, errors="replace") as file: writer = csv.writer(file) writer.writerow(headers) writer.writerows(rows) return False def metric_row(values): return [ csv_text(values.get("area_type")), csv_text(values.get("area_name")), csv_text(values.get("longitude")), csv_text(values.get("latitude")), csv_text(values.get("mro_total_dl")), csv_text(values.get("rsrp_lt_neg105_dl")), csv_text(values.get("ssb_rsrp_dl")), signal_level(values.get("ssb_rsrp_yd")), signal_level(values.get("ssb_rsrp_dl")), ] def export_market_building_metrics_csv( building_conn, building_layer, building_rtree, building_info_conn, building_info_layer, building_info_rtree, market, output_path, ): rows, candidates = collect_intersecting_metric_features( building_conn, building_layer, building_rtree, market, config.CSV_SOURCE_FIELDS, ) building_geometries = [geometry for _values, geometry in rows] building_bounds = shapely.total_bounds(building_geometries) if building_geometries else None building_name_index = load_building_name_index( building_info_conn, building_info_layer, building_info_rtree, building_bounds, ) headers = [ "网格ID", "区域类型", "区域名称", "建筑名称", "经度", "纬度", "竟对采样点总", "竟对弱覆盖采样点", "竟对平均信号值", "移动信号", "竟对信号", ] csv_rows = [] matched_names = 0 building_names = match_building_info_names(building_name_index, building_geometries) for (values, _geometry), building_name in zip(rows, building_names): if building_name: matched_names += 1 common_row = metric_row(values) csv_rows.append([market.code, common_row[0], common_row[1], building_name, *common_row[2:]]) skipped = write_metric_csv(output_path, headers, csv_rows) return { "market_code": market.code, "market_name": market.name, "output": str(output_path), "candidates": candidates, "row_count": len(csv_rows), "matched_names": matched_names, "skipped": skipped, } def grid_metrics_headers(): return [ "网格ID", "区域类型", "区域名称", "经度", "纬度", "竟对采样点总", "竟对弱覆盖采样点", "竟对平均信号值", "移动信号", "竟对信号", ]