| Conditions | 24 | 
| Total Lines | 556 | 
| Code Lines | 359 | 
| Lines | 0 | 
| Ratio | 0 % | 
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like data.datasets.sanity_checks.sanitycheck_emobility_mit() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | """ | ||
| 505 | |||
| 506 | # Comparison for geothermal | ||
| 507 | |||
| 508 | input_geo_thermal = db.select_dataframe( | ||
| 509 | """SELECT carrier, | ||
| 510 | SUM(capacity::numeric) as Urban_central_geo_thermal_MW | ||
| 511 | FROM supply.egon_scenario_capacities | ||
| 512 | WHERE carrier= 'urban_central_geo_thermal' | ||
| 513 |             AND scenario_name IN ('eGon2035') | ||
| 514 | GROUP BY (carrier); | ||
| 515 | """, | ||
| 516 | warning=False, | ||
| 517 | )["urban_central_geo_thermal_mw"].values[0] | ||
| 518 | |||
| 519 | output_geo_thermal = db.select_dataframe( | ||
| 520 | """SELECT carrier, SUM(p_nom::numeric) as geo_thermal_MW | ||
| 521 | FROM grid.egon_etrago_generator | ||
| 522 | WHERE carrier= 'geo_thermal' | ||
| 523 |             AND scn_name IN ('eGon2035') | ||
| 524 | GROUP BY (carrier); | ||
| 525 | """, | ||
| 526 | warning=False, | ||
| 527 | )["geo_thermal_mw"].values[0] | ||
| 528 | |||
| 529 | e_geo_thermal = ( | ||
| 530 | round((output_geo_thermal - input_geo_thermal) / input_geo_thermal, 2) | ||
| 531 | * 100 | ||
| 532 | ) | ||
| 533 |     logger.info(f"'geothermal': {e_geo_thermal} %") | ||
| 534 | |||
| 535 | |||
| 536 | def residential_electricity_annual_sum(rtol=1e-5): | ||
| 537 | """Sanity check for dataset electricity_demand_timeseries : | ||
| 538 | Demand_Building_Assignment | ||
| 539 | |||
| 540 | Aggregate the annual demand of all census cells at NUTS3 to compare | ||
| 541 | with initial scaling parameters from DemandRegio. | ||
| 542 | """ | ||
| 543 | |||
| 544 | df_nuts3_annual_sum = db.select_dataframe( | ||
| 545 | sql=""" | ||
| 546 | SELECT dr.nuts3, dr.scenario, dr.demand_regio_sum, profiles.profile_sum | ||
| 547 | FROM ( | ||
| 548 | SELECT scenario, SUM(demand) AS profile_sum, vg250_nuts3 | ||
| 549 | FROM demand.egon_demandregio_zensus_electricity AS egon, | ||
| 550 | boundaries.egon_map_zensus_vg250 AS boundaries | ||
| 551 | Where egon.zensus_population_id = boundaries.zensus_population_id | ||
| 552 | AND sector = 'residential' | ||
| 553 | GROUP BY vg250_nuts3, scenario | ||
| 554 | ) AS profiles | ||
| 555 | JOIN ( | ||
| 556 | SELECT nuts3, scenario, sum(demand) AS demand_regio_sum | ||
| 557 | FROM demand.egon_demandregio_hh | ||
| 558 | GROUP BY year, scenario, nuts3 | ||
| 559 | ) AS dr | ||
| 560 | ON profiles.vg250_nuts3 = dr.nuts3 and profiles.scenario = dr.scenario | ||
| 561 | """ | ||
| 562 | ) | ||
| 563 | |||
| 564 | np.testing.assert_allclose( | ||
| 565 | actual=df_nuts3_annual_sum["profile_sum"], | ||
| 566 | desired=df_nuts3_annual_sum["demand_regio_sum"], | ||
| 567 | rtol=rtol, | ||
| 568 | verbose=False, | ||
| 569 | ) | ||
| 570 | |||
| 571 | logger.info( | ||
| 572 | "Aggregated annual residential electricity demand" | ||
| 573 | " matches with DemandRegio at NUTS-3." | ||
| 574 | ) | ||
| 575 | |||
| 576 | |||
| 577 | def residential_electricity_hh_refinement(rtol=1e-5): | ||
| 578 | """Sanity check for dataset electricity_demand_timeseries : | ||
| 579 | Household Demands | ||
| 580 | |||
| 581 | Check sum of aggregated household types after refinement method | ||
| 582 | was applied and compare it to the original census values.""" | ||
| 583 | |||
| 584 | df_refinement = db.select_dataframe( | ||
| 585 | sql=""" | ||
| 586 | SELECT refined.nuts3, refined.characteristics_code, | ||
| 587 | refined.sum_refined::int, census.sum_census::int | ||
| 588 | FROM( | ||
| 589 | SELECT nuts3, characteristics_code, SUM(hh_10types) as sum_refined | ||
| 590 | FROM society.egon_destatis_zensus_household_per_ha_refined | ||
| 591 | GROUP BY nuts3, characteristics_code) | ||
| 592 | AS refined | ||
| 593 | JOIN( | ||
| 594 | SELECT t.nuts3, t.characteristics_code, sum(orig) as sum_census | ||
| 595 | FROM( | ||
| 596 | SELECT nuts3, cell_id, characteristics_code, | ||
| 597 | sum(DISTINCT(hh_5types))as orig | ||
| 598 | FROM society.egon_destatis_zensus_household_per_ha_refined | ||
| 599 | GROUP BY cell_id, characteristics_code, nuts3) AS t | ||
| 600 | GROUP BY t.nuts3, t.characteristics_code ) AS census | ||
| 601 | ON refined.nuts3 = census.nuts3 | ||
| 602 | AND refined.characteristics_code = census.characteristics_code | ||
| 603 | """ | ||
| 604 | ) | ||
| 605 | |||
| 606 | np.testing.assert_allclose( | ||
| 607 | actual=df_refinement["sum_refined"], | ||
| 608 | desired=df_refinement["sum_census"], | ||
| 609 | rtol=rtol, | ||
| 610 | verbose=False, | ||
| 611 | ) | ||
| 612 | |||
| 613 |     logger.info("All Aggregated household types match at NUTS-3.") | ||
| 614 | |||
| 615 | |||
| 616 | def cts_electricity_demand_share(rtol=1e-5): | ||
| 617 | """Sanity check for dataset electricity_demand_timeseries : | ||
| 618 | CtsBuildings | ||
| 619 | |||
| 620 | Check sum of aggregated cts electricity demand share which equals to one | ||
| 621 | for every substation as the substation profile is linearly disaggregated | ||
| 622 | to all buildings.""" | ||
| 623 | |||
| 624 | with db.session_scope() as session: | ||
| 625 | cells_query = session.query(EgonCtsElectricityDemandBuildingShare) | ||
| 626 | |||
| 627 | df_demand_share = pd.read_sql( | ||
| 628 | cells_query.statement, cells_query.session.bind, index_col=None | ||
| 629 | ) | ||
| 630 | |||
| 631 | np.testing.assert_allclose( | ||
| 632 | actual=df_demand_share.groupby(["bus_id", "scenario"])[ | ||
| 633 | "profile_share" | ||
| 634 | ].sum(), | ||
| 635 | desired=1, | ||
| 636 | rtol=rtol, | ||
| 637 | verbose=False, | ||
| 638 | ) | ||
| 639 | |||
| 640 |     logger.info("The aggregated demand shares equal to one!.") | ||
| 641 | |||
| 642 | |||
| 643 | def cts_heat_demand_share(rtol=1e-5): | ||
| 644 | """Sanity check for dataset electricity_demand_timeseries | ||
| 645 | : CtsBuildings | ||
| 646 | |||
| 647 | Check sum of aggregated cts heat demand share which equals to one | ||
| 648 | for every substation as the substation profile is linearly disaggregated | ||
| 649 | to all buildings.""" | ||
| 650 | |||
| 651 | with db.session_scope() as session: | ||
| 652 | cells_query = session.query(EgonCtsHeatDemandBuildingShare) | ||
| 653 | |||
| 654 | df_demand_share = pd.read_sql( | ||
| 655 | cells_query.statement, cells_query.session.bind, index_col=None | ||
| 656 | ) | ||
| 657 | |||
| 658 | np.testing.assert_allclose( | ||
| 659 | actual=df_demand_share.groupby(["bus_id", "scenario"])[ | ||
| 660 | "profile_share" | ||
| 661 | ].sum(), | ||
| 662 | desired=1, | ||
| 663 | rtol=rtol, | ||
| 664 | verbose=False, | ||
| 665 | ) | ||
| 666 | |||
| 667 |     logger.info("The aggregated demand shares equal to one!.") | ||
| 668 | |||
| 669 | |||
| 670 | def sanitycheck_emobility_mit(): | ||
| 671 | """Execute sanity checks for eMobility: motorized individual travel | ||
| 672 | |||
| 673 | Checks data integrity for eGon2035, eGon2035_lowflex and eGon100RE scenario | ||
| 674 | using assertions: | ||
| 675 | 1. Allocated EV numbers and EVs allocated to grid districts | ||
| 676 | 2. Trip data (original inout data from simBEV) | ||
| 677 | 3. Model data in eTraGo PF tables (grid.egon_etrago_*) | ||
| 678 | |||
| 679 | Parameters | ||
| 680 | ---------- | ||
| 681 | None | ||
| 682 | |||
| 683 | Returns | ||
| 684 | ------- | ||
| 685 | None | ||
| 686 | """ | ||
| 687 | |||
| 688 | def check_ev_allocation(): | ||
| 689 | # Get target number for scenario | ||
| 690 | ev_count_target = scenario_variation_parameters["ev_count"] | ||
| 691 |         print(f"  Target count: {str(ev_count_target)}") | ||
| 692 | |||
| 693 | # Get allocated numbers | ||
| 694 |         ev_counts_dict = {} | ||
| 695 | with db.session_scope() as session: | ||
| 696 | for table, level in zip( | ||
| 697 | [ | ||
| 698 | EgonEvCountMvGridDistrict, | ||
| 699 | EgonEvCountMunicipality, | ||
| 700 | EgonEvCountRegistrationDistrict, | ||
| 701 | ], | ||
| 702 | ["Grid District", "Municipality", "Registration District"], | ||
| 703 | ): | ||
| 704 | query = session.query( | ||
| 705 | func.sum( | ||
| 706 | table.bev_mini | ||
| 707 | + table.bev_medium | ||
| 708 | + table.bev_luxury | ||
| 709 | + table.phev_mini | ||
| 710 | + table.phev_medium | ||
| 711 | + table.phev_luxury | ||
| 712 |                     ).label("ev_count") | ||
| 713 | ).filter( | ||
| 714 | table.scenario == scenario_name, | ||
| 715 | table.scenario_variation == scenario_var_name, | ||
| 716 | ) | ||
| 717 | |||
| 718 | ev_counts = pd.read_sql( | ||
| 719 | query.statement, query.session.bind, index_col=None | ||
| 720 | ) | ||
| 721 | ev_counts_dict[level] = ev_counts.iloc[0].ev_count | ||
| 722 | print( | ||
| 723 |                     f"    Count table: Total count for level {level} " | ||
| 724 |                     f"(table: {table.__table__}): " | ||
| 725 |                     f"{str(ev_counts_dict[level])}" | ||
| 726 | ) | ||
| 727 | |||
| 728 | # Compare with scenario target (only if not in testmode) | ||
| 729 | if TESTMODE_OFF: | ||
| 730 | for level, count in ev_counts_dict.items(): | ||
| 731 | np.testing.assert_allclose( | ||
| 732 | count, | ||
| 733 | ev_count_target, | ||
| 734 | rtol=0.0001, | ||
| 735 |                     err_msg=f"EV numbers in {level} seems to be flawed.", | ||
| 736 | ) | ||
| 737 | else: | ||
| 738 |             print("    Testmode is on, skipping sanity check...") | ||
| 739 | |||
| 740 | # Get allocated EVs in grid districts | ||
| 741 | with db.session_scope() as session: | ||
| 742 | query = session.query( | ||
| 743 | func.count(EgonEvMvGridDistrict.egon_ev_pool_ev_id).label( | ||
| 744 | "ev_count" | ||
| 745 | ), | ||
| 746 | ).filter( | ||
| 747 | EgonEvMvGridDistrict.scenario == scenario_name, | ||
| 748 | EgonEvMvGridDistrict.scenario_variation == scenario_var_name, | ||
| 749 | ) | ||
| 750 | ev_count_alloc = ( | ||
| 751 | pd.read_sql(query.statement, query.session.bind, index_col=None) | ||
| 752 | .iloc[0] | ||
| 753 | .ev_count | ||
| 754 | ) | ||
| 755 | print( | ||
| 756 | f" EVs allocated to Grid Districts " | ||
| 757 |             f"(table: {EgonEvMvGridDistrict.__table__}) total count: " | ||
| 758 |             f"{str(ev_count_alloc)}" | ||
| 759 | ) | ||
| 760 | |||
| 761 | # Compare with scenario target (only if not in testmode) | ||
| 762 | if TESTMODE_OFF: | ||
| 763 | np.testing.assert_allclose( | ||
| 764 | ev_count_alloc, | ||
| 765 | ev_count_target, | ||
| 766 | rtol=0.0001, | ||
| 767 | err_msg=( | ||
| 768 | "EV numbers allocated to Grid Districts seems to be flawed." | ||
| 769 | ), | ||
| 770 | ) | ||
| 771 | else: | ||
| 772 |             print("    Testmode is on, skipping sanity check...") | ||
| 773 | |||
| 774 | return ev_count_alloc | ||
| 775 | |||
| 776 | def check_trip_data(): | ||
| 777 | # Check if trips start at timestep 0 and have a max. of 35040 steps | ||
| 778 | # (8760h in 15min steps) | ||
| 779 |         print("  Checking timeranges...") | ||
| 780 | with db.session_scope() as session: | ||
| 781 | query = session.query( | ||
| 782 |                 func.count(EgonEvTrip.event_id).label("cnt") | ||
| 783 | ).filter( | ||
| 784 | or_( | ||
| 785 | and_( | ||
| 786 | EgonEvTrip.park_start > 0, | ||
| 787 | EgonEvTrip.simbev_event_id == 0, | ||
| 788 | ), | ||
| 789 | EgonEvTrip.park_end | ||
| 790 | > (60 / int(meta_run_config.stepsize)) * 8760, | ||
| 791 | ), | ||
| 792 | EgonEvTrip.scenario == scenario_name, | ||
| 793 | ) | ||
| 794 | invalid_trips = pd.read_sql( | ||
| 795 | query.statement, query.session.bind, index_col=None | ||
| 796 | ) | ||
| 797 | np.testing.assert_equal( | ||
| 798 | invalid_trips.iloc[0].cnt, | ||
| 799 | 0, | ||
| 800 | err_msg=( | ||
| 801 |                 f"{str(invalid_trips.iloc[0].cnt)} trips in table " | ||
| 802 |                 f"{EgonEvTrip.__table__} have invalid timesteps." | ||
| 803 | ), | ||
| 804 | ) | ||
| 805 | |||
| 806 | # Check if charging demand can be covered by available charging energy | ||
| 807 | # while parking | ||
| 808 |         print("  Compare charging demand with available power...") | ||
| 809 | with db.session_scope() as session: | ||
| 810 | query = session.query( | ||
| 811 |                 func.count(EgonEvTrip.event_id).label("cnt") | ||
| 812 | ).filter( | ||
| 813 | func.round( | ||
| 814 | cast( | ||
| 815 | (EgonEvTrip.park_end - EgonEvTrip.park_start + 1) | ||
| 816 | * EgonEvTrip.charging_capacity_nominal | ||
| 817 | * (int(meta_run_config.stepsize) / 60), | ||
| 818 | Numeric, | ||
| 819 | ), | ||
| 820 | 3, | ||
| 821 | ) | ||
| 822 | < cast(EgonEvTrip.charging_demand, Numeric), | ||
| 823 | EgonEvTrip.scenario == scenario_name, | ||
| 824 | ) | ||
| 825 | invalid_trips = pd.read_sql( | ||
| 826 | query.statement, query.session.bind, index_col=None | ||
| 827 | ) | ||
| 828 | np.testing.assert_equal( | ||
| 829 | invalid_trips.iloc[0].cnt, | ||
| 830 | 0, | ||
| 831 | err_msg=( | ||
| 832 |                 f"In {str(invalid_trips.iloc[0].cnt)} trips (table: " | ||
| 833 |                 f"{EgonEvTrip.__table__}) the charging demand cannot be " | ||
| 834 | f"covered by available charging power." | ||
| 835 | ), | ||
| 836 | ) | ||
| 837 | |||
| 838 | def check_model_data(): | ||
| 839 | # Check if model components were fully created | ||
| 840 |         print("  Check if all model components were created...") | ||
| 841 | # Get MVGDs which got EV allocated | ||
| 842 | with db.session_scope() as session: | ||
| 843 | query = ( | ||
| 844 | session.query( | ||
| 845 | EgonEvMvGridDistrict.bus_id, | ||
| 846 | ) | ||
| 847 | .filter( | ||
| 848 | EgonEvMvGridDistrict.scenario == scenario_name, | ||
| 849 | EgonEvMvGridDistrict.scenario_variation | ||
| 850 | == scenario_var_name, | ||
| 851 | ) | ||
| 852 | .group_by(EgonEvMvGridDistrict.bus_id) | ||
| 853 | ) | ||
| 854 | mvgds_with_ev = ( | ||
| 855 | pd.read_sql(query.statement, query.session.bind, index_col=None) | ||
| 856 | .bus_id.sort_values() | ||
| 857 | .to_list() | ||
| 858 | ) | ||
| 859 | |||
| 860 | # Load model components | ||
| 861 | with db.session_scope() as session: | ||
| 862 | query = ( | ||
| 863 | session.query( | ||
| 864 |                     EgonPfHvLink.bus0.label("mvgd_bus_id"), | ||
| 865 |                     EgonPfHvLoad.bus.label("emob_bus_id"), | ||
| 866 |                     EgonPfHvLoad.load_id.label("load_id"), | ||
| 867 |                     EgonPfHvStore.store_id.label("store_id"), | ||
| 868 | ) | ||
| 869 | .select_from(EgonPfHvLoad, EgonPfHvStore) | ||
| 870 | .join( | ||
| 871 | EgonPfHvLoadTimeseries, | ||
| 872 | EgonPfHvLoadTimeseries.load_id == EgonPfHvLoad.load_id, | ||
| 873 | ) | ||
| 874 | .join( | ||
| 875 | EgonPfHvStoreTimeseries, | ||
| 876 | EgonPfHvStoreTimeseries.store_id == EgonPfHvStore.store_id, | ||
| 877 | ) | ||
| 878 | .filter( | ||
| 879 | EgonPfHvLoad.carrier == "land transport EV", | ||
| 880 | EgonPfHvLoad.scn_name == scenario_name, | ||
| 881 | EgonPfHvLoadTimeseries.scn_name == scenario_name, | ||
| 882 | EgonPfHvStore.carrier == "battery storage", | ||
| 883 | EgonPfHvStore.scn_name == scenario_name, | ||
| 884 | EgonPfHvStoreTimeseries.scn_name == scenario_name, | ||
| 885 | EgonPfHvLink.scn_name == scenario_name, | ||
| 886 | EgonPfHvLink.bus1 == EgonPfHvLoad.bus, | ||
| 887 | EgonPfHvLink.bus1 == EgonPfHvStore.bus, | ||
| 888 | ) | ||
| 889 | ) | ||
| 890 | model_components = pd.read_sql( | ||
| 891 | query.statement, query.session.bind, index_col=None | ||
| 892 | ) | ||
| 893 | |||
| 894 | # Check number of buses with model components connected | ||
| 895 | mvgd_buses_with_ev = model_components.loc[ | ||
| 896 | model_components.mvgd_bus_id.isin(mvgds_with_ev) | ||
| 897 | ] | ||
| 898 | np.testing.assert_equal( | ||
| 899 | len(mvgds_with_ev), | ||
| 900 | len(mvgd_buses_with_ev), | ||
| 901 | err_msg=( | ||
| 902 | f"Number of Grid Districts with connected model components " | ||
| 903 |                 f"({str(len(mvgd_buses_with_ev))} in tables egon_etrago_*) " | ||
| 904 | f"differ from number of Grid Districts that got EVs " | ||
| 905 |                 f"allocated ({len(mvgds_with_ev)} in table " | ||
| 906 |                 f"{EgonEvMvGridDistrict.__table__})." | ||
| 907 | ), | ||
| 908 | ) | ||
| 909 | |||
| 910 | # Check if all required components exist (if no id is NaN) | ||
| 911 | np.testing.assert_equal( | ||
| 912 | model_components.drop_duplicates().isna().any().any(), | ||
| 913 | False, | ||
| 914 | err_msg=( | ||
| 915 | f"Some components are missing (see True values): " | ||
| 916 |                 f"{model_components.drop_duplicates().isna().any()}" | ||
| 917 | ), | ||
| 918 | ) | ||
| 919 | |||
| 920 | # Get all model timeseries | ||
| 921 |         print("  Loading model timeseries...") | ||
| 922 | # Get all model timeseries | ||
| 923 |         model_ts_dict = { | ||
| 924 |             "Load": { | ||
| 925 | "carrier": "land transport EV", | ||
| 926 | "table": EgonPfHvLoad, | ||
| 927 | "table_ts": EgonPfHvLoadTimeseries, | ||
| 928 | "column_id": "load_id", | ||
| 929 | "columns_ts": ["p_set"], | ||
| 930 | "ts": None, | ||
| 931 | }, | ||
| 932 |             "Link": { | ||
| 933 | "carrier": "BEV charger", | ||
| 934 | "table": EgonPfHvLink, | ||
| 935 | "table_ts": EgonPfHvLinkTimeseries, | ||
| 936 | "column_id": "link_id", | ||
| 937 | "columns_ts": ["p_max_pu"], | ||
| 938 | "ts": None, | ||
| 939 | }, | ||
| 940 |             "Store": { | ||
| 941 | "carrier": "battery storage", | ||
| 942 | "table": EgonPfHvStore, | ||
| 943 | "table_ts": EgonPfHvStoreTimeseries, | ||
| 944 | "column_id": "store_id", | ||
| 945 | "columns_ts": ["e_min_pu", "e_max_pu"], | ||
| 946 | "ts": None, | ||
| 947 | }, | ||
| 948 | } | ||
| 949 | |||
| 950 | with db.session_scope() as session: | ||
| 951 | for node, attrs in model_ts_dict.items(): | ||
| 952 |                 print(f"    Loading {node} timeseries...") | ||
| 953 | subquery = ( | ||
| 954 | session.query( | ||
| 955 | getattr(attrs["table"], attrs["column_id"]) | ||
| 956 | ) | ||
| 957 | .filter(attrs["table"].carrier == attrs["carrier"]) | ||
| 958 | .filter(attrs["table"].scn_name == scenario_name) | ||
| 959 | .subquery() | ||
| 960 | ) | ||
| 961 | |||
| 962 | cols = [ | ||
| 963 | getattr(attrs["table_ts"], c) for c in attrs["columns_ts"] | ||
| 964 | ] | ||
| 965 | query = session.query( | ||
| 966 | getattr(attrs["table_ts"], attrs["column_id"]), *cols | ||
| 967 | ).filter( | ||
| 968 | getattr(attrs["table_ts"], attrs["column_id"]).in_( | ||
| 969 | subquery | ||
| 970 | ), | ||
| 971 | attrs["table_ts"].scn_name == scenario_name, | ||
| 972 | ) | ||
| 973 | attrs["ts"] = pd.read_sql( | ||
| 974 | query.statement, | ||
| 975 | query.session.bind, | ||
| 976 | index_col=attrs["column_id"], | ||
| 977 | ) | ||
| 978 | |||
| 979 | # Check if all timeseries have 8760 steps | ||
| 980 |         print("    Checking timeranges...") | ||
| 981 | for node, attrs in model_ts_dict.items(): | ||
| 982 | for col in attrs["columns_ts"]: | ||
| 983 | ts = attrs["ts"] | ||
| 984 | invalid_ts = ts.loc[ts[col].apply(lambda _: len(_)) != 8760][ | ||
| 985 | col | ||
| 986 | ].apply(len) | ||
| 987 | np.testing.assert_equal( | ||
| 988 | len(invalid_ts), | ||
| 989 | 0, | ||
| 990 | err_msg=( | ||
| 991 |                         f"{str(len(invalid_ts))} rows in timeseries do not " | ||
| 992 | f"have 8760 timesteps. Table: " | ||
| 993 |                         f"{attrs['table_ts'].__table__}, Column: {col}, IDs: " | ||
| 994 |                         f"{str(list(invalid_ts.index))}" | ||
| 995 | ), | ||
| 996 | ) | ||
| 997 | |||
| 998 | # Compare total energy demand in model with some approximate values | ||
| 999 | # (per EV: 14,000 km/a, 0.17 kWh/km) | ||
| 1000 |         print("  Checking energy demand in model...") | ||
| 1001 | total_energy_model = ( | ||
| 1002 | model_ts_dict["Load"]["ts"].p_set.apply(lambda _: sum(_)).sum() | ||
| 1003 | / 1e6 | ||
| 1004 | ) | ||
| 1005 |         print(f"    Total energy amount in model: {total_energy_model} TWh") | ||
| 1006 | total_energy_scenario_approx = ev_count_alloc * 14000 * 0.17 / 1e9 | ||
| 1007 | print( | ||
| 1008 | f" Total approximated energy amount in scenario: " | ||
| 1009 |             f"{total_energy_scenario_approx} TWh" | ||
| 1010 | ) | ||
| 1011 | np.testing.assert_allclose( | ||
| 1012 | total_energy_model, | ||
| 1013 | total_energy_scenario_approx, | ||
| 1014 | rtol=0.1, | ||
| 1015 | err_msg=( | ||
| 1016 | "The total energy amount in the model deviates heavily " | ||
| 1017 | "from the approximated value for current scenario." | ||
| 1018 | ), | ||
| 1019 | ) | ||
| 1020 | |||
| 1021 | # Compare total storage capacity | ||
| 1022 |         print("  Checking storage capacity...") | ||
| 1023 | # Load storage capacities from model | ||
| 1024 | with db.session_scope() as session: | ||
| 1025 | query = session.query( | ||
| 1026 |                 func.sum(EgonPfHvStore.e_nom).label("e_nom") | ||
| 1027 | ).filter( | ||
| 1028 | EgonPfHvStore.scn_name == scenario_name, | ||
| 1029 | EgonPfHvStore.carrier == "battery storage", | ||
| 1030 | ) | ||
| 1031 | storage_capacity_model = ( | ||
| 1032 | pd.read_sql( | ||
| 1033 | query.statement, query.session.bind, index_col=None | ||
| 1034 | ).e_nom.sum() | ||
| 1035 | / 1e3 | ||
| 1036 | ) | ||
| 1037 | print( | ||
| 1038 |             f"    Total storage capacity ({EgonPfHvStore.__table__}): " | ||
| 1039 |             f"{round(storage_capacity_model, 1)} GWh" | ||
| 1040 | ) | ||
| 1041 | |||
| 1042 | # Load occurences of each EV | ||
| 1043 | with db.session_scope() as session: | ||
| 1044 | query = ( | ||
| 1045 | session.query( | ||
| 1046 | EgonEvMvGridDistrict.bus_id, | ||
| 1047 | EgonEvPool.type, | ||
| 1048 | func.count(EgonEvMvGridDistrict.egon_ev_pool_ev_id).label( | ||
| 1049 | "count" | ||
| 1050 | ), | ||
| 1051 | ) | ||
| 1052 | .join( | ||
| 1053 | EgonEvPool, | ||
| 1054 | EgonEvPool.ev_id | ||
| 1055 | == EgonEvMvGridDistrict.egon_ev_pool_ev_id, | ||
| 1056 | ) | ||
| 1057 | .filter( | ||
| 1058 | EgonEvMvGridDistrict.scenario == scenario_name, | ||
| 1059 | EgonEvMvGridDistrict.scenario_variation | ||
| 1060 | == scenario_var_name, | ||
| 1061 | EgonEvPool.scenario == scenario_name, | ||
| 1226 |