| Conditions | 24 | 
| Total Lines | 555 | 
| Code Lines | 358 | 
| 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 | """  | 
            ||
| 794 | def sanitycheck_emobility_mit():  | 
            ||
| 795 | """Execute sanity checks for eMobility: motorized individual travel  | 
            ||
| 796 | |||
| 797 | Checks data integrity for eGon2035, eGon2035_lowflex and eGon100RE scenario  | 
            ||
| 798 | using assertions:  | 
            ||
| 799 | 1. Allocated EV numbers and EVs allocated to grid districts  | 
            ||
| 800 | 2. Trip data (original inout data from simBEV)  | 
            ||
| 801 | 3. Model data in eTraGo PF tables (grid.egon_etrago_*)  | 
            ||
| 802 | |||
| 803 | Parameters  | 
            ||
| 804 | ----------  | 
            ||
| 805 | None  | 
            ||
| 806 | |||
| 807 | Returns  | 
            ||
| 808 | -------  | 
            ||
| 809 | None  | 
            ||
| 810 | """  | 
            ||
| 811 | |||
| 812 | def check_ev_allocation():  | 
            ||
| 813 | # Get target number for scenario  | 
            ||
| 814 | ev_count_target = scenario_variation_parameters["ev_count"]  | 
            ||
| 815 |         print(f"  Target count: {str(ev_count_target)}") | 
            ||
| 816 | |||
| 817 | # Get allocated numbers  | 
            ||
| 818 |         ev_counts_dict = {} | 
            ||
| 819 | with db.session_scope() as session:  | 
            ||
| 820 | for table, level in zip(  | 
            ||
| 821 | [  | 
            ||
| 822 | EgonEvCountMvGridDistrict,  | 
            ||
| 823 | EgonEvCountMunicipality,  | 
            ||
| 824 | EgonEvCountRegistrationDistrict,  | 
            ||
| 825 | ],  | 
            ||
| 826 | ["Grid District", "Municipality", "Registration District"],  | 
            ||
| 827 | ):  | 
            ||
| 828 | query = session.query(  | 
            ||
| 829 | func.sum(  | 
            ||
| 830 | table.bev_mini  | 
            ||
| 831 | + table.bev_medium  | 
            ||
| 832 | + table.bev_luxury  | 
            ||
| 833 | + table.phev_mini  | 
            ||
| 834 | + table.phev_medium  | 
            ||
| 835 | + table.phev_luxury  | 
            ||
| 836 |                     ).label("ev_count") | 
            ||
| 837 | ).filter(  | 
            ||
| 838 | table.scenario == scenario_name,  | 
            ||
| 839 | table.scenario_variation == scenario_var_name,  | 
            ||
| 840 | )  | 
            ||
| 841 | |||
| 842 | ev_counts = pd.read_sql(  | 
            ||
| 843 | query.statement, query.session.bind, index_col=None  | 
            ||
| 844 | )  | 
            ||
| 845 | ev_counts_dict[level] = ev_counts.iloc[0].ev_count  | 
            ||
| 846 | print(  | 
            ||
| 847 |                     f"    Count table: Total count for level {level} " | 
            ||
| 848 |                     f"(table: {table.__table__}): " | 
            ||
| 849 |                     f"{str(ev_counts_dict[level])}" | 
            ||
| 850 | )  | 
            ||
| 851 | |||
| 852 | # Compare with scenario target (only if not in testmode)  | 
            ||
| 853 | if TESTMODE_OFF:  | 
            ||
| 854 | for level, count in ev_counts_dict.items():  | 
            ||
| 855 | np.testing.assert_allclose(  | 
            ||
| 856 | count,  | 
            ||
| 857 | ev_count_target,  | 
            ||
| 858 | rtol=0.0001,  | 
            ||
| 859 |                     err_msg=f"EV numbers in {level} seems to be flawed.", | 
            ||
| 860 | )  | 
            ||
| 861 | else:  | 
            ||
| 862 |             print("    Testmode is on, skipping sanity check...") | 
            ||
| 863 | |||
| 864 | # Get allocated EVs in grid districts  | 
            ||
| 865 | with db.session_scope() as session:  | 
            ||
| 866 | query = session.query(  | 
            ||
| 867 | func.count(EgonEvMvGridDistrict.egon_ev_pool_ev_id).label(  | 
            ||
| 868 | "ev_count"  | 
            ||
| 869 | ),  | 
            ||
| 870 | ).filter(  | 
            ||
| 871 | EgonEvMvGridDistrict.scenario == scenario_name,  | 
            ||
| 872 | EgonEvMvGridDistrict.scenario_variation == scenario_var_name,  | 
            ||
| 873 | )  | 
            ||
| 874 | ev_count_alloc = (  | 
            ||
| 875 | pd.read_sql(query.statement, query.session.bind, index_col=None)  | 
            ||
| 876 | .iloc[0]  | 
            ||
| 877 | .ev_count  | 
            ||
| 878 | )  | 
            ||
| 879 | print(  | 
            ||
| 880 | f" EVs allocated to Grid Districts "  | 
            ||
| 881 |             f"(table: {EgonEvMvGridDistrict.__table__}) total count: " | 
            ||
| 882 |             f"{str(ev_count_alloc)}" | 
            ||
| 883 | )  | 
            ||
| 884 | |||
| 885 | # Compare with scenario target (only if not in testmode)  | 
            ||
| 886 | if TESTMODE_OFF:  | 
            ||
| 887 | np.testing.assert_allclose(  | 
            ||
| 888 | ev_count_alloc,  | 
            ||
| 889 | ev_count_target,  | 
            ||
| 890 | rtol=0.0001,  | 
            ||
| 891 | err_msg=(  | 
            ||
| 892 | "EV numbers allocated to Grid Districts seems to be "  | 
            ||
| 893 | "flawed."  | 
            ||
| 894 | ),  | 
            ||
| 895 | )  | 
            ||
| 896 | else:  | 
            ||
| 897 |             print("    Testmode is on, skipping sanity check...") | 
            ||
| 898 | |||
| 899 | return ev_count_alloc  | 
            ||
| 900 | |||
| 901 | def check_trip_data():  | 
            ||
| 902 | # Check if trips start at timestep 0 and have a max. of 35040 steps  | 
            ||
| 903 | # (8760h in 15min steps)  | 
            ||
| 904 |         print("  Checking timeranges...") | 
            ||
| 905 | with db.session_scope() as session:  | 
            ||
| 906 | query = session.query(  | 
            ||
| 907 |                 func.count(EgonEvTrip.event_id).label("cnt") | 
            ||
| 908 | ).filter(  | 
            ||
| 909 | or_(  | 
            ||
| 910 | and_(  | 
            ||
| 911 | EgonEvTrip.park_start > 0,  | 
            ||
| 912 | EgonEvTrip.simbev_event_id == 0,  | 
            ||
| 913 | ),  | 
            ||
| 914 | EgonEvTrip.park_end  | 
            ||
| 915 | > (60 / int(meta_run_config.stepsize)) * 8760,  | 
            ||
| 916 | ),  | 
            ||
| 917 | EgonEvTrip.scenario == scenario_name,  | 
            ||
| 918 | )  | 
            ||
| 919 | invalid_trips = pd.read_sql(  | 
            ||
| 920 | query.statement, query.session.bind, index_col=None  | 
            ||
| 921 | )  | 
            ||
| 922 | np.testing.assert_equal(  | 
            ||
| 923 | invalid_trips.iloc[0].cnt,  | 
            ||
| 924 | 0,  | 
            ||
| 925 | err_msg=(  | 
            ||
| 926 |                 f"{str(invalid_trips.iloc[0].cnt)} trips in table " | 
            ||
| 927 |                 f"{EgonEvTrip.__table__} have invalid timesteps." | 
            ||
| 928 | ),  | 
            ||
| 929 | )  | 
            ||
| 930 | |||
| 931 | # Check if charging demand can be covered by available charging energy  | 
            ||
| 932 | # while parking  | 
            ||
| 933 |         print("  Compare charging demand with available power...") | 
            ||
| 934 | with db.session_scope() as session:  | 
            ||
| 935 | query = session.query(  | 
            ||
| 936 |                 func.count(EgonEvTrip.event_id).label("cnt") | 
            ||
| 937 | ).filter(  | 
            ||
| 938 | func.round(  | 
            ||
| 939 | cast(  | 
            ||
| 940 | (EgonEvTrip.park_end - EgonEvTrip.park_start + 1)  | 
            ||
| 941 | * EgonEvTrip.charging_capacity_nominal  | 
            ||
| 942 | * (int(meta_run_config.stepsize) / 60),  | 
            ||
| 943 | Numeric,  | 
            ||
| 944 | ),  | 
            ||
| 945 | 3,  | 
            ||
| 946 | )  | 
            ||
| 947 | < cast(EgonEvTrip.charging_demand, Numeric),  | 
            ||
| 948 | EgonEvTrip.scenario == scenario_name,  | 
            ||
| 949 | )  | 
            ||
| 950 | invalid_trips = pd.read_sql(  | 
            ||
| 951 | query.statement, query.session.bind, index_col=None  | 
            ||
| 952 | )  | 
            ||
| 953 | np.testing.assert_equal(  | 
            ||
| 954 | invalid_trips.iloc[0].cnt,  | 
            ||
| 955 | 0,  | 
            ||
| 956 | err_msg=(  | 
            ||
| 957 |                 f"In {str(invalid_trips.iloc[0].cnt)} trips (table: " | 
            ||
| 958 |                 f"{EgonEvTrip.__table__}) the charging demand cannot be " | 
            ||
| 959 | f"covered by available charging power."  | 
            ||
| 960 | ),  | 
            ||
| 961 | )  | 
            ||
| 962 | |||
| 963 | def check_model_data():  | 
            ||
| 964 | # Check if model components were fully created  | 
            ||
| 965 |         print("  Check if all model components were created...") | 
            ||
| 966 | # Get MVGDs which got EV allocated  | 
            ||
| 967 | with db.session_scope() as session:  | 
            ||
| 968 | query = (  | 
            ||
| 969 | session.query(  | 
            ||
| 970 | EgonEvMvGridDistrict.bus_id,  | 
            ||
| 971 | )  | 
            ||
| 972 | .filter(  | 
            ||
| 973 | EgonEvMvGridDistrict.scenario == scenario_name,  | 
            ||
| 974 | EgonEvMvGridDistrict.scenario_variation  | 
            ||
| 975 | == scenario_var_name,  | 
            ||
| 976 | )  | 
            ||
| 977 | .group_by(EgonEvMvGridDistrict.bus_id)  | 
            ||
| 978 | )  | 
            ||
| 979 | mvgds_with_ev = (  | 
            ||
| 980 | pd.read_sql(query.statement, query.session.bind, index_col=None)  | 
            ||
| 981 | .bus_id.sort_values()  | 
            ||
| 982 | .to_list()  | 
            ||
| 983 | )  | 
            ||
| 984 | |||
| 985 | # Load model components  | 
            ||
| 986 | with db.session_scope() as session:  | 
            ||
| 987 | query = (  | 
            ||
| 988 | session.query(  | 
            ||
| 989 |                     EgonPfHvLink.bus0.label("mvgd_bus_id"), | 
            ||
| 990 |                     EgonPfHvLoad.bus.label("emob_bus_id"), | 
            ||
| 991 |                     EgonPfHvLoad.load_id.label("load_id"), | 
            ||
| 992 |                     EgonPfHvStore.store_id.label("store_id"), | 
            ||
| 993 | )  | 
            ||
| 994 | .select_from(EgonPfHvLoad, EgonPfHvStore)  | 
            ||
| 995 | .join(  | 
            ||
| 996 | EgonPfHvLoadTimeseries,  | 
            ||
| 997 | EgonPfHvLoadTimeseries.load_id == EgonPfHvLoad.load_id,  | 
            ||
| 998 | )  | 
            ||
| 999 | .join(  | 
            ||
| 1000 | EgonPfHvStoreTimeseries,  | 
            ||
| 1001 | EgonPfHvStoreTimeseries.store_id == EgonPfHvStore.store_id,  | 
            ||
| 1002 | )  | 
            ||
| 1003 | .filter(  | 
            ||
| 1004 | EgonPfHvLoad.carrier == "land transport EV",  | 
            ||
| 1005 | EgonPfHvLoad.scn_name == scenario_name,  | 
            ||
| 1006 | EgonPfHvLoadTimeseries.scn_name == scenario_name,  | 
            ||
| 1007 | EgonPfHvStore.carrier == "battery storage",  | 
            ||
| 1008 | EgonPfHvStore.scn_name == scenario_name,  | 
            ||
| 1009 | EgonPfHvStoreTimeseries.scn_name == scenario_name,  | 
            ||
| 1010 | EgonPfHvLink.scn_name == scenario_name,  | 
            ||
| 1011 | EgonPfHvLink.bus1 == EgonPfHvLoad.bus,  | 
            ||
| 1012 | EgonPfHvLink.bus1 == EgonPfHvStore.bus,  | 
            ||
| 1013 | )  | 
            ||
| 1014 | )  | 
            ||
| 1015 | model_components = pd.read_sql(  | 
            ||
| 1016 | query.statement, query.session.bind, index_col=None  | 
            ||
| 1017 | )  | 
            ||
| 1018 | |||
| 1019 | # Check number of buses with model components connected  | 
            ||
| 1020 | mvgd_buses_with_ev = model_components.loc[  | 
            ||
| 1021 | model_components.mvgd_bus_id.isin(mvgds_with_ev)  | 
            ||
| 1022 | ]  | 
            ||
| 1023 | np.testing.assert_equal(  | 
            ||
| 1024 | len(mvgds_with_ev),  | 
            ||
| 1025 | len(mvgd_buses_with_ev),  | 
            ||
| 1026 | err_msg=(  | 
            ||
| 1027 | f"Number of Grid Districts with connected model components "  | 
            ||
| 1028 |                 f"({str(len(mvgd_buses_with_ev))} in tables egon_etrago_*) " | 
            ||
| 1029 | f"differ from number of Grid Districts that got EVs "  | 
            ||
| 1030 |                 f"allocated ({len(mvgds_with_ev)} in table " | 
            ||
| 1031 |                 f"{EgonEvMvGridDistrict.__table__})." | 
            ||
| 1032 | ),  | 
            ||
| 1033 | )  | 
            ||
| 1034 | |||
| 1035 | # Check if all required components exist (if no id is NaN)  | 
            ||
| 1036 | np.testing.assert_equal(  | 
            ||
| 1037 | model_components.drop_duplicates().isna().any().any(),  | 
            ||
| 1038 | False,  | 
            ||
| 1039 | err_msg=(  | 
            ||
| 1040 | f"Some components are missing (see True values): "  | 
            ||
| 1041 |                 f"{model_components.drop_duplicates().isna().any()}" | 
            ||
| 1042 | ),  | 
            ||
| 1043 | )  | 
            ||
| 1044 | |||
| 1045 | # Get all model timeseries  | 
            ||
| 1046 |         print("  Loading model timeseries...") | 
            ||
| 1047 | # Get all model timeseries  | 
            ||
| 1048 |         model_ts_dict = { | 
            ||
| 1049 |             "Load": { | 
            ||
| 1050 | "carrier": "land transport EV",  | 
            ||
| 1051 | "table": EgonPfHvLoad,  | 
            ||
| 1052 | "table_ts": EgonPfHvLoadTimeseries,  | 
            ||
| 1053 | "column_id": "load_id",  | 
            ||
| 1054 | "columns_ts": ["p_set"],  | 
            ||
| 1055 | "ts": None,  | 
            ||
| 1056 | },  | 
            ||
| 1057 |             "Link": { | 
            ||
| 1058 | "carrier": "BEV charger",  | 
            ||
| 1059 | "table": EgonPfHvLink,  | 
            ||
| 1060 | "table_ts": EgonPfHvLinkTimeseries,  | 
            ||
| 1061 | "column_id": "link_id",  | 
            ||
| 1062 | "columns_ts": ["p_max_pu"],  | 
            ||
| 1063 | "ts": None,  | 
            ||
| 1064 | },  | 
            ||
| 1065 |             "Store": { | 
            ||
| 1066 | "carrier": "battery storage",  | 
            ||
| 1067 | "table": EgonPfHvStore,  | 
            ||
| 1068 | "table_ts": EgonPfHvStoreTimeseries,  | 
            ||
| 1069 | "column_id": "store_id",  | 
            ||
| 1070 | "columns_ts": ["e_min_pu", "e_max_pu"],  | 
            ||
| 1071 | "ts": None,  | 
            ||
| 1072 | },  | 
            ||
| 1073 | }  | 
            ||
| 1074 | |||
| 1075 | with db.session_scope() as session:  | 
            ||
| 1076 | for node, attrs in model_ts_dict.items():  | 
            ||
| 1077 |                 print(f"    Loading {node} timeseries...") | 
            ||
| 1078 | subquery = (  | 
            ||
| 1079 | session.query(getattr(attrs["table"], attrs["column_id"]))  | 
            ||
| 1080 | .filter(attrs["table"].carrier == attrs["carrier"])  | 
            ||
| 1081 | .filter(attrs["table"].scn_name == scenario_name)  | 
            ||
| 1082 | .subquery()  | 
            ||
| 1083 | )  | 
            ||
| 1084 | |||
| 1085 | cols = [  | 
            ||
| 1086 | getattr(attrs["table_ts"], c) for c in attrs["columns_ts"]  | 
            ||
| 1087 | ]  | 
            ||
| 1088 | query = session.query(  | 
            ||
| 1089 | getattr(attrs["table_ts"], attrs["column_id"]), *cols  | 
            ||
| 1090 | ).filter(  | 
            ||
| 1091 | getattr(attrs["table_ts"], attrs["column_id"]).in_(  | 
            ||
| 1092 | subquery  | 
            ||
| 1093 | ),  | 
            ||
| 1094 | attrs["table_ts"].scn_name == scenario_name,  | 
            ||
| 1095 | )  | 
            ||
| 1096 | attrs["ts"] = pd.read_sql(  | 
            ||
| 1097 | query.statement,  | 
            ||
| 1098 | query.session.bind,  | 
            ||
| 1099 | index_col=attrs["column_id"],  | 
            ||
| 1100 | )  | 
            ||
| 1101 | |||
| 1102 | # Check if all timeseries have 8760 steps  | 
            ||
| 1103 |         print("    Checking timeranges...") | 
            ||
| 1104 | for node, attrs in model_ts_dict.items():  | 
            ||
| 1105 | for col in attrs["columns_ts"]:  | 
            ||
| 1106 | ts = attrs["ts"]  | 
            ||
| 1107 | invalid_ts = ts.loc[ts[col].apply(lambda _: len(_)) != 8760][  | 
            ||
| 1108 | col  | 
            ||
| 1109 | ].apply(len)  | 
            ||
| 1110 | np.testing.assert_equal(  | 
            ||
| 1111 | len(invalid_ts),  | 
            ||
| 1112 | 0,  | 
            ||
| 1113 | err_msg=(  | 
            ||
| 1114 |                         f"{str(len(invalid_ts))} rows in timeseries do not " | 
            ||
| 1115 | f"have 8760 timesteps. Table: "  | 
            ||
| 1116 |                         f"{attrs['table_ts'].__table__}, Column: {col}, IDs: " | 
            ||
| 1117 |                         f"{str(list(invalid_ts.index))}" | 
            ||
| 1118 | ),  | 
            ||
| 1119 | )  | 
            ||
| 1120 | |||
| 1121 | # Compare total energy demand in model with some approximate values  | 
            ||
| 1122 | # (per EV: 14,000 km/a, 0.17 kWh/km)  | 
            ||
| 1123 |         print("  Checking energy demand in model...") | 
            ||
| 1124 | total_energy_model = (  | 
            ||
| 1125 | model_ts_dict["Load"]["ts"].p_set.apply(lambda _: sum(_)).sum()  | 
            ||
| 1126 | / 1e6  | 
            ||
| 1127 | )  | 
            ||
| 1128 |         print(f"    Total energy amount in model: {total_energy_model} TWh") | 
            ||
| 1129 | total_energy_scenario_approx = ev_count_alloc * 14000 * 0.17 / 1e9  | 
            ||
| 1130 | print(  | 
            ||
| 1131 | f" Total approximated energy amount in scenario: "  | 
            ||
| 1132 |             f"{total_energy_scenario_approx} TWh" | 
            ||
| 1133 | )  | 
            ||
| 1134 | np.testing.assert_allclose(  | 
            ||
| 1135 | total_energy_model,  | 
            ||
| 1136 | total_energy_scenario_approx,  | 
            ||
| 1137 | rtol=0.1,  | 
            ||
| 1138 | err_msg=(  | 
            ||
| 1139 | "The total energy amount in the model deviates heavily "  | 
            ||
| 1140 | "from the approximated value for current scenario."  | 
            ||
| 1141 | ),  | 
            ||
| 1142 | )  | 
            ||
| 1143 | |||
| 1144 | # Compare total storage capacity  | 
            ||
| 1145 |         print("  Checking storage capacity...") | 
            ||
| 1146 | # Load storage capacities from model  | 
            ||
| 1147 | with db.session_scope() as session:  | 
            ||
| 1148 | query = session.query(  | 
            ||
| 1149 |                 func.sum(EgonPfHvStore.e_nom).label("e_nom") | 
            ||
| 1150 | ).filter(  | 
            ||
| 1151 | EgonPfHvStore.scn_name == scenario_name,  | 
            ||
| 1152 | EgonPfHvStore.carrier == "battery storage",  | 
            ||
| 1153 | )  | 
            ||
| 1154 | storage_capacity_model = (  | 
            ||
| 1155 | pd.read_sql(  | 
            ||
| 1156 | query.statement, query.session.bind, index_col=None  | 
            ||
| 1157 | ).e_nom.sum()  | 
            ||
| 1158 | / 1e3  | 
            ||
| 1159 | )  | 
            ||
| 1160 | print(  | 
            ||
| 1161 |             f"    Total storage capacity ({EgonPfHvStore.__table__}): " | 
            ||
| 1162 |             f"{round(storage_capacity_model, 1)} GWh" | 
            ||
| 1163 | )  | 
            ||
| 1164 | |||
| 1165 | # Load occurences of each EV  | 
            ||
| 1166 | with db.session_scope() as session:  | 
            ||
| 1167 | query = (  | 
            ||
| 1168 | session.query(  | 
            ||
| 1169 | EgonEvMvGridDistrict.bus_id,  | 
            ||
| 1170 | EgonEvPool.type,  | 
            ||
| 1171 | func.count(EgonEvMvGridDistrict.egon_ev_pool_ev_id).label(  | 
            ||
| 1172 | "count"  | 
            ||
| 1173 | ),  | 
            ||
| 1174 | )  | 
            ||
| 1175 | .join(  | 
            ||
| 1176 | EgonEvPool,  | 
            ||
| 1177 | EgonEvPool.ev_id  | 
            ||
| 1178 | == EgonEvMvGridDistrict.egon_ev_pool_ev_id,  | 
            ||
| 1179 | )  | 
            ||
| 1180 | .filter(  | 
            ||
| 1181 | EgonEvMvGridDistrict.scenario == scenario_name,  | 
            ||
| 1182 | EgonEvMvGridDistrict.scenario_variation  | 
            ||
| 1183 | == scenario_var_name,  | 
            ||
| 1184 | EgonEvPool.scenario == scenario_name,  | 
            ||
| 1185 | )  | 
            ||
| 1186 | .group_by(EgonEvMvGridDistrict.bus_id, EgonEvPool.type)  | 
            ||
| 1187 | )  | 
            ||
| 1188 | count_per_ev_all = pd.read_sql(  | 
            ||
| 1189 | query.statement, query.session.bind, index_col="bus_id"  | 
            ||
| 1190 | )  | 
            ||
| 1191 | count_per_ev_all["bat_cap"] = count_per_ev_all.type.map(  | 
            ||
| 1192 | meta_tech_data.battery_capacity  | 
            ||
| 1193 | )  | 
            ||
| 1194 | count_per_ev_all["bat_cap_total_MWh"] = (  | 
            ||
| 1195 | count_per_ev_all["count"] * count_per_ev_all.bat_cap / 1e3  | 
            ||
| 1196 | )  | 
            ||
| 1197 | storage_capacity_simbev = count_per_ev_all.bat_cap_total_MWh.div(  | 
            ||
| 1198 | 1e3  | 
            ||
| 1199 | ).sum()  | 
            ||
| 1200 | print(  | 
            ||
| 1201 | f" Total storage capacity (simBEV): "  | 
            ||
| 1202 |             f"{round(storage_capacity_simbev, 1)} GWh" | 
            ||
| 1203 | )  | 
            ||
| 1204 | |||
| 1205 | np.testing.assert_allclose(  | 
            ||
| 1206 | storage_capacity_model,  | 
            ||
| 1207 | storage_capacity_simbev,  | 
            ||
| 1208 | rtol=0.01,  | 
            ||
| 1209 | err_msg=(  | 
            ||
| 1210 | "The total storage capacity in the model deviates heavily "  | 
            ||
| 1211 | "from the input data provided by simBEV for current scenario."  | 
            ||
| 1212 | ),  | 
            ||
| 1213 | )  | 
            ||
| 1214 | |||
| 1215 | # Check SoC storage constraint: e_min_pu < e_max_pu for all timesteps  | 
            ||
| 1216 |         print("  Validating SoC constraints...") | 
            ||
| 1217 | stores_with_invalid_soc = []  | 
            ||
| 1218 | for idx, row in model_ts_dict["Store"]["ts"].iterrows():  | 
            ||
| 1219 | ts = row[["e_min_pu", "e_max_pu"]]  | 
            ||
| 1220 | x = np.array(ts.e_min_pu) > np.array(ts.e_max_pu)  | 
            ||
| 1221 | if x.any():  | 
            ||
| 1222 | stores_with_invalid_soc.append(idx)  | 
            ||
| 1223 | |||
| 1224 | np.testing.assert_equal(  | 
            ||
| 1225 | len(stores_with_invalid_soc),  | 
            ||
| 1226 | 0,  | 
            ||
| 1227 | err_msg=(  | 
            ||
| 1228 | f"The store constraint e_min_pu < e_max_pu does not apply "  | 
            ||
| 1229 |                 f"for some storages in {EgonPfHvStoreTimeseries.__table__}. " | 
            ||
| 1230 |                 f"Invalid store_ids: {stores_with_invalid_soc}" | 
            ||
| 1231 | ),  | 
            ||
| 1232 | )  | 
            ||
| 1233 | |||
| 1234 | def check_model_data_lowflex_eGon2035():  | 
            ||
| 1235 | # TODO: Add eGon100RE_lowflex  | 
            ||
| 1236 |         print("") | 
            ||
| 1237 |         print("SCENARIO: eGon2035_lowflex") | 
            ||
| 1238 | |||
| 1239 | # Compare driving load and charging load  | 
            ||
| 1240 |         print("  Loading eGon2035 model timeseries: driving load...") | 
            ||
| 1241 | with db.session_scope() as session:  | 
            ||
| 1242 | query = (  | 
            ||
| 1243 | session.query(  | 
            ||
| 1244 | EgonPfHvLoad.load_id,  | 
            ||
| 1245 | EgonPfHvLoadTimeseries.p_set,  | 
            ||
| 1246 | )  | 
            ||
| 1247 | .join(  | 
            ||
| 1248 | EgonPfHvLoadTimeseries,  | 
            ||
| 1249 | EgonPfHvLoadTimeseries.load_id == EgonPfHvLoad.load_id,  | 
            ||
| 1250 | )  | 
            ||
| 1251 | .filter(  | 
            ||
| 1252 | EgonPfHvLoad.carrier == "land transport EV",  | 
            ||
| 1253 | EgonPfHvLoad.scn_name == "eGon2035",  | 
            ||
| 1254 | EgonPfHvLoadTimeseries.scn_name == "eGon2035",  | 
            ||
| 1255 | )  | 
            ||
| 1256 | )  | 
            ||
| 1257 | model_driving_load = pd.read_sql(  | 
            ||
| 1258 | query.statement, query.session.bind, index_col=None  | 
            ||
| 1259 | )  | 
            ||
| 1260 | driving_load = np.array(model_driving_load.p_set.to_list()).sum(axis=0)  | 
            ||
| 1261 | |||
| 1262 | print(  | 
            ||
| 1263 | " Loading eGon2035_lowflex model timeseries: dumb charging "  | 
            ||
| 1264 | "load..."  | 
            ||
| 1265 | )  | 
            ||
| 1266 | with db.session_scope() as session:  | 
            ||
| 1267 | query = (  | 
            ||
| 1268 | session.query(  | 
            ||
| 1269 | EgonPfHvLoad.load_id,  | 
            ||
| 1270 | EgonPfHvLoadTimeseries.p_set,  | 
            ||
| 1271 | )  | 
            ||
| 1272 | .join(  | 
            ||
| 1273 | EgonPfHvLoadTimeseries,  | 
            ||
| 1274 | EgonPfHvLoadTimeseries.load_id == EgonPfHvLoad.load_id,  | 
            ||
| 1275 | )  | 
            ||
| 1276 | .filter(  | 
            ||
| 1277 | EgonPfHvLoad.carrier == "land transport EV",  | 
            ||
| 1278 | EgonPfHvLoad.scn_name == "eGon2035_lowflex",  | 
            ||
| 1279 | EgonPfHvLoadTimeseries.scn_name == "eGon2035_lowflex",  | 
            ||
| 1280 | )  | 
            ||
| 1281 | )  | 
            ||
| 1282 | model_charging_load_lowflex = pd.read_sql(  | 
            ||
| 1283 | query.statement, query.session.bind, index_col=None  | 
            ||
| 1284 | )  | 
            ||
| 1285 | charging_load = np.array(  | 
            ||
| 1286 | model_charging_load_lowflex.p_set.to_list()  | 
            ||
| 1287 | ).sum(axis=0)  | 
            ||
| 1288 | |||
| 1289 | # Ratio of driving and charging load should be 0.9 due to charging  | 
            ||
| 1290 | # efficiency  | 
            ||
| 1291 |         print("  Compare cumulative loads...") | 
            ||
| 1292 |         print(f"    Driving load (eGon2035): {driving_load.sum() / 1e6} TWh") | 
            ||
| 1293 | print(  | 
            ||
| 1294 | f" Dumb charging load (eGon2035_lowflex): "  | 
            ||
| 1295 |             f"{charging_load.sum() / 1e6} TWh" | 
            ||
| 1296 | )  | 
            ||
| 1297 | driving_load_theoretical = (  | 
            ||
| 1298 | float(meta_run_config.eta_cp) * charging_load.sum()  | 
            ||
| 1299 | )  | 
            ||
| 1300 | np.testing.assert_allclose(  | 
            ||
| 1301 | driving_load.sum(),  | 
            ||
| 1302 | driving_load_theoretical,  | 
            ||
| 1303 | rtol=0.01,  | 
            ||
| 1304 | err_msg=(  | 
            ||
| 1305 | f"The driving load (eGon2035) deviates by more than 1% "  | 
            ||
| 1306 | f"from the theoretical driving load calculated from charging "  | 
            ||
| 1307 | f"load (eGon2035_lowflex) with an efficiency of "  | 
            ||
| 1308 |                 f"{float(meta_run_config.eta_cp)}." | 
            ||
| 1309 | ),  | 
            ||
| 1310 | )  | 
            ||
| 1311 | |||
| 1312 |     print("=====================================================") | 
            ||
| 1313 |     print("=== SANITY CHECKS FOR MOTORIZED INDIVIDUAL TRAVEL ===") | 
            ||
| 1314 |     print("=====================================================") | 
            ||
| 1315 | |||
| 1316 | for scenario_name in ["eGon2035", "eGon100RE"]:  | 
            ||
| 1317 | scenario_var_name = DATASET_CFG["scenario"]["variation"][scenario_name]  | 
            ||
| 1318 | |||
| 1319 |         print("") | 
            ||
| 1320 |         print(f"SCENARIO: {scenario_name}, VARIATION: {scenario_var_name}") | 
            ||
| 1321 | |||
| 1322 | # Load scenario params for scenario and scenario variation  | 
            ||
| 1323 | scenario_variation_parameters = get_sector_parameters(  | 
            ||
| 1324 | "mobility", scenario=scenario_name  | 
            ||
| 1325 | )["motorized_individual_travel"][scenario_var_name]  | 
            ||
| 1326 | |||
| 1327 | # Load simBEV run config and tech data  | 
            ||
| 1328 | meta_run_config = read_simbev_metadata_file(  | 
            ||
| 1329 | scenario_name, "config"  | 
            ||
| 1330 | ).loc["basic"]  | 
            ||
| 1331 | meta_tech_data = read_simbev_metadata_file(scenario_name, "tech_data")  | 
            ||
| 1332 | |||
| 1333 |         print("") | 
            ||
| 1334 |         print("Checking EV counts...") | 
            ||
| 1335 | ev_count_alloc = check_ev_allocation()  | 
            ||
| 1336 | |||
| 1337 |         print("") | 
            ||
| 1338 |         print("Checking trip data...") | 
            ||
| 1339 | check_trip_data()  | 
            ||
| 1340 | |||
| 1341 |         print("") | 
            ||
| 1342 |         print("Checking model data...") | 
            ||
| 1343 | check_model_data()  | 
            ||
| 1344 | |||
| 1345 |     print("") | 
            ||
| 1346 | check_model_data_lowflex_eGon2035()  | 
            ||
| 1347 | |||
| 1348 |     print("=====================================================") | 
            ||
| 1349 | |||
| 1394 |