|
14 | 14 | import os |
15 | 15 | import zipfile |
16 | 16 | from io import BytesIO |
| 17 | +import io as io |
| 18 | +import csv as csv |
17 | 19 |
|
18 | 20 | watershed = Blueprint('watershed', __name__) |
19 | 21 |
|
@@ -350,6 +352,219 @@ def get_watershed_report_by_id(id): |
350 | 352 |
|
351 | 353 | return response, 200 |
352 | 354 |
|
| 355 | +@watershed.route('/<int:id>/report/csv', methods=['GET']) |
| 356 | +def get_watershed_report_zip_by_id(id): |
| 357 | + sections_param = request.args.get('sections', '') |
| 358 | + requested_sections = set(s.strip() for s in sections_param.split(',') if s.strip()) if sections_param else set() |
| 359 | + |
| 360 | + region_id = app.db.get_watershed_region_by_id(watershed_feature_id=id)['region_id'] |
| 361 | + |
| 362 | + watershed_metadata = app.db.get_watershed_report_by_id(watershed_feature_id=id, region_id=region_id) |
| 363 | + |
| 364 | + if not watershed_metadata or not watershed_metadata.get("watershed_metadata"): |
| 365 | + return {"error": "Watershed not found"}, 404 |
| 366 | + |
| 367 | + zip_stream = BytesIO() |
| 368 | + months = ["January", "February", "March", "April", "May", "June", |
| 369 | + "July", "August", "September", "October", "November", "December"] |
| 370 | + |
| 371 | + with zipfile.ZipFile(zip_stream, "w", zipfile.ZIP_DEFLATED) as zip_file: |
| 372 | + |
| 373 | + if not requested_sections or 'annualHydrology' in requested_sections: |
| 374 | + annual_hydrology = app.db.get_watershed_annual_hydrology_by_id(watershed_feature_id=id) |
| 375 | + if annual_hydrology["results"]: |
| 376 | + readability_map = { |
| 377 | + 'area_km2': 'Area (km²)', |
| 378 | + 'mad_m3s': 'Mean Annual Discharge (MAD, m³/s)', |
| 379 | + 'allocs_m3s': 'Allocations (average, m³/s)', |
| 380 | + 'allocs_pct': 'Allocations (average, % of MAD)', |
| 381 | + 'rr': 'Reserves and Restrictions', |
| 382 | + 'runoff_m3yr': 'Volume Runoff (m³/yr)', |
| 383 | + 'allocs_m3yr': 'Volume Allocations (m³/yr)', |
| 384 | + 'seasonal_sens': 'Seasonal Flow Sensitivity', |
| 385 | + } |
| 386 | + flattened_data = [ |
| 387 | + { |
| 388 | + "Metric": readability_map[key], |
| 389 | + "Query Watershed Value": values.get("query"), |
| 390 | + "Downstream Watershed Value": values.get("downstream") |
| 391 | + } |
| 392 | + for key, values in annual_hydrology["results"].items() |
| 393 | + if isinstance(values, dict) |
| 394 | + ] |
| 395 | + if flattened_data: |
| 396 | + zip_file.writestr("annual_hydrology.csv", pl.DataFrame(flattened_data).write_csv()) |
| 397 | + |
| 398 | + if not requested_sections or 'monthlyHydrology' in requested_sections: |
| 399 | + query_monthly = app.db.get_watershed_monthly_hydrology_by_id( |
| 400 | + watershed_feature_id=id, in_basin='query', region_id=region_id) |
| 401 | + downstream_monthly = app.db.get_watershed_monthly_hydrology_by_id( |
| 402 | + watershed_feature_id=id, in_basin='downstream', region_id=region_id) |
| 403 | + if query_monthly["results"] or downstream_monthly["results"]: |
| 404 | + query_results = query_monthly["results"] |
| 405 | + downstream_results = downstream_monthly["results"] |
| 406 | + flattened_data = [ |
| 407 | + { |
| 408 | + "Month": month, |
| 409 | + "Metric": metric_name, |
| 410 | + "Query Watershed Value": query_results.get(qk, [])[i] if i < len(query_results.get(qk, [])) else None, |
| 411 | + "Downstream Watershed Value": downstream_results.get(dk, [])[i] if i < len(downstream_results.get(dk, [])) else None, |
| 412 | + } |
| 413 | + for i, month in enumerate(months) |
| 414 | + for metric_name, qk, dk in [ |
| 415 | + ("Existing Allocations (m³/s)", "ea_all", "ea_all"), |
| 416 | + ("Monthly Discharge (m³/s)", "mad_m3s", "mad_m3s"), |
| 417 | + ] |
| 418 | + ] |
| 419 | + zip_file.writestr("monthly_hydrology.csv", pl.DataFrame(flattened_data).write_csv()) |
| 420 | + |
| 421 | + if not requested_sections or 'allocationsByIndustry' in requested_sections: |
| 422 | + industry_allocs = app.db.get_watershed_industry_allocations_by_id(watershed_feature_id=id) |
| 423 | + if industry_allocs["results"]: |
| 424 | + flattened_data = [ |
| 425 | + { |
| 426 | + "Industry Type": industry, |
| 427 | + "Surface Water Licence (m³)": allocations.get("sw_long"), |
| 428 | + "Surface Water STUA (m³)": allocations.get("sw_short"), |
| 429 | + "Ground Water Licence (m³)": allocations.get("gw_long"), |
| 430 | + "Ground Water STUA (m³)": allocations.get("gw_short") |
| 431 | + } |
| 432 | + for industry, allocations in industry_allocs["results"].items() |
| 433 | + ] |
| 434 | + zip_file.writestr("allocations_by_industry.csv", pl.DataFrame(flattened_data).write_csv()) |
| 435 | + |
| 436 | + if not requested_sections or 'allocations' in requested_sections: |
| 437 | + allocations = app.db.get_watershed_allocations_by_id(watershed_feature_id=id, in_basin='query') |
| 438 | + if allocations: |
| 439 | + zip_file.writestr("allocations.csv", pl.DataFrame(allocations, infer_schema_length=10000).write_csv()) |
| 440 | + |
| 441 | + if not requested_sections or 'hydrologicVariability' in requested_sections: |
| 442 | + if region_id in (5, 6): |
| 443 | + hydrologic_var = app.db.get_watershed_hydrologic_variability_by_id(watershed_feature_id=id) |
| 444 | + if hydrologic_var: |
| 445 | + rows = [ |
| 446 | + { |
| 447 | + "Month": months[row["month"] - 1], |
| 448 | + "Candidate": f"Candidate {cand_num}", |
| 449 | + "Station": mv.get(f"c{cand_num}"), |
| 450 | + "10th Percentile (m³/s)": dict(zip(mv.get("percs", []), mv.get(f"q_m3s_c{cand_num}", []))).get(10), |
| 451 | + "25th Percentile (m³/s)": dict(zip(mv.get("percs", []), mv.get(f"q_m3s_c{cand_num}", []))).get(25), |
| 452 | + "50th Percentile (m³/s)": dict(zip(mv.get("percs", []), mv.get(f"q_m3s_c{cand_num}", []))).get(50), |
| 453 | + "75th Percentile (m³/s)": dict(zip(mv.get("percs", []), mv.get(f"q_m3s_c{cand_num}", []))).get(75), |
| 454 | + "90th Percentile (m³/s)": dict(zip(mv.get("percs", []), mv.get(f"q_m3s_c{cand_num}", []))).get(90), |
| 455 | + } |
| 456 | + for row in hydrologic_var |
| 457 | + for cand_num in range(1, 4) |
| 458 | + for mv in [row["month_value"]] |
| 459 | + if mv.get(f"c{cand_num}") |
| 460 | + ] |
| 461 | + if rows: |
| 462 | + zip_file.writestr("hydrologic_variability.csv", pl.DataFrame(rows).write_csv()) |
| 463 | + candidate_metadata = app.db.get_watershed_candidates_by_id(watershed_feature_id=id) |
| 464 | + if candidate_metadata: |
| 465 | + |
| 466 | + distance_rows = [ |
| 467 | + { |
| 468 | + "Candidate ID": row["candidate_id"], |
| 469 | + "Candidate Name": row["candidate_name"], |
| 470 | + "Area (km²)": row["candidate_area_km2"], |
| 471 | + "Month": months[month_idx], |
| 472 | + "Monthly Flow Ratio": row["candidate_month_value"].get(f"month{month_idx+1:02d}"), |
| 473 | + } |
| 474 | + for row in candidate_metadata |
| 475 | + for month_idx in range(12) |
| 476 | + ] |
| 477 | + if distance_rows: |
| 478 | + zip_file.writestr( |
| 479 | + "hydrologic_variability_candidate_distance_values.csv", |
| 480 | + pl.DataFrame(distance_rows).write_csv() |
| 481 | + ) |
| 482 | + |
| 483 | + climate_rows = [ |
| 484 | + { |
| 485 | + "Candidate ID": row["candidate_id"], |
| 486 | + "Candidate Name": row["candidate_name"], |
| 487 | + "Latitude": row["candidate_climate_data"].get("lat"), |
| 488 | + "Longitude": row["candidate_climate_data"].get("lon"), |
| 489 | + "Upstream Area (km²)": row["candidate_climate_data"].get("upstream_area_km2"), |
| 490 | + "Min Elevation (m)": row["candidate_climate_data"].get("min_elev"), |
| 491 | + "Avg Elevation (m)": row["candidate_climate_data"].get("avg_elev"), |
| 492 | + "Max Elevation (m)": row["candidate_climate_data"].get("max_elev"), |
| 493 | + "Month": months[month_idx], |
| 494 | + "Precipitation (mm)": row["candidate_climate_data"].get("ppt", [])[month_idx] if month_idx < len(row["candidate_climate_data"].get("ppt", [])) else None, |
| 495 | + "Mean Temperature (°C)": row["candidate_climate_data"].get("tave", [])[month_idx] if month_idx < len(row["candidate_climate_data"].get("tave", [])) else None, |
| 496 | + "Snow (mm)": row["candidate_climate_data"].get("pas", [])[month_idx] if month_idx < len(row["candidate_climate_data"].get("pas", [])) else None, |
| 497 | + } |
| 498 | + for row in candidate_metadata |
| 499 | + for month_idx in range(12) |
| 500 | + ] |
| 501 | + if climate_rows: |
| 502 | + zip_file.writestr( |
| 503 | + "hydrologic_variability_candidate_climate_data.csv", |
| 504 | + pl.DataFrame(climate_rows).write_csv() |
| 505 | + ) |
| 506 | + elif region_id == 4: |
| 507 | + hydrologic_var = app.db.get_kwt_hydrologic_variability_by_id(watershed_feature_id = id) |
| 508 | + if hydrologic_var: |
| 509 | + hv = hydrologic_var['hydrological_variability'] |
| 510 | + return_periods = [6, 20, 50, 80] |
| 511 | + |
| 512 | + rows = [ |
| 513 | + { |
| 514 | + "Month": months[month_idx], |
| 515 | + "Return Period (years)": rp, |
| 516 | + "10th Percentile (m³/s)": hv.get(f"nc_p10_m{month_idx+1:02d}_{rp:02d}"), |
| 517 | + "25th Percentile (m³/s)": hv.get(f"nc_p25_m{month_idx+1:02d}_{rp:02d}"), |
| 518 | + "50th Percentile (m³/s)": hv.get(f"nc_p50_m{month_idx+1:02d}_{rp:02d}"), |
| 519 | + "75th Percentile (m³/s)": hv.get(f"nc_p75_m{month_idx+1:02d}_{rp:02d}"), |
| 520 | + "90th Percentile (m³/s)": hv.get(f"nc_p90_m{month_idx+1:02d}_{rp:02d}"), |
| 521 | + } |
| 522 | + for month_idx in range(12) |
| 523 | + for rp in return_periods |
| 524 | + ] |
| 525 | + |
| 526 | + if rows: |
| 527 | + zip_file.writestr("future_hydrologic_variability.csv", pl.DataFrame(rows).write_csv()) |
| 528 | + |
| 529 | + |
| 530 | + if not requested_sections or 'climate' in requested_sections: |
| 531 | + climate_data = watershed_metadata.get("watershed_metadata", {}) |
| 532 | + if climate_data: |
| 533 | + flattened_data = [ |
| 534 | + { |
| 535 | + "Month": month, |
| 536 | + "Precipitation (mm) historical": climate_data.get("ppt_monthly_hist", [])[i] if i < len(climate_data.get("ppt_monthly_hist", [])) else None, |
| 537 | + "Precipitation (mm) future high": climate_data.get("ppt_monthly_future_max", [])[i] if i < len(climate_data.get("ppt_monthly_future_max", [])) else None, |
| 538 | + "Precipitation (mm) future low": climate_data.get("ppt_monthly_future_min", [])[i] if i < len(climate_data.get("ppt_monthly_future_min", [])) else None, |
| 539 | + "Temperature (°C) historical": climate_data.get("tave_monthly_hist", [])[i] if i < len(climate_data.get("tave_monthly_hist", [])) else None, |
| 540 | + "Temperature (°C) future high": climate_data.get("tave_monthly_future_max", [])[i] if i < len(climate_data.get("tave_monthly_future_max", [])) else None, |
| 541 | + "Temperature (°C) future low": climate_data.get("tave_monthly_future_min", [])[i] if i < len(climate_data.get("tave_monthly_future_min", [])) else None, |
| 542 | + "Snow (mm) historical": climate_data.get("pas_monthly_hist", [])[i] if i < len(climate_data.get("pas_monthly_hist", [])) else None, |
| 543 | + "Snow (mm) future high": climate_data.get("pas_monthly_future_max", [])[i] if i < len(climate_data.get("pas_monthly_future_max", [])) else None, |
| 544 | + "Snow (mm) future low": climate_data.get("pas_monthly_future_min", [])[i] if i < len(climate_data.get("pas_monthly_future_min", [])) else None, |
| 545 | + } |
| 546 | + for i, month in enumerate(months) |
| 547 | + ] |
| 548 | + zip_file.writestr("climate.csv", pl.DataFrame(flattened_data).write_csv()) |
| 549 | + |
| 550 | + if not requested_sections or 'topography' in requested_sections: |
| 551 | + if region_id in (5, 6): |
| 552 | + df = pl.DataFrame({ |
| 553 | + "Cumulative %": list(range(1, len(watershed_metadata.get("elevation_steep", [])) + 1)), |
| 554 | + "Elevation Steep (M)": watershed_metadata.get("elevation_steep"), |
| 555 | + "Elevation Flat (M)": watershed_metadata.get("elevation_flat"), |
| 556 | + }) |
| 557 | + else: |
| 558 | + df = pl.DataFrame({ |
| 559 | + "Cumulative %": list(range(1, len(watershed_metadata.get("elevs", [])) + 1)), |
| 560 | + "Elevation (M)": watershed_metadata.get("elevs"), |
| 561 | + }) |
| 562 | + zip_file.writestr("topography.csv", df.write_csv()) |
| 563 | + |
| 564 | + zip_stream.seek(0) |
| 565 | + return send_file(zip_stream, mimetype="application/zip", as_attachment=True, |
| 566 | + download_name=f"watershed_{id}_report.zip") |
| 567 | + |
353 | 568 |
|
354 | 569 | @watershed.route('/<int:id>/report/download_watershed/<string:format>', methods=['GET']) |
355 | 570 | def get_watershed_polygon_as_file(id, format): |
|
0 commit comments